Using system;
Using system. runtime. interopservices;
Using system. Windows. forms;
Using system. diagnostics;
Using system. reflection;
Namespace oneinstance
{
/// <Summary>
/// Class with program entry point.
/// </Summary>
Internal sealed class Program
{
// Declare the API and declare it
[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;
[Stathread] public static void main ()
{
// Obtain the running routine
Process instance = runninginstance ();
If (instance = NULL)
{
// If there are no other routines, create a new form
Application. Run (New mainform ());
}
Else
{
// Process the detected routine
Handlerunninginstance (instance );
}
}
Public static process runninginstance ()
{
Process current = process. getcurrentprocess ();
Process [] processes = process. getprocessesbyname (current. processname );
// Traverse a routine with the same name running
Foreach (Process in processes)
{
// Ignore existing routines
If (process. ID! = Current. ID)
{
// Ensure that the routine runs from the EXE file
If (assembly. getexecutingassembly (). Location. Replace ("/", "\") = current. mainmodule. filename)
{
// Return another routine instance
Return process;
}
}
}
// If no other routine exists, null is returned.
Return NULL;
}
Public static void handlerunninginstance (process instance)
{
// Ensure that the window is not minimized or maximized
Showwindowasync (instance. main1_whandle, ws_shownormal );
// Set the actual routine to foreground window
Setforegroundwindow (instance. main1_whandle );
}
}
}