Method 1: prohibit multiple processes from running.
[Stathread]
Public static void main ()
{
Bool ret;
System. Threading. mutex = new system. Threading. mutex (true, application. productname, out RET );
If (RET)
{System. Windows. Forms. application. enablevisualstyles (); // these two lines implement the XP visual style.
System. Windows. Forms. application. doevents ();
System. Windows. Forms. application. Run (New Main ());
// Main is for you Program The main form of, if the console program does not use this sentence
Mutex. releasemutex ();
}
Else
{
MessageBox. Show (null, "one application with the same program is already running. Please do not run multiple programs at the same time. /N is about to exit. ", Application. productname, messageboxbuttons. OK, messageboxicon. Warning );
// Message, which can be deleted.
Application. Exit (); // exit the program
}
}
Method 2: prohibit multiple processes from running and activate the previous processes when they are repeated.
[Stathread]
Public static void main ()
{
// Get the running instance.
Process instance = runninginstance ();
If (instance = NULL)
{System. Windows. Forms. application. enablevisualstyles (); // these two lines implement the XP visual style.
System. Windows. Forms. application. doevents ();
// There isn' t another instance, show our form.
Application. Run (New Main ());
}
Else
{
// There is another instance of this process.
Handlerunninginstance (instance );
}
}
Public static process runninginstance ()
{
Process current = process. getcurrentprocess ();
Process [] processes = process. getprocessesbyname (current. processname );
// Loop through the running processes in with the same name
Foreach (Process in processes)
{
// Ignore the current process
If (process. ID! = Current. ID)
{
// Make sure that the process is running from the EXE file.
If (assembly. getexecutingassembly (). Location. Replace ("/", "//") = current. mainmodule. filename)
{
// Return the other process instance.
Return process;
}
}
}
// No other instance was found, return null.
Return NULL;
}
Public static void handlerunninginstance (process instance)
{
// Make sure the window is not minimized or maximized
Showwindowasync (instance. main1_whandle, ws_shownormal );
// Set the real intance to foreground window
Setforegroundwindow (instance. main1_whandle );
}
[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;