andrew4582

ProcessHelper_EnsureSingleInsance

Aug 21st, 2010
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Windows.Forms;
  7.  
  8. namespace Core.System.Diagnostics {
  9.  
  10.     public static class ProcessHelper {
  11.  
  12.         const int SW_RESTORE = 9;
  13.  
  14.         [DllImport("user32.dll",EntryPoint = "SetForegroundWindow")]
  15.         public static extern bool SetForegroundWindow(IntPtr hWnd);
  16.  
  17.         [DllImport("user32.dll")]
  18.         public static extern Boolean ShowWindow(IntPtr hWnd,Int32 nCmdShow);
  19.  
  20.         /// <summary>
  21.         /// Ensures a process single insance
  22.         /// </summary>
  23.         /// <param name="mainWidowTitle">Main widow title</param>
  24.         /// <returns>True if the same process is already running</returns>
  25.         public static bool EnsureSingleInsance(string mainWidowTitle,bool focusRunningApp = true) {
  26.  
  27.             Process current = Process.GetCurrentProcess();
  28.  
  29.             //get active title if no main title
  30.             if(Form.ActiveForm != null)
  31.                 mainWidowTitle = Form.ActiveForm.Text;
  32.  
  33.             //find process
  34.             Process alreadyRunning = Process.GetProcessesByName(current.ProcessName)
  35.                 .Where(p => {
  36.                     try {
  37.                         if(p.MainWindowTitle.StartsWith(mainWidowTitle)) {
  38.                             return p.MainModule.FileName == current.MainModule.FileName;
  39.                         }
  40.                         return false;
  41.                     }
  42.                     catch {
  43.                         return false;
  44.                     }
  45.                 })
  46.                 .FirstOrDefault();
  47.  
  48.             //show existing process
  49.             if(alreadyRunning != null) {
  50.                 if(focusRunningApp) {
  51.                     IntPtr handle = alreadyRunning.MainWindowHandle;
  52.                     ShowWindow(handle,SW_RESTORE);
  53.                     SetForegroundWindow(handle);
  54.                 }
  55.                 return false;
  56.             }
  57.             return true;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment