mig*_*lla 1 c# wpf instance single-instance
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>
Run Code Online (Sandbox Code Playgroud)
之后,您可以转到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();
}
}
Run Code Online (Sandbox Code Playgroud)
这将测试互斥锁是否存在以及它是否存在,应用程序将显示一条消息并退出.否则将构造应用程序并调用OnStartup覆盖.
根据您的Windows版本,提升消息框也会将现有实例推送到Z顺序的顶部.如果没有,你可以提出另一个关于将窗户置于顶部的问题.
Win32Api中还有其他功能,可以帮助进一步自定义行为.
此方法为您提供了您所使用的消息通知,并确保仅创建主窗口的一个实例.