Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static void Main()
- {
- string mutex_id = "MY_APP";
- using (Mutex mutex = new Mutex(false, mutex_id))
- {
- if (!mutex.WaitOne(0, false))
- {
- MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
- return;
- }
- // Do stuff
- }
- }
- private static bool AlreadyRunning()
- {
- Process[] processes = Process.GetProcesses();
- Process currentProc = Process.GetCurrentProcess();
- foreach (Process process in processes)
- {
- try
- {
- if (process.Modules[0].FileName == System.Reflection.Assembly.GetExecutingAssembly().Location
- && currentProc.Id != process.Id)
- return true;
- }
- catch (Exception)
- {
- }
- }
- return false;
- }
- private static bool AlreadyRunning()
- {
- Process[] processes = Process.GetProcesses();
- Process currentProc = Process.GetCurrentProcess();
- logger.LogDebug("Current proccess: {0}", currentProc.ProcessName);
- foreach (Process process in processes)
- {
- if (currentProc.ProcessName == process.ProcessName && currentProc.Id != process.Id)
- {
- logger.LogInformation("Another instance of this process is already running: {pid}", process.Id);
- return true;
- }
- }
- return false;
- }
- bool createdNew;
- using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
- {
- if (createdNew) {
- // process
- }
- else {
- // in my case, quietly exit
- }
- }
Add Comment
Please, Sign In to add comment