使用C#终止重复的进程

时间:2012-11-15 15:06:13

标签: c# .net

所以在我的程序开始时,我有一段代码检查是否正在运行此进程的另一个实例。

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

如果进程正在运行,那么我打开一个消息框,说明进程已在运行,并询问用户是否要终止当前进程并打开一个新进程。

如果对话结果为yes,那么我使用process.kill来关闭进程。问题是我将运行其中两个进程,因此如何指定要关闭哪个进程?进程名称将完全相同,我想关闭首先打开的进程名称。

6 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分: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();
    }
}

答案 2 :(得分: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将当前进程转换为差异进程。

答案 3 :(得分:0)

您可以使用Process.StartTime属性并查看稍后启动的进程,然后将其终止。

答案 4 :(得分:0)

我刚才写了这篇文章,使用了一些R& D(Ripoff和Deploy)来自该网站上的另一个问答(找不到原文),它检查程序是否已经从同一个程序运行path(只要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返回的falseSingleApplication.Run(),以了解您的计划是否正在启动。它会阻塞,直到Application.Run()正常退出并返回true,否则如果程序已在运行,它会立即返回false。

答案 5 :(得分: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();
                }
            }
        }
    }