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.