简体   繁体   中英

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.

I am new to threading.

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();
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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