可能重复:
What is the correct way to create a single instance application?如何检查WPF应用程序是否已在运行?
我如何检查我的应用程序已经打开?如果我的应用程序已经运行,我想显示它而不是打开一个新的实例。
可能重复:
What is the correct way to create a single instance application?如何检查WPF应用程序是否已在运行?
我如何检查我的应用程序已经打开?如果我的应用程序已经运行,我想显示它而不是打开一个新的实例。
[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);
static void Main()
{
Process currentProcess = Process.GetCurrentProcess();
var runningProcess = (from process in Process.GetProcesses()
where
process.Id != currentProcess.Id &&
process.ProcessName.Equals(
currentProcess.ProcessName,
StringComparison.Ordinal)
select process).FirstOrDefault();
if (runningProcess != null)
{
ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);
return;
}
}
方法2
static void Main()
{
string procName = Process.GetCurrentProcess().ProcessName;
// get the list of all processes by the "procName"
Process[] processes=Process.GetProcessesByName(procName);
if (processes.Length > 1)
{
MessageBox.Show(procName + " already running");
return;
}
else
{
// Application.Run(...);
}
}
感谢重播,但对我来说还不清楚。我不知道在哪里使用这段代码。在主窗口或在app.xaml?如果登录对话框结果为true,则主窗口将打开。我甚至不知道如何显示,最大化打开的应用程序 –
此代码应该转到主要方法。在这里看看有关主要方法的更多信息。 http://joyfulwpf.blogspot.com/2009/05/where-is-main-method-in-my-wpf.html – CharithJ
做到这一点:
using System.Threading;
protected override void OnStartup(StartupEventArgs e)
{
bool result;
Mutex oMutex = new Mutex(true, "Global\\" + "YourAppName",
out result);
if (!result)
{
MessageBox.Show("Already running.", "Startup Warning");
Application.Current.Shutdown();
}
base.OnStartup(e);
}
这不会显示现有实例的窗口 –
试试这个,我测试了它。 – saber
我刚测试过它。第一次运行应用程序时,表单通常显示。第二次,你会看到一个对话框“已经运行”,并且当你忽略该对话时什么也没有发生。 OP希望在这种情况下显示应用程序的原始实例。使用你的解决方案,如果我最小化原始实例,或者将记事本放在它的前面,它不会被带到前台。 –
public partial class App
{
private const string Guid = "250C5597-BA73-40DF-B2CF-DD644F044834";
static readonly Mutex Mutex = new Mutex(true, "{" + Guid + "}");
public App()
{
if (!Mutex.WaitOne(TimeSpan.Zero, true))
{
//already an instance running
Application.Current.Shutdown();
}
else
{
//no instance running
}
}
}
对我的.NET 4.0 WPF应用程序不起作用? – Darren
下面是一行代码,它会为你做这个...
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
// Show your error message
}
它是每个计算机,每个用户还是每个桌面的一个实例吗? – adrianm