您的位置:首页 > 编程语言 > C#

C# WINFORM判断程序是否运行,且只能运行一个实例

2016-07-13 09:53 811 查看
判断程序是否已经运行,使程序只能运行一个实例有很多方法,下面记录自己用的一种方法:

1、在Program.cs文件内修改

static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
if (Tools.IsRun(Tools.getExefilename()))
{
Tools.FatalAppExitA(0, "程序已运行!");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Frm_Main());
}
}

2、Tools内添加方法:
/// <summary>
/// Name:Panda
/// 检查程序是否已经运行
/// Date:2016-07-13
/// </summary>
/// <param name="exeName"></param>
/// <returns></returns>
public static bool IsRun(string exeName)
{
string tmp_exeName = exeName.ToUpper();
bool result = false;
int processnumber = 0;
IntPtr handle = CreateToolhelp32Snapshot(0x2, 0);
if ((int)handle > 0)
{
ProcessEntry32 pe32 = new ProcessEntry32();
pe32.dwSize = (uint)Marshal.SizeOf(pe32);
int bMore = Process32First(handle, ref pe32);
if (bMore == 1)
{
if (pe32.szExeFile.ToUpper().Equals(tmp_exeName))
{
processnumber++;
}
}
while (bMore == 1)
{
bMore = Process32Next(handle, ref pe32);
if (bMore == 1)
{
if (pe32.szExeFile.ToUpper().Equals(tmp_exeName))
{
processnumber++;
}
}
}
CloseHandle(handle);
if (processnumber >= 2)
{
result = true;
}
}
return result;
}

#region 检查程序是否已经运行(使用)

public static string getExefilename()
{
string strFullPath = Application.ExecutablePath;
string strFileName = System.IO.Path.GetFileName(strFullPath);
return strFileName;
}

[DllImport("KERNEL32.DLL ")]
public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid);
[DllImport("KERNEL32.DLL ")]
public static extern int Process32First(IntPtr handle, ref ProcessEntry32 pe);
[DllImport("KERNEL32.DLL ")]
public static extern int Process32Next(IntPtr handle, ref ProcessEntry32 pe);
[DllImport("KERNEL32.DLL ")]
public static extern int CloseHandle(IntPtr handle);
[DllImport("kernel32.dll")]
public static extern void FatalAppExitA(uint uAction, string lpMessageText);

[StructLayout(LayoutKind.Sequential)]
public struct ProcessEntry32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
};
#endregion

效果,当程序打开未关闭继续点击快捷键启动程序时:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: