c++ builder 得到程序运行的实例数量

//在多个程序交互运行时,常常出现一些问题。

//比如应用程序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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值