Using System;
Using System. Runtime. InteropServices;
Using System. Windows. Forms;
Using System. Diagnostics;
Using System. Reflection;
Public class OneInstnace
{
[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 Form ());
}
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 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 );
}
[DllImport ("User32.dll")]
Private static extern bool ShowWindowAsync (IntPtr hWnd, intcmdShow );
[DllImport ("User32.dll")]
Private static extern bool SetForegroundWindow (IntPtr hWnd );
Private const int WS_SHOWNORMAL = 1;
}