Method 1:
Static void Main ()
{
System. Threading. Mutex mutex;
Bool isNew;
Mutex = new System. Threading. Mutex (true, "myproject", out isNew );
If (isNew)
{
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
Application. Run (new Login ());
}
Else
{
MessageBox. Show ("this program is already running! "," Message ", MessageBoxButtons. OK, MessageBoxIcon. Warning );
}
}
Method 2 (a running window is displayed) to allow the program to run only one instance ):
Static void Main ()
{
Process instance = RunningInstance ();
If (instance = null)
{
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
Application. Run (new Login ());
}
Else
{
HandleRunningInstance (instance );
}
}
// Return the running program process
Public static Process RunningInstance ()
{
Process current = Process. GetCurrentProcess ();
Process [] processes = Process. GetProcessesByName (current. ProcessName );
Foreach (Process process in processes)
{
If (process. Id! = Current. Id)
{
If (Assembly. GetExecutingAssembly (). Location. Replace ("/", "\") = current. MainModule. FileName)
{
Return process;
}
}
}
Return null; // The first run, returns null
}
// Display the current window of the running process
Public static void HandleRunningInstance (Process instance)
{
ShowWindowAsync (instance. main1_whandle, WS_SHOWNORMAL); // set the window to normal
SetForegroundWindow (instance. main1_whandle );
}
# Region calls the system api
[DllImport ("User32.dll")]
Private static extern bool ShowWindowAsync (IntPtr hWnd, int cmdShow );
[DllImport ("User32.dll")]
Private static extern bool SetForegroundWindow (IntPtr hWnd );
Private const int WS_SHOWNORMAL = 1;
# Endregion
Author: pukuimin1226