C# WPF,如何创建单个实例,并在c中启动另一个实例时显示主窗口#
作为标题状态,我想制作一个单实例程序,并在启动另一个实例时显示MainWindow。 我已经显示了一条消息,只允许一个实例C# WPF,如何创建单个实例,并在c中启动另一个实例时显示主窗口#,c#,wpf,mutex,single-instance,C#,Wpf,Mutex,Single Instance,作为标题状态,我想制作一个单实例程序,并在启动另一个实例时显示MainWindow。 我已经显示了一条消息,只允许一个实例 public class MyApplication { static Mutex mutex = new Mutex(true, "FirstInstance"); [STAThread] public static void Main(string[] args) { if (mutex.WaitOne(TimeSpan.Zero
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");
}
}
}
这很好,但我想显示主窗口而不是消息,所以我尝试了
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:对象引用未设置为对象的实例”。似乎应用程序中的主窗口(是静态的)是空的,我不明白为什么
所以我尝试了这篇文章
但WndProc方法在WPF中不存在
如果你能帮助我,我将不胜感激。
谢谢 如果我没有误解你的问题,试着这样做
[STAThread]
public static void Main(string[] args)
{
Task task = new Task(() => { Thread.Sleep(200); MessageBox.Show("what a marvelous engineering"); });
task.Start();
//If you want application not to run untill task is complete then just use wait
task.Wait();
App app = new App();
app.InitializeComponent();
app.Run();
}
但我想知道你是否希望在主窗口实例化之前完成C#工作,为什么不在App App=new App()之前完成其他工作,让代码按顺序运行。我创建了一个示例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;
}
}
}
}
仅供参考,这在调试模式下不起作用,因为.vshost成为进程名称的一部分。如果需要它在调试模式下工作,则需要迭代所有进程,而不是调用Process.getProcessByName。因为首先需要创建应用程序实例和Mainwindow实例。