0

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

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

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

如果对话结果是肯定的,那么我使用 process.kill 来关闭进程。问题是我将运行其中两个进程,那么如何指定要关闭哪个进程?进程名会完全一样,我想关闭先打开的那个。

4

6 回答 6

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();
    }
}
于 2012-11-15T15:18:01.770 回答
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();
    }
}
于 2012-11-15T15:10:33.800 回答
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 获得当前流程后,以区别流程。

于 2012-11-15T15:10:14.673 回答
0

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

于 2012-11-15T15:18:24.743 回答
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());
    }
}

如果您愿意,您可以检查是否返回truefalse返回SingleApplication.Run()以了解您的程序是否正在启动。它会阻塞直到Application.Run()正常退出并返回 true,或者如果程序已经在运行,它会立即返回 false。

于 2012-11-15T15:44:08.557 回答
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();
                }
            }
        }
    }
于 2012-11-15T15:45:53.327 回答