Hello.
I have an application which I check to see if there is another running instance at startup. If there is another running instance, I set focus to the existing instance. I am using code that I found on a webpage to do this (Code I am using is at the bottom of this post). When the application is minimized, the form is hidden and an icon appears in the System Tray. My problem is that when I run another instance, the new instance attempts to set focus to the hidden window. The window does not reappear. Can I modify the code to not only make sure that the window is in focus, but to Show the window as well?
Thanks.
-Joe
I have an application which I check to see if there is another running instance at startup. If there is another running instance, I set focus to the existing instance. I am using code that I found on a webpage to do this (Code I am using is at the bottom of this post). When the application is minimized, the form is hidden and an icon appears in the System Tray. My problem is that when I run another instance, the new instance attempts to set focus to the hidden window. The window does not reappear. Can I modify the code to not only make sure that the window is in focus, but to Show the window as well?
Thanks.
-Joe
Code:
[STAThread]
static void Main()
{
//Get the running instance.
Process instance = RunningInstance();
if (instance == null)
{
//There isn't another instance, show our form.
Application.Run (new frmMain());
}
else
{
//There is another instance of this process.
HandleRunningInstance(instance);
}
}
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName
(current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
public static void HandleRunningInstance(Process instance)
{
//Make sure the window is not minimized or maximized
ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);
//Set the real intance to foreground window
SetForegroundWindow (instance.MainWindowHandle);
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(
IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")] private static extern bool
SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;