//
/應用程式程序自檢,防止應用已被打開,占用了硬體端口,導緻後啟動的軟體無法正常使用/
//
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