设计桌面应用程序时往往只希望该程序在桌面中只能运行一次。
本文给出一个通过判断窗口标题来判断桌面应用是否重复运行,这种方法比较简单,
但不是最好的,如果第一个应用的主窗体还没来得及创建第二个应用就起来了,就可
能同时起两个窗体。但一般情况下不会有这个问题。最好的方法还是通过互斥量来判断。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace 优快云Test
...{
static class Program
...{
[DllImport("User32.dll")]
private static extern IntPtr FindWindow(String lpClassName, String lpWindowName);

/**//// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
...{
IntPtr handle = FindWindow(null, "Form1"); //查找和主窗体标题相同的窗体,这里假设主窗体标题为Form1
if (handle != (IntPtr)0)
...{
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

在设计WinForm应用时,通常需要确保程序不能多次运行。本文介绍了一种简单的方法,即通过查找窗体标题来判断是否已运行。尽管此方法可能存在主窗体未及时创建导致的漏洞,一般情况下能有效防止重复启动。互斥量被认为是更优的解决方案。
1350

被折叠的 条评论
为什么被折叠?



