获得跨线程操作SetWindowPos无效() [英] Getting Cross-thread operation not valid in SetWindowPos()

查看:1034
本文介绍了获得跨线程操作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:

跨线程操作无效

code:

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

我传递这是在另一个线程中运行的一种形式。我试图测试 InvokeRequired ,但它始终是假的。

I am passing a form which is running in another thread. I tried testing InvokeRequired, but it is always false.

我是新来的线程。

推荐答案

请确保您正在测试正确的对象为 InvokeRequired

Make sure you are testing the right object for 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();
    }
}

您可以就可以致电:

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

这可能是最可读的。

Which is probably the most readable.

请注意,如果您的窗体类本身中使用这一点,你必须使用 this.SafeInvoke(...),以访问扩展方法。

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.

这篇关于获得跨线程操作SetWindowPos无效()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆