小编典典

检查我的Windows应用程序是否正在运行

c#

如何检查C#Windows应用程序是否正在运行?

我知道我可以检查进程名称,但是如果exe更改,则可以更改名称。

有什么方法可以使用哈希键或其他使我的应用程序具有唯一性的方法吗?


阅读 379

收藏
2020-05-19

共1个答案

小编典典

public partial class App : System.Windows.Application
{
    public bool IsProcessOpen(string name)
    {
        foreach (Process clsProcess in Process.GetProcesses()) 
        {
            if (clsProcess.ProcessName.Contains(name))
            {
                return true;
            }
        }

        return false;
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        // Get Reference to the current Process
        Process thisProc = Process.GetCurrentProcess();

        if (IsProcessOpen("name of application.exe") == false)
        {
            //System.Windows.MessageBox.Show("Application not open!");
            //System.Windows.Application.Current.Shutdown();
        }
        else
        {
            // Check how many total processes have the same name as the current one
            if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
            {
                // If ther is more than one, than it is already running.
                System.Windows.MessageBox.Show("Application is already running.");
                System.Windows.Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }
    }
2020-05-19