简体   繁体   English

在SetWindowPos()中获取跨线程操作无效

[英]Getting Cross-thread operation not valid in SetWindowPos()

I am trying to access a form from a different thread to that on which the form was created, and finally ended up with an error: 我试图从一个不同的线程访问一个表单到创建表单的表单,最后得到一个错误:

Cross thread operation not valid 跨线程操作无效

Code: 码:

public static void MakeTopMost(Form form)
{
    SetWindowPos(form.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}

I am passing a form which is running in another thread. 我正在传递一个在另一个线程中运行的表单。 I tried testing InvokeRequired , but it is always false. 我试过测试InvokeRequired ,但它总是假的。

I am new to threading. 我是线程新手。

Make sure you are testing the right object for InvokeRequired : 确保您正在为InvokeRequired测试正确的对象:

public static void MakeTopMost(Form form)
{
    if (form.InvokeRequired)
    {
        form.Invoke((Action)delegate { MakeTopMost(form); });
        return;
    }

    SetWindowPos(form.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}

I like to wrap all of this up with an extension method like this: 我喜欢用这样的扩展方法包装所有这些:

public static class SynchronizeInvokeUtil
{
    public static void SafeInvoke(this ISynchroniseInvoke sync, Action action)
    {
        if (sync.InvokeRequired)
            sync.Invoke(action);
        else
            action();
    }

    public static void SafeBeginInvoke(this ISynchroniseInvoke sync, 
                                       Action action)
    {
        if (sync.InvokeRequired)
            sync.BeginInvoke(action);
        else
            action();
    }
}

You can then just call: 然后你可以打电话:

form.SafeInvoke(() => SetWindowPos(form.Handle, HWND_TOPMOST, 
                                   0, 0, 0, 0, TOPMOST_FLAGS));

Which is probably the most readable. 这可能是最具可读性的。

Note that if you are using this within the form class itself, you have to use this.SafeInvoke(...) in order to access the extension method. 请注意,如果您在表单类本身中使用它,则必须使用this.SafeInvoke(...)才能访问扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM