//
/应用程序进程自检,防止应用已被打开,占用了硬件端口,导致后启动的软件无法正常使用/
//
void AppProcessOfSelfCheck()
{
//进程自检
QString strCurrentAppPath = QCoreApplication::applicationFilePath();
QFileInfo fileInfo(strCurrentAppPath);
QString str_app_name = fileInfo.fileName();
QByteArray chStrArray = str_app_name.toLocal8Bit();
const char ch_app_name = chStrArray.constData();
PowerController power;
power.AppOfSelfCheck(ch_app_name);
}
}
/********************************/
PowerController.h文件
/**
Description:
应用程序进程自检
@param 无
@return 无
/
void AppOfSelfCheck(const char pName);
/**
Description:
关闭当前进程
@param 无
@return 无
*/
void KillCurrentProcess();
PowerController.cpp文件
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include “PowerController.h”
/---------------应用程序进程自检---------------/
#pragma region 应用程序进程自检接口函数
/************************************************************************/
/通过进程ID获取进程句柄 /
/**********************************************************************/
HANDLE GetProcessHandleByID(DWORD nID)
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}
/************************************************************************/
/获取指定进程名的所有进程ID 比如 “IS05.exe” /
/*********************************************************************/
std::vector GetProcessIDByName(const char pName)
{
std::vector vecProcessId;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return vecProcessId;
}
PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
{
if (strcmp(pe.szExeFile, pName) == 0)
{
DWORD pid;
pid = pe.th32ProcessID;
vecProcessId.push_back(pid);
printf("%-6d %s\n", pe.th32ProcessID, pe.szExeFile);
}
}
CloseHandle(hSnapshot);
return vecProcessId;
}
//
/应用程序进程自检,防止应用已被打开,占用了硬件端口,导致后启动的软件无法正常使用/
//
void PowerController::AppOfSelfCheck(const char pName)
{
std::vector pidList = GetProcessIDByName(pName);
for (int i = 0; i < pidList.size(); i++)
{
if (GetCurrentProcessId() != pidList[i])
{
HANDLE hSnapshot = NULL;
hSnapshot = GetProcessHandleByID(pidList[i]);
if (hSnapshot)
{
TerminateProcess(hSnapshot, 0);
CloseHandle(hSnapshot);
}
}
}
}
//
/杀死当前进程/
/*/
void PowerController::KillCurrentProcess()
{
HANDLE hSnapshot = NULL;
hSnapshot = GetProcessHandleByID(GetCurrentProcessId());
if (hSnapshot)
{
TerminateProcess(hSnapshot, 0);
CloseHandle(hSnapshot);
}
}
#pragma endregion