Showing a topmost form without deactivating current active form

 

Q: Is there a way to show a borderless, topmost form on the screen without deactivating the current active form?

A: I bet your first instinct is to go with ShowWindow and specifying SW_SHOWNA, it was mine as well. Unfortunately it does not work. It appears that when you specify that a form is top most and you call Show() on it the form actually gets activated. The same thing occurs when you call the ShowWindow() API. If you modify the form so that it is not top most ShowWindow with SW_SHOWNA works just as you expect. I did not spend too much time investigating the cause for this but was able to find a way to make this work.

Instead of specifying the Topmost property of the form to be true at design time set it to false. Then, what you want to do is in the constructor for the form modify the style of the window using SetWindowLong() and then set the Topmost property.

Here’s the code you want to add to the constructor and the necessary API declares:

// Code to be added to the topmost form's constructor

                  SetWindowLong(this.Handle, GWL_EXSTYLE, GetWindowLong(this.Handle, GWL_EXSTYLE) | WS_EX_TOPMOST);

                     this.TopMost = true;

            // API Declarations

            [DllImport("user32.dll")]

            public static extern Int32 GetWindowLong(IntPtr hwnd, int nIndex);

            [DllImport("user32.dll")]

            public static extern Int32 SetWindowLong(IntPtr hwnd, int nIndex, Int32 dwNewLong);

            const int GWL_EXSTYLE = -20;

            const int WS_EX_TOPMOST = 0x8;

            const int SW_SHOWNA = 8;

            const int SW_NORMAL = 1;

            const int SW_SHOWNOACTIVATE = 4;