2012-11-15 77 views
0

因此,在我的程序開始時,我有一段代碼檢查此進程的另一個實例是否正在運行。用C#終止重複進程

Process process = Process.GetCurrentProcess(); 
bool isProcessRunning = (Process.GetProcessesByName(process.ProcessName)).Length > 1; 

如果正在運行的進程,然後我打開一個消息框,指出該進程已經運行,並詢問用戶是否要終止當前進程,並打開一個新的。

如果對話結果爲是,則使用process.kill關閉進程。問題是我將有兩個這樣的進程在運行,那麼如何指定要關閉哪一個?進程名稱將完全相同,我想關閉首先打開的進程名稱。

+0

你可以嘗試進程間的通信,使您的流程封閉自己 –

+1

一點比更溫柔'Process.Kill()' – jglouie

回答

1

循環遍歷具有相同名稱的進程並檢查Id是否不同。如果是,就殺了它。

Process process = Process.GetCurrentProcess(); 
var dupl = (Process.GetProcessesByName(process.ProcessName)); 
if(dupl.Length > 1 && MessageBox.Show("Kill?", "Kill duplicates?", MessageBoxButtons.YesNo) == DialogResult.Yes) { 
    foreach(var p in dupl) { 
     if(p.Id != process.Id) 
      p.Kill(); 
    } 
} 
+0

正是我需要的,謝謝! – NMunro

0

使用此命令殺死當前正在啓動的進程。伯爵將根據程序的路徑位置是2,這將被終止:

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill(); 

您還可以使用:

Process.Id 

你使用GetProcessesByName來區別處理當前的進程後。

+0

我要殺死一個已經運行的進程。 – NMunro

+0

使用process.ID然後一旦GetProcessesByName()並將其與具有相同名稱的其他正在運行的進程進行比較 –

3
private static void killps(string processName) 
{ 
    Process[] process = Process.GetProcessesByName(processName); 
    Process current = Process.GetCurrentProcess(); 
    foreach (Process p in process) 
    { 
     if (p.Id != current.Id) 
     p.Kill(); 
    } 
} 
0

您可以使用Process.StartTime屬性,看看有什麼處理,後面開始,然後殺死它。

0

我前一段時間使用一些R & D(Ripoff和Deploy)從本網站的其他問題和答案(找不到原文)寫了這段代碼,它檢查程序是否已經從相同的路徑(只要exe是從不同的路徑啓動,這允許多個實例)。我使另一個程序成爲活動窗口(它甚至在最小化時恢復窗口),甚至不告訴用戶有重複的實例打開。

public static class SingleApplication 
{ 
    [DllImport("user32.Dll")] 
    private static extern int EnumWindows(EnumWinCallBack callBackFunc, int lParam); 

    [DllImport("User32.Dll")] 
    private static extern void GetWindowText(int hWnd, StringBuilder str, int nMaxCount); 

    [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] 
    private static extern bool SetForegroundWindow(IntPtr hWnd); 

    [DllImport("user32.dll")] 
    private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow); 

    static Mutex mutex; 
    const int SW_RESTORE = 9; 
    static string sTitle; 
    static IntPtr windowHandle; 
    delegate bool EnumWinCallBack(int hwnd, int lParam); 

    private static bool EnumWindowCallBack(int hwnd, int lParam) 
    { 
     windowHandle = (IntPtr)hwnd; 
     StringBuilder sbuilder = new StringBuilder(256); 
     GetWindowText((int)windowHandle, sbuilder, sbuilder.Capacity); 
     string strTitle = sbuilder.ToString(); 
     if (strTitle == sTitle && hwnd != lParam) 
     { 
      ShowWindow(windowHandle, SW_RESTORE); 
      SetForegroundWindow(windowHandle); 
      return false; 
     } 
     return true; 
    } 

    /// <summary> 
    /// Execute a form application. If another instance already running on the system activate previous one. 
    /// </summary> 
    /// <param name="frmMain">main form</param> 
    /// <returns>true if no previous instance is running</returns> 
    public static bool Run(System.Windows.Forms.Form frmMain) 
    { 
     if (IsAlreadyRunning()) 
     { 
      sTitle = frmMain.Text; 
      EnumWindows(new EnumWinCallBack(EnumWindowCallBack), frmMain.Handle.ToInt32()); 
      return false; 
     } 
     Application.Run(frmMain); 
     return true; 
    } 

    /// <summary> 
    /// Checks using a Mutex with the name of the running assembly's location 
    /// </summary> 
    /// <returns>True if the assembly is already launched from the same location, false otherwise.</returns> 
    private static bool IsAlreadyRunning() 
    { 
     string strLoc = Assembly.GetEntryAssembly().Location; 

     FileSystemInfo fileInfo = new FileInfo(strLoc); 
     string name = fileInfo.Name; 
     mutex = new Mutex(true, name); 
     if (mutex.WaitOne(0, false)) 
     { 
      return false; 
     } 
     return true; 
    } 
} 

它被用作以下

static class Program 
{ 
    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     SingleApplication.Run(new Form1()); 
    } 
} 

如果你願意,你可以檢查是否true或從SingleApplication.Run()返回找出如果你的程序正在啓動或不false。它會阻止,直到Application.Run()通常會退出並返回true,或者如果程序已經運行,它立即返回false。

0

通過比較兩個過程的開始時間。

Process process = Process.GetCurrentProcess(); 
Process [] duplicateProcess = Process.GetProcessesByName(process.ProcessName).ToArray(); 
if (duplicateProcess.Length > 1) 
{ 
     if (MessageBox.Show("Duplicate Found. Do you want to kill duplicate process", "Duplicate Process", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
     { 
      foreach (Process p in duplicateProcess) 
      { 
       int res = DateTime.Compare(p.StartTime, process.StartTime); 
       if (res < 0) 
       { 
        // P process opened first 
        p.Kill(); 
       } 
       else if (res > 0) 
       { 
        // process Opened first 
        process.Kill(); 
       } 
      } 
     } 
    }