Skip to content

Instantly share code, notes, and snippets.

@gamlerhart
Created February 14, 2011 21:57
Show Gist options
  • Save gamlerhart/826642 to your computer and use it in GitHub Desktop.
Save gamlerhart/826642 to your computer and use it in GitHub Desktop.
A global mutex across the machine
public class Program
{
static readonly Mutex mutex = new Mutex(true,
"YourCompany-YourApp-SingleInstance-" + Environment.UserName);
[STAThread]
public static void Main(string[] args)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
try
{
// now we start the real application.
// in this case a WPF-app.
new App().Run();
} finally
{
mutex.ReleaseMutex();
}
}
else
{
FocusSwitcher.SwitchToCurrent();
}
}
}
public class FocusSwitcher
{
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int SW_MAXIMIZE = 3;
public static void SwitchToCurrent()
{
var hWnd = IntPtr.Zero;
var thisProcess = Process.GetCurrentProcess();
var processes = Process.GetProcessesByName(thisProcess.ProcessName)
.Where(p=>p.Id != thisProcess.Id);
foreach (Process runningProcesses in processes)
{
// Get the first instance that is not this instance, has the
// same process name and was started from the same file name
// and location. Also check that the process has a valid
// window handle in this session to filter out other user's
// processes.
if (runningProcesses.MainModule.FileName == thisProcess.MainModule.FileName &&
runningProcesses.MainWindowHandle != IntPtr.Zero)
{
hWnd = runningProcesses.MainWindowHandle;
ShowWindowAsync(new HandleRef(null, hWnd), SW_MAXIMIZE);
SetForegroundWindow(hWnd);
break;
}
}
}
}
var mutex = new Mutex(true,
"YourCompany-YourApp-SingleInstance-" + Environment.UserName);
var mutex = new Mutex(true,
"YourCompany-YourApp-SingleInstance");
public class Program
{
static readonly Mutex mutex = new Mutex(true,
"YourCompany-YourApp-SingleInstance-" + Environment.UserName);
[STAThread]
public static void Main(string[] args)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
try
{
// now we start the real application.
// in this case a WPF-app.
new App().Run();
} finally
{
mutex.ReleaseMutex();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment