Form.TopMost works sometimes
It appears that the topmost property sometimes puts my开发者_如何学编程 application above all others, but throughout my testing it has been very weird in that sometimes it works and the window remains above all other (external application) windows, but sometimes it does nothing at all. I have even tried using the WS_EX_TOPMOST flag by setting it with the Win32 API call to setWindowLong(). None of them keep the window on top. Is there another way to keep a window on top of every open window besides using topmost? Or is there something else I should know about topmost?
I simply use this:
form.TopLevel = true;
form.TopMost = true;
which makes the window top-level (i.e. it has no parent and behaves as the main form of the application), then ensures that it is topmost (i.e. displays above all other non-topmost windows). It has always worked like a charm.
Note that I do this before I show the window.
I've had luck with the following win32 api calls:
const int SW_SHOW = 5;
BringWindowToTop(form.Handle);
ShowWindow(form.Handle, SW_SHOW);
In addition to Form.TopMost
you can try the Win32 API SetForegroundWindow.
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
Then call SetForegroundWindow(this.Handle)
.
Works 100%!
User32.AllowSetForegroundWindow((uint)Process.GetCurrentProcess().Id);
User32.SetForegroundWindow(Handle);
User32.ShowWindow(Handle, User32.SW_SHOWNORMAL);
精彩评论