需求
应用程序运行之后,再次点击EXE可执行文件时,应用程序不会重复打开,并将已打开的应用程序状态还原并激活展示。
实现
在应用程序的执行之前,检查进程中是否存在已经在运行的应用程序。如果存在,则激活存在的应用程序,当前应用程序退出。
检查进程方法定义,以下方法不仅仅在WPF框架下,在其他C#框架下依然可行:
-
-
/// <summary>
-
/// 进程
-
/// </summary>
-
private Mutex mutex;
-
-
/// <summary>
-
/// 检查应用程序是否在进程中已经存在了
-
/// </summary>
-
private void CheckApplicationMutex()
-
{
-
bool mutexResult;
-
-
// 第二个参数为 你的工程命名空间名。
-
// out 给 ret 为 false 时,表示已有相同实例运行。
-
mutex =
new Mutex(
true,
"Deamon",
out mutexResult);
-
-
if (!mutexResult)
-
{
-
// 找到已经在运行的实例句柄(给出你的窗体标题名 “Deamon Club”)
-
IntPtr hWndPtr = FindWindow(
null,
"Deamon Club");
-
-
// 还原窗口
-
ShowWindow(hWndPtr, SW_RESTORE);
-
-
// 激活窗口
-
SetForegroundWindow(hWndPtr);
-
-
// 退出当前实例程序
-
Environment.Exit(
0);
-
}
-
}
-
-
#region Windows API
-
-
// ShowWindow 参数
-
public
const
int SW_RESTORE =
9;
-
-
/// <summary>
-
/// 在桌面窗口列表中寻找与指定条件相符的第一个窗口。
-
/// </summary>
-
/// <param name="lpClassName">指向指定窗口的类名。如果 lpClassName 是 NULL,所有类名匹配。</param>
-
/// <param name="lpWindowName">指向指定窗口名称(窗口的标题)。如果 lpWindowName 是 NULL,所有windows命名匹配。</param>
-
/// <returns>返回指定窗口句柄</returns>
-
[
DllImport("USER32.DLL", SetLastError = true, CharSet = CharSet.Auto)]
-
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
-
-
/// <summary>
-
/// 将窗口还原,可从最小化还原
-
/// </summary>
-
/// <param name="hWnd"></param>
-
/// <param name="nCmdShow"></param>
-
/// <returns></returns>
-
[
DllImport("USER32.DLL")]
-
[
return: MarshalAs(UnmanagedType.Bool)]
-
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
-
-
/// <summary>
-
/// 激活指定窗口
-
/// </summary>
-
/// <param name="hWnd">指定窗口句柄</param>
-
/// <returns></returns>
-
[
DllImport("USER32.DLL")]
-
[
return: MarshalAs(UnmanagedType.Bool)]
-
public static extern bool SetForegroundWindow(IntPtr hWnd);
-
-
#endregion
在应用程序开始工作之前调用(WPF举例,WPF在App中的OnStartup方法开始时调用)。
-
protected override void OnStartup(StartupEventArgs e)
-
{
-
CheckApplicationMutex();
-
-
base.OnStartup(e);
-
-
// 配置 IoC 容器
-
IoC.Setup();
-
-
// 启动主窗体
-
Current.MainWindow =
new MainWindow();
-
Current.MainWindow.Show();
-
}
Over
每次记录一小步...点点滴滴人生路...