0

我在 WPF 中创建了一个小程序。当我运行我的 exe 文件时,它将正确打开我的应用程序。但是,当我再次运行我的 exe 时,它​​会再次打开。我只希望它运行一次。

我搜索了这个问题的解决方案,我得到了一些这样的代码:

System.Diagnostics.Process.GetCurrentProcess().Kill();

此代码将关闭所有应用程序。但是,我需要的是,当我一次又一次地运行我的 exe 时,将只有一个应用程序实例。

4

2 回答 2

0

如果我理解正确,您希望应用程序在再次打开同一个文件时只打开一次。

这样做的一种方法不是杀死一个进程(这可能会损坏文件),而是立即关闭新打开的应用程序。

将打开的文件列表保留在中心位置(注册表、文件),并在应用程序启动时检查文件是否已经在列表中。如果它关闭新启动的应用程序。

您可以尝试添加一些代码,将包含所请求文件的应用程序带到桌面顶部。

于 2012-08-30T07:42:54.383 回答
0

您可以使用Mutex类。

  • 由于每个系统可能始终只存在一个具有特定名称的 Mutex ,因此您可以第一次应用程序启动时实例化它。
  • 您可以在每次启动应用程序时检查应用程序实例是否可以拥有互斥锁。
  • 如果没有,您知道应用程序的另一个实例已经存在,并且可以优雅地关闭新实例。

使用Mutex它非常简单明了。

using System;
using System.Threading;

public class Test
{
    public static void Main()
    {
        // Set this variable to false if you do not want to request  
        // initial ownership of the named mutex. 
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing 
        // true for the first parameter. Only one system object named  
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains 
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);

        // This thread owns the mutex only if it both requested  
        // initial ownership and created the named mutex. Otherwise, 
        // it can request the named mutex by calling WaitOne. 
        if (!(requestInitialOwnership && mutexWasCreated))
        {
           // The mutex is already owned by another application instance.
           // Close gracefully.

           // Put your exit code here...
           // For WPF, this would be Application.Current.Shutdown();
           // (Obviously, that would not work in this Console example.. :-) )
        }

        // Your application code here...
    }
}
于 2012-08-30T07:59:38.220 回答