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
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");
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.
prevent multiple instances of an application
Jeroen Alblas
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();
}
Mark Pitman
that works great. how would i set focus to the previous instances.
thanks
Drew Marsh
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.
Shihan
SoopahMan
Cool, I knew I was fairly close :)