Search code examples
c#winformsfocuswindowstate

C# FormWindowState.Normal not to steal focus


I have a Windows Form Application that will go to system tray when it is minimized. When I received a message to pop-up my application it will call ShowWindowFromTray() function. I do not want to steal focus on the application that has the focus because it might interrupts on what the user is doing.

private void ShowWindowFromTray()
{
    this.Show();
    this.WindowState = FormWindowState.Normal;
}

BTW this application has option that the users can check if the application will always on top or TopMost on all other windows.


Solution

  • Instead of Show(), use the ShowWindow() API with SW_SHOWNA:

        private const int SW_SHOWNA = 4;
    
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
        private void ShowWindowFromTray()
        {
            ShowWindow(this.Handle, SW_SHOWNA);
        }