prevent multiple instances of an application  
Author Message
Job Lot





PostPosted: Visual C# General, prevent multiple instances of an application Top

How can I prevent multiple instances of a C# windows forms application. VB.NET provides My.Application.StartupNextInstance Event to do this. Is there any C# equivalent as well

Thanks



Visual C#15  
 
 
ahmedilyas





PostPosted: Visual C# General, prevent multiple instances of an application Top

you could do this...

Process[] theProcesses = System.Diagnostics.Process.GetProcessesByName(Application.ProductName); //maybe add .exe at the end of Application.ProductName

if (theProcesses.Length > 1)

{

MessageBox.Show("There is already another instance of the application running");

Application.Exit();

}



 
 
Job Lot





PostPosted: Visual C# General, prevent multiple instances of an application Top

that works great. how would i set focus to the previous instances.

thanks



 
 
Paul Louth





PostPosted: Visual C# General, prevent multiple instances of an application Top

I haven't managed to get this to work.  But maybe this will help you go in the right direction.

First, create an extern to PostMessage:

[DllImport("User32.Dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);

Then call that with the window handle of the process you're trying to open with the relevant windows message:

IntPtr hWnd = Process.GetProcessesByName("iexplore")[0].MainWindowHandle;
PostMessage(hWnd, 0x18, 0, 0);

(where 0x18 == WM_SHOWWINDOW)

Like I say, I haven't got this working yet.  But it seems like a plausible method.  Unfortunately I don't have more time to look into this for you.

 


 
 
Peter Ritchie





PostPosted: Visual C# General, prevent multiple instances of an application Top

You can use the Process object's MainWindowHandle member and PInvoke the ShowWindow and UpdateWindow Win32 functions. See the Restoring a Previous Instance section at http://www.codeproject.com/csharp/SingleInstanceApplication.asp which contains some information on single instance applications.

 
 
Paul Louth





PostPosted: Visual C# General, prevent multiple instances of an application Top

Cool, I knew I was fairly close :)