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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Kirtan PatelRank #292 · 8.6K reputationPosted Jan 18, 2010, 3:23 PM EST
private bool IsSingleInstance() { foreach (Process process in Process.GetProcesses()) { if (process.MainWindowTitle == this.Text) return false; } return true; }Sam HobbsRank #107 · 20.5K reputationPosted Jan 18, 2010, 1:44 PM EST
If that is not enough, then search the msdn for "single instance"; I hope that is enough.
Sam HobbsRank #107 · 20.5K reputationPosted Jan 18, 2010, 7:50 PM EST
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.
theLizardRank #1,079 · 1.8K reputationPosted Jan 19, 2010, 10:16 AM EST
theLizardRank #1,079 · 1.8K reputationPosted Jan 19, 2010, 10:16 AM EST
patrickRank #4,458 · 342 reputationPosted Jan 19, 2010, 11:28 AM EST
theLizardRank #1,079 · 1.8K reputationPosted Jan 19, 2010, 3:12 PM EST
Sam HobbsRank #107 · 20.5K reputationPosted Jan 21, 2010, 10:31 AM EST
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.
Marshall Neill2 reputationPosted Mar 21, 2010, 1:09 PM EDT
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;
}
}
}
}
}
}
}