10

可能重复:
创建单实例应用程序的正确方法是什么?

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

4

4 回答 4

19
[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; 
    }
}

方法二

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(...);
    }
}
于 2011-08-24T22:21:23.337 回答
3
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
            }
        }
    }
于 2011-08-24T22:25:36.670 回答
3

这是一个将为您执行此操作的行代码...

 if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
// Show your error message
}
于 2011-08-25T09:00:48.563 回答
-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);
    }
于 2011-08-24T22:25:30.480 回答