开发者

How to check if a WPF application is already running? [duplicate]

This question already has answers here: 开发者_如何学JAVA Closed 11 years ago.

Possible Duplicate:

What is the correct way to create a single instance application?

How can I check if my application is already open? If my application is already running, I want to show it instead of opening a new instance.


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

Method 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(...);
    }
}


Here is one line code which will do this for you...

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


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
            }
        }
    }


Do This :

    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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜