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

10

每台计算机、每个用户或每个桌面是一个实例吗? - adrianm
4个回答

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

1
谢谢回复,但对我来说不太清楚。我不知道在哪里使用这段代码。是在主窗口还是在app.xaml中?如果登录对话框结果为true,则打开主窗口。我甚至不知道如何显示和最大化已打开的应用程序。 - Irakli Lekishvili
1
这段代码应该放在主方法中。查看此处以获取有关主方法的更多信息。http://joyfulwpf.blogspot.com/2009/05/where-is-main-method-in-my-wpf.html - CharithJ
请使用System.Windows.Application.Current.Shutdown();代替return。 - AmirHossein Rezaei

4
这是一行代码,可以为您完成这个操作...
 if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
// Show your error message
}

这就是实际的答案。只需将其放入Application_Startup中,您就可以开始了。 - sonofsmog

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

我的.NET 4.0 WPF应用程序无法工作? - user755404

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

这不会显示现有实例的窗口。 - Chris Shain
1
我刚刚测试了一下。第一次运行应用程序时,窗体正常显示。第二次运行时,会弹出一个对话框,显示“已在运行”,当你关闭该对话框后,什么也不会发生。原帖作者希望在这种情况下显示应用程序的原始实例。使用您的解决方案,如果我将原始实例最小化或将记事本放在其前面,它不会被置于前台。 - Chris Shain
1
@Chris- 感谢您的关注,我没有仔细阅读问题。 - Saber Amani
无法在我的.NET 4.0 WPF应用程序中工作。 - user755404

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接