gpt4 book ai didi

c# - WPF,如何创建单个实例并在 c# 中启动另一个实例时显示 MainWindow

转载 作者:行者123 更新时间:2023-11-30 22:15:49 25 4
gpt4 key购买 nike

如标题所述,我想制作一个单实例程序并在启动另一个实例时显示 MainWindow。我已实现显示仅允许一个实例的消息。

public class MyApplication
{
static Mutex mutex = new Mutex(true, "FirstInstance");
[STAThread]
public static void Main(string[] args)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
App app = new App();
app.InitializeComponent();
app.Run();
}
else
{
MessageBox.Show("only one instance at a time");
}
}
}

这很好用,但我想显示 MainWindow 而不是消息,所以我尝试了

static Application app;//change app to static
if (mutex.WaitOne(TimeSpan.Zero, true))
{
app = new App();
app.InitializeComponent();
app.Run();
}
else
{
app.MainWindow.WindowState = WindowState.Normal;
}

我收到“System.NullReferenceException:对象引用未设置为对象的实例”。应用程序(静态)中的 MainWindow 似乎为空,我不明白为什么。

所以我试了这篇文章http://sanity-free.org/143/csharp_dotnet_single_instance_application.html但 WndProc 方法在 WPF 中不存在。

如果你能帮助我,我将不胜感激。谢谢!

最佳答案

我创建了一个示例 WPF 应用程序并且只更改了 App.xaml.cs 文件。如果单实例窗口已经打开,此代码将查找与当前进程名称匹配的任何进程,如果该进程有窗口,则显示它:

public partial class App : Application
{
// signals to restore the window to its normal state
private const int SW_SHOWNORMAL = 1;

// create the mutex
private const string MUTEXNAME = "FirstInstance";
private readonly Mutex _mutex = new Mutex(true, MUTEXNAME);

public App()
{
if (!_mutex.WaitOne(TimeSpan.Zero))
{
ShowExistingWindow();
Shutdown();
}
}

[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

// shows the window of the single-instance that is already open
private void ShowExistingWindow()
{
var currentProcess = Process.GetCurrentProcess();
var processes = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (var process in processes)
{
// the single-instance already open should have a MainWindowHandle
if (process.MainWindowHandle != IntPtr.Zero)
{
// restores the window in case it was minimized
ShowWindow(process.MainWindowHandle, SW_SHOWNORMAL);

// brings the window to the foreground
SetForegroundWindow(process.MainWindowHandle);

return;
}
}
}
}

仅供引用,这在 Debug模式下不起作用,因为 .vshost 成为进程名称的一部分。如果您需要它在 Debug模式下工作,则需要遍历所有进程而不是调用 Process.GetProcessesByName。

关于c# - WPF,如何创建单个实例并在 c# 中启动另一个实例时显示 MainWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com