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 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. |
// No other instance was found, return null. |
Public Shared Function RunningInstance () As Process |
Dim current As Process = Process. GetCurrentProcess () |
Dim processes As Process () = Process. GetProcessesByName (current. ProcessName) |
'Loop through the running processes in with the same name |
For Each process In processes |
'Ignore the current process |
If process. Id <> current. Id Then |
'Make sure that the process is running from the exe file. |
If [Assembly]. GetExecutingAssembly (). Location. Replace ("/", "/") = current. MainModule. FileName Then |
'Return the other process instance. |
'No other instance was found, return null. |
End Function 'runninginstance |
If an existing form instance is detected, the instance is displayed for reference:
[STAThread] Static void Main () { // Get the running instance. Process instance = RunningInstance (); If (instance = null) { // There isn' t another instance, show our form. Application. Run (new Form2 ()); } 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 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 |
Source: http://blog.csdn.net/acewang/archive/2004/02/05/17627.aspx