设计桌面应用程序时往往只希望该程序在桌面中只能运行一次。
本文给出一个通过判断窗口标题来判断桌面应用是否重复运行,这种方法比较简单,
但不是最好的,如果第一个应用的主窗体还没来得及创建第二个应用就起来了,就可
能同时起两个窗体。但一般情况下不会有这个问题。最好的方法还是通过互斥量来判断。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CSDNTest
{
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());
}
}
}


浙公网安备 33010602011771号