//在多个程序交互运行时,常常出现一些问题。
//比如应用程序A,B,A与B有交互。如果B运行了几个实例,可能出现一些问题。
//如果在A程序里知道了B程序实例的数量,就可以进行报警提示。
//本文为此目的而写。
//本文在10.3 64/32,6.0版本都调试通过。
#include <vcl.h>
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include <iostream>
#include <vector>
using namespace std;
#if(__BORLANDC__<=1380) // 低版本
#else // Earlier Versions
void TcharToChar(const TCHAR * tchar, char * _char)
{
int iLength;
//获取字节长度
iLength = WideCharToMultiByte(CP_ACP, 0, tchar, -1, NULL, 0, NULL, NULL);
//将tchar值赋给_char
WideCharToMultiByte(CP_ACP, 0, tchar, -1, _char, iLength, NULL, NULL);
}
#endif
int GetProcessIDByName(const char* pName)//根据应用程序名称返回有几个应用程序在运行
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
int Count=0;
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
{
String str=pe.szExeFile;
char temp[100]={0};
#if(__BORLANDC__<=1380) // 低版本
sprintf(temp,"%10s",str.c_str());
#else // Earlier Versions
TcharToChar(pe.szExeFile,temp);
#endif
if (strcmp(temp, pName) == 0)
{
Count++;
//cout<<"get a"<<endl;
}
//printf("%-6d %s\n", pe.th32ProcessID, temp);
}
CloseHandle(hSnapshot);
return Count;
}
#if(__BORLANDC__<=1380) // 低版本
int main(int argc, char* argv[])
#else //高版本
int _tmain(int argc, _TCHAR* argv[])
#endif
{
cout<<GetProcessIDByName("notepad.exe")<<endl;
cout<<GetProcessIDByName("hdevelop.exe")<<endl;
//cout<<__BORLANDC__<<endl;
system("pause");
return 0;
}