#include "myprocess.h"//随意创建的一个QT界面类
#include <QtWidgets/QApplication>
#include <QFileInfo>
#include <QString>
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <iostream>
#include <vector>
//通过进程ID获取进程句柄
HANDLE GetProcessHandleByID(DWORD nID)
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}
//获取指定进程名的所有进程ID列表
std::vector<DWORD> GetProcessIDByName(const char* pName)
{
std::vector<DWORD> 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);
}
//printf("%-6d %s\n", pe.th32ProcessID, pe.szExeFile);//打印所以进程列表中的所以进程
}
CloseHandle(hSnapshot);
return vecProcessId;
}
//自检当前进程,杀掉与当前进程名一样的进程,保留当前进程(目的:防止用户重复启动当前软件,导致软件无法正常运行)
void AppOfSelfCheck(const char* pName)//pName (xxx.exe)
{
std::vector<DWORD> 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);
}
}
}
printf("pid = %u\n", pidList.size());
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);//argv 应用程序所在的绝对路径
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();//当前进程名
printf("ch_app_name=%s--------\n", ch_app_name);
AppOfSelfCheck(ch_app_name);//自检当前应用是否被打开,如果已被打开,则杀到与当前进程名一样的进程,保留当前启动进程
MyProcess w;//随意创建的一个QT界面类
w.show();//显示
return a.exec();
}