仅启用WPF应用程序的一个实例
我有仅启用WPF应用程序的一个实例,wpf,Wpf,我有WPF分配,我希望能够只打开我的应用程序的一个实例 所以我有两门课: public sealed class SingleInstance { public static bool AlreadyRunning() { bool running = false; try { // Getting collection of process
WPF
分配,我希望能够只打开我的应用程序的一个实例
所以我有两门课:
public sealed class SingleInstance
{
public static bool AlreadyRunning()
{
bool running = false;
try
{
// Getting collection of process
Process currentProcess = Process.GetCurrentProcess();
// Check with other process already running
foreach (var p in Process.GetProcesses())
{
if (p.Id != currentProcess.Id) // Check running process
{
if (p.ProcessName.Equals(currentProcess.ProcessName) == true)
{
running = true;
IntPtr hFound = p.MainWindowHandle;
if (User32API.IsIconic(hFound)) // If application is in ICONIC mode then
User32API.ShowWindow(hFound, User32API.SW_RESTORE);
User32API.SetForegroundWindow(hFound); // Activate the window, if process is already running
break;
}
}
}
}
catch { }
return running;
}
}
以及:
App.xaml:
protected override void OnStartup(StartupEventArgs e)
{
if (SingleInstance.AlreadyRunning())
App.Current.Shutdown(); // Just shutdown the current application,if any instance found.
base.OnStartup(e);
}
因此,此解决方案只允许一个实例,但如果用户尝试打开另一个实例
,我可以在任务栏中看到我的应用程序的新图标
,鼠标悬停时,此图标会自动关闭,但我想阻止显示此图标
,因此我将其从App.xaml
中删除:
StartupUri="MainWindow.xaml"
现在我的应用程序没有启动(可能启动了,但我看不到)。
有机会实现我想要的吗
我需要调用main窗口
,但我不知道从哪里开始
更新
所以我尝试这种方法:
protected override void OnStartup(StartupEventArgs e)
{
if (SingleInstance.AlreadyRunning())
App.Current.Shutdown(); // Just shutdown the current application,if any instance found.
base.OnStartup(e);
new MainWindow().Show();
}
当用户试图打开另一个实例时,我仍然可以看到第二个(和第三个等…)图标您需要在OnStartup中手动启动主窗口。基础后。启动时(e);如果问题仍然存在,请尝试将ShowInTaskbar设置为false。请查看我的更新查看类似问题的答案:
protected override void OnStartup(StartupEventArgs e)
{
if (SingleInstance.AlreadyRunning())
App.Current.Shutdown(); // Just shutdown the current application,if any instance found.
base.OnStartup(e);
new MainWindow().Show();
}