WM C#查找进程是否在运行的三种方法
1、FindWindow
[DllImport("coredll.Dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private void isRun()
{
IntPtr ptrTaskbar = FindWindow(@"calendar", null);
if (ptrTaskbar == IntPtr.Zero)//如果没有运行
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = @"\Windows\calendar.exe";//需要启动的程序名
p.Start();//启动
i f (p.HasExited)//判断是否运行结束
p.Kill();
}
}
但是找不到后台的服务程序。
2、CreateMutex
[DllImport("Coredll.dll", EntryPoint = "CreateMutex")]
private static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner, string lpWindowName);
[DllImport("coredll.Dll", SetLastError = true)]
private static extern int ReleaseMutex(IntPtr hMutex);
[DllImport("coredll.dll")]
private static extern int GetLastError();
private const int ERROR_ALREADY_EXISTS = 183;
IntPtr hMutex = CreateMutex(IntPtr.Zero, false, @"ScanEmul");
if (hMutex == IntPtr.Zero)
{
throw new ApplicationException("Failure creating mutex: "
+ Marshal.GetLastWin32Error().ToString("X"));
}
int i = Marshal.GetLastWin32Error();
if (Marshal.GetLastWin32Error() != ERROR_ALREADY_EXISTS)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = @"\Windows\ScanEmul.exe";//需要启动的程序名
p.Start();//启动
if (p.HasExited)//判断是否运行结束
p.Kill();
}
ReleaseMutex(hMutex);
但是也找不到后台的服务程序
3、CreateToolhelp32Snapshot
[DllImport("toolhelp.dll")]
private static extern int Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("toolhelp.dll")]
private static extern int Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("toolhelp.dll", SetLastError = true)]
private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
private const uint TH32CS_SNAPPROCESS = 0x00000002;
private int GetProcessByName(string ProcessName)
{
IntPtr handle = IntPtr.Zero;
int id = 0;
try
{
handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 info = new PROCESSENTRY32();
info.dwSize = 1024;
int first = Process32First(handle, ref info);
if (first != 0)
do
{
if (string.Compare(info.szExeFile, ProcessName, true) == 0)
{
id = (int)info.th32ProcessID;
return id;
}
}
while (Process32Next(handle, ref info) != 0);
return id;
}
catch
{
return id;
}
}
private void isRun()
{
ProcessInfo[] list = ProcessCE.GetProcesses();
foreach (ProcessInfo item in list)
{
if (item.FullPath == @"\Windows\ScanEmul.exe")
{
// item.Kill();
isTure = true;
break;
}
}
//如果不存在,则启动
/* if (isTure == false)
{
Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = @"\Windows\ScanEmul.exe";//需要启动的程序名
p.Start();//启动
if (p.HasExited)//判断是否运行结束
p.Kill();
}*/
}
最后用此方法解决了后台服务程序的检测。