Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a WinForms Form with TopMost = true but not having it steal focus?

Tags:

I have a form that pops up on a user's screen and has TopMost=true, but it steals the focus. How can I get it to not steal focus when it first appears?

like image 608
sooprise Avatar asked Sep 16 '10 19:09

sooprise


People also ask

What is the replacement for WinForms?

WPF, would be your answer to Windows Forms if you are on the . NET platform.

Will WinForms be deprecated?

WinForms won't be deprecated until Win32 is ... which could be quite sometime! WPF on the other hand has few direct dependencies on Win32 so could potentially form the basis of a "fresh start" UI layer on a future version of windows.

How do I hide winform?

If you Don't want the user to be able to see the app at all set this: this. ShowInTaskbar = false; Then they won't be able to see the form in the task bar and it will be invisible.


2 Answers

This is what worked for me. It provides TopMost but without focus-stealing.

    protected override bool ShowWithoutActivation
    {
       get { return true; }
    }

    private const int WS_EX_TOPMOST = 0x00000008;
    protected override CreateParams CreateParams
    {
       get
       {
          CreateParams createParams = base.CreateParams;
          createParams.ExStyle |= WS_EX_TOPMOST;
          return createParams;
       }
    }

Remember to omit setting TopMost in Visual Studio designer, or elsewhere.

This is stolen, err, borrowed, from here (click on Workarounds):

https://connect.microsoft.com/VisualStudio/feedback/details/401311/showwithoutactivation-is-not-supported-with-topmost

like image 191
RenniePet Avatar answered Sep 20 '22 10:09

RenniePet


Paste this code in your form:

protected override bool ShowWithoutActivation
{
    get { return true; }
}
like image 42
Hans Passant Avatar answered Sep 20 '22 10:09

Hans Passant