2

I am having a problem where my main form loses focus when opening a new form. I know I can revert the focus back by using mainForm.focus(), but how do I handle things if I want the main form to never give up its focus when new window is opened?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
RGB
  • 51
  • 1
  • 4
  • 1
    possible duplicate of [Show a Form without stealing focus (in C#)](http://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c) – Cody Gray - on strike Jan 13 '11 at 10:40
  • 1
    Possible duplicate of [Show a Form without stealing focus?](http://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus) – Nathan Van Dyken May 17 '17 at 14:58

2 Answers2

5

You can accomplish this by overriding the property ShowWithoutActivation in order for it to return true in the forms that you want to show without stealing focus from the form that shown it, in your case that would be your main form.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • Note that you have to override this property for each form that you want to be shown without activation, not on your main form. Otherwise, precisely correct. +1 – Cody Gray - on strike Jan 13 '11 at 10:39
2

Cody Gray answered this, I'm just expanding it by directly pasting the code. Someone with edit rights can copy it over there and delete this for all I care ;)

pinvoke.net's ShowWindow method.:

    private const int SW_SHOWNOACTIVATE = 4;
    private const int HWND_TOPMOST = -1;
    private const uint SWP_NOACTIVATE = 0x0010;

    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    static extern bool SetWindowPos(
         int hWnd,           // window handle
         int hWndInsertAfter,    // placement-order handle
         int X,          // horizontal position
         int Y,          // vertical position
         int cx,         // width
         int cy,         // height
         uint uFlags);       // window positioning flags

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    static void ShowInactiveTopmost(Form frm)
    {
        ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);
        SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,frm.Left, frm.Top, frm.Width, frm.Height,SWP_NOACTIVATE);
        frm.TopMost = false;
    }
RGB
  • 51
  • 1
  • 4