Single Instance Application
CodeKeep C# Feed Gennaio 26th, 2008
Description: This provides an easy way to make a single instance application in C#. Simply put this code in your application, and whenever you would call Application.Run, call SingleInstanceApp.Run.Link: http://www.codekeep.net/snippets/706d3140-f9b1-4cd1-a22f-5928cc06db72.aspx
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;
internal static class SingleInstanceApp{
[DllImport( "user32.dll" )]
private static extern int ShowWindow( IntPtr hWnd, int nCmdShow );
[DllImport( "user32.dll" )]
private static extern int SetForegroundWindow( IntPtr hWnd );
[DllImport( "user32.dll" )]
private static extern int IsIconic( IntPtr hWnd );
private static IntPtr GetCurrentInstanceWindowHandle() {
IntPtr hWnd = IntPtr.Zero;
Process process = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName( process.ProcessName );
foreach ( Process _process 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 ( _process.Id != process.Id &&
_process.MainModule.FileName == process.MainModule.FileName &&
_process.MainWindowHandle != IntPtr.Zero ) {
hWnd = _process.MainWindowHandle;
break;
}
}
return hWnd;
}
private static void SwitchToCurrentInstance() {
IntPtr hWnd = GetCurrentInstanceWindowHandle();
if ( hWnd != IntPtr.Zero ) {
if ( IsIconic( hWnd ) != 0 ) {
ShowWindow( hWnd, SW_RESTORE );
}
SetForegroundWindow( hWnd );
}
}
public static bool Run( System.Windows.Forms.Form frmMain ) {
if ( IsAlreadyRunning() ) {
SwitchToCurrentInstance();
return false;
}
Application.Run( frmMain );
return true;
}
private static bool IsAlreadyRunning() {
string strLoc = System.Reflection.Assembly.GetExecutingAssembly().Location;
System.IO.FileSystemInfo fileInfo = new System.IO.FileInfo( strLoc );
string sExeName = fileInfo.Name;
bool bCreatedNew;
mutex = new Mutex( true, "Global\\" + sExeName, out bCreatedNew );
if ( bCreatedNew )
mutex.ReleaseMutex();
return !bCreatedNew;
}
static Mutex mutex;
const int SW_RESTORE = 9;
}