Single instance Application
How can I make sure only a single instance of my application can run?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Kirtan PatelPosted Jan 18, 2010, 8:23 PM
if my answer helps you than check "Do you like this answer" check box :)
Marshall NeillPosted Mar 21, 2010, 5:09 PM
using System;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Control_Center {
static class Program {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
///
/// The main entry point for the application.
///
[STAThread]
static void Main() {
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "Control Center", out createdNew)) {
if (createdNew) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmCC());
}
else {
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName)) {
if (process.Id != current.Id) {
SetForegroundWindow(process.MainWindowHandle);
ShowWindowAsync(process.MainWindowHandle,1);
break;
}
}
}
}
}
}
}
Sam HobbsPosted Jan 21, 2010, 3:31 PM
I understand and agree that it is customary to activate an existing instance in situations such as that. If Patrick wanted that then we could solve that problem too.
theLizardPosted Jan 19, 2010, 8:12 PM
patrickPosted Jan 19, 2010, 4:28 PM
theLizardPosted Jan 19, 2010, 3:16 PM
theLizardPosted Jan 19, 2010, 3:16 PM
Sam HobbsPosted Jan 19, 2010, 12:50 AM
Note that you need to also do the following after the "Application.Run(new Form1());":
That line is not important for small programs, but always use it anyway.
Sam HobbsPosted Jan 18, 2010, 6:44 PM
If that is not enough, then search the msdn for "single instance"; I hope that is enough.