检查WPF应用程序的其他实例是否正在运行
这个问题在这里已经有了答案:
如果exe被复制并重命名,则按名称获取策略可能会失败。 调试也可能有问题,因为.vshost被附加到进程名称。
要在WPF中创建单个实例应用程序,您可以先从App.Xaml文件中删除StartupUri属性,使其看起来像这样...
<Application x:Class="SingleInstance.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>
之后,您可以转到App.xaml.cs文件并更改它,使其看起来像这样...
public partial class App 
{
    // give the mutex a  unique name
    private const string MutexName = "##||ThisApp||##";
    // declare the mutex
    private readonly Mutex _mutex;
    // overload the constructor
    bool createdNew;
    public App() 
    {
        // overloaded mutex constructor which outs a boolean
        // telling if the mutex is new or not.
        // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx
        _mutex = new Mutex(true, MutexName, out createdNew);
        if (!createdNew)
        {
            // if the mutex already exists, notify and quit
            MessageBox.Show("This program is already running");
            Application.Current.Shutdown(0);
        }
    }
    protected override void OnStartup(StartupEventArgs e)
    {
        if (!createdNew) return;
        // overload the OnStartup so that the main window 
        // is constructed and visible
        MainWindow mw = new MainWindow();
        mw.Show();
    }
}
这将测试互斥量是否存在,如果存在,应用程序将显示一条消息并退出。 否则,应用程序将被构造并且OnStartup覆盖将被调用。
根据您的Windows版本,提高消息框也会将现有实例推到Z顺序的顶部。 如果不是的话,你可以提出另一个关于把窗户打到顶端的问题。
Win32Api中还有其他功能可以帮助进一步自定义行为。
这种方法为您提供您之后的消息通知,并确保仅创建主窗口的一个实例。
链接地址: http://www.djcxy.com/p/51141.html上一篇: Check if other instances of a WPF application are/aren't running
