Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bring another processes Window to foreground when it has ShowInTaskbar = false

Tags:

c#

winforms

We only want one instance of our app running at any one time. So on start up it looks to see if the app is running and if it is, it calls SetForegroundWindow on the Main Window.

This is all good and well ... for the most part..

When our app starts up it will show a Splash screen and a Logon form. Both of these forms have ShowInTaskBar = false.

Because of this, if you try to start up another copy of the app when the Logon form is showing, that Logon form is not brought to the front!

Especially as the user cant see anything in the taskbar as well, all they figure is that the app is duff and cannot start. There is no indication that there is another instance running.

Is there any way around this problem?

like image 453
Mongus Pong Avatar asked Apr 14 '10 10:04

Mongus Pong


2 Answers

Well, code is here. Even if the ShowInTaskBar is false, you should be able to bring it to the front.

    [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]     public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);      [DllImport("USER32.DLL")]     public static extern bool SetForegroundWindow(IntPtr hWnd);      public static void bringToFront(string title) {         // Get a handle to the Calculator application.         IntPtr handle = FindWindow(null, title);          // Verify that Calculator is a running process.         if (handle == IntPtr.Zero) {             return;         }          // Make Calculator the foreground application         SetForegroundWindow(handle);     } 

Note: you should FindWindow using the form's class and not by name as the splash screen forms sometimes do not have titles or even the controlbox. Use Spy++ to dig deeper.

Use FindWindow on splash. I think this is what you want to do - bring the splash screen in front while loading of the main form.

like image 54
Nayan Avatar answered Sep 20 '22 08:09

Nayan


I think this is the better solution because its restores from minimized state:

public static class WindowHelper {     public static void BringProcessToFront(Process process)     {         IntPtr handle = process.MainWindowHandle;         if (IsIconic(handle))         {             ShowWindow(handle, SW_RESTORE);         }          SetForegroundWindow(handle);     }      const int SW_RESTORE = 9;      [System.Runtime.InteropServices.DllImport("User32.dll")]     private static extern bool SetForegroundWindow(IntPtr handle);     [System.Runtime.InteropServices.DllImport("User32.dll")]     private static extern bool ShowWindow(IntPtr handle, int nCmdShow);     [System.Runtime.InteropServices.DllImport("User32.dll")]     private static extern bool IsIconic(IntPtr handle); } 

Simple call:

WindowHelper.BringProcessToFront(process); 
like image 29
Suplanus Avatar answered Sep 21 '22 08:09

Suplanus