Created
October 6, 2011 09:51
-
-
Save manicai/1266999 to your computer and use it in GitHub Desktop.
Single instance of a application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
using System.Threading; | |
using System.Windows.Forms; | |
namespace Child | |
{ | |
static class Program | |
{ | |
private static readonly string MutexName = @"Global\Child-Instance-98E99708-0FE1-4310-93C5-00B10BB5605D"; | |
[STAThread] | |
static void Main() | |
{ | |
using (Mutex m = new Mutex(false, MutexName)) | |
{ | |
if (m.WaitOne(1)) | |
{ | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(new Form1()); | |
} | |
else | |
{ | |
RaiseOtherInstance(); | |
} | |
} | |
} | |
[DllImport("user32.dll")] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
static extern bool SetForegroundWindow(IntPtr hWnd); | |
private static void RaiseOtherInstance() | |
{ | |
Process me = Process.GetCurrentProcess(); | |
foreach (Process process in Process.GetProcessesByName(me.ProcessName)) | |
{ | |
if (process.Id != me.Id) | |
{ | |
SetForegroundWindow(process.MainWindowHandle); | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment