如果你已经读了前面的几篇文章,我相信你自己或许已经有答案了,我自己用下来感觉还是有一些区别的,现在把我总结的记录下来:

一:使用System.Threading.Mutex类

using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))


使用这个方法,我自己测试下来,在Windows的单一用户使用的时候可以使用,当多个Windows用户同时使用的时候则无法检测到程序是否在运行状态。

二:检查进程名的

Process[] processes = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);


使用这个方法可以检查当前机器上的所有进程名称,多个用户也可以同时检测。但是如果程序改名运行,则无法检测到程序是否在运行状态。

三:使用API

API一:
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
API二:
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr OpenMutex(
uint dwDesiredAccess, // access
int bInheritHandle, // inheritance option
string lpName // object name
);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr CreateMutex(
IntPtr lpMutexAttributes, // SD
int bInitialOwner, // initial owner
string lpName // object name
);


这个方法在我前面的文章中已经提到了两种API的使用

API一,可以使程序前端显示出来,并且获取为焦点。

API二,其实更像System.Threading.Mutex类,

因为在项目中暂时没有使用这些功能,所以没有太多的意见。