如何检查WPF应用程序是否已在运行?

时间:2011-08-24 22:12:31

标签: c# .net wpf single-instance

  

可能重复:
  What is the correct way to create a single instance application?

如何检查我的应用程序是否已打开?如果我的应用程序已经运行,我想显示它而不是打开一个新实例。

4 个答案:

答案 0 :(得分:17)

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

static void Main() 
{
    Process currentProcess = Process.GetCurrentProcess();
    var runningProcess = (from process in Process.GetProcesses()
                          where
                            process.Id != currentProcess.Id &&
                            process.ProcessName.Equals(
                              currentProcess.ProcessName,
                              StringComparison.Ordinal)
                          select process).FirstOrDefault();
    if (runningProcess != null)
    {
        ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
       return; 
    }
}

方法2

static void Main()
{
    string procName = Process.GetCurrentProcess().ProcessName;

    // get the list of all processes by the "procName"       
    Process[] processes=Process.GetProcessesByName(procName);

    if (processes.Length > 1)
    {
        MessageBox.Show(procName + " already running");  
        return;
    } 
    else
    {
        // Application.Run(...);
    }
}

答案 1 :(得分:2)

public partial class App
    {
        private const string Guid = "250C5597-BA73-40DF-B2CF-DD644F044834";
        static readonly Mutex Mutex = new Mutex(true, "{" + Guid + "}");

        public App()
        {

            if (!Mutex.WaitOne(TimeSpan.Zero, true))
            {
                //already an instance running
                Application.Current.Shutdown();
            }
            else
            {
                //no instance running
            }
        }
    }

答案 2 :(得分:1)

这是一行代码,它将为您执行此操作...

 if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
// Show your error message
}

答案 3 :(得分:-1)

执行此操作:

    using System.Threading;
    protected override void OnStartup(StartupEventArgs e)
    {
        bool result;
        Mutex oMutex = new Mutex(true, "Global\\" + "YourAppName",
             out result);
        if (!result)
        {
            MessageBox.Show("Already running.", "Startup Warning");
            Application.Current.Shutdown();
        }
        base.OnStartup(e);
    }