如何检查是否一个WPF应用程序已经运行? [英] How to check if a WPF application is already running?
本文介绍了如何检查是否一个WPF应用程序已经运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application">What是创建一个单实例应用程序的正确方法是什么?
我如何检查,如果我的应用程序已经打开?如果我的应用程序已经在运行,我想告诉打开一个新的实例,它代替。
解决方案
[的DllImport(user32.dll中)
私人静态外部布尔的ShowWindow(IntPtr的的HWND,的Int32的nCmdShow);
静态无效的主要()
{
过程currentProcess = Process.GetCurrentProcess();
VAR runningProcess =(从过程Process.GetProcesses()
哪里
process.Id = currentProcess.Id和放大器;!&安培;
process.ProcessName.Equals(
currentProcess.ProcessName,
StringComparison.Ordinal)
选择过程).FirstOrDefault();
如果(runningProcess!= NULL)
{
的ShowWindow(runningProcess.MainWindowHandle,SW_SHOWMAXIMIZED);
返回;
}
}
方法2
静态无效的主要()
{
字符串PROCNAME = Process.GetCurrentProcess()ProcessName。
//得到所有进程列表的PROCNAME
流程[]进程= Process.GetProcessesByName(PROCNAME);
如果(processes.Length→1)
{
的MessageBox.show(PROCNAME +已经在运行);
返回;
}
其他
{
// Application.Run(...);
}
}
Possible Duplicate:
What is the correct way to create a single instance application?
How can I check if my application is already open? If my application is already running, I want to show it instead of opening a new instance.
解决方案
[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;
}
}
Method 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(...);
}
}
这篇关于如何检查是否一个WPF应用程序已经运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文