C++程序檢測,發現程序路徑,關閉程序(一)
阿新 • • 發佈:2019-02-20
#include "stdafx.h"
#include <windows.h>
#include "stdio.h"
#include <tlhelp32.h>
#include "Psapi.h"
BOOL DosPathToNtPath(LPTSTR pszDosPath, LPTSTR pszNtPath)
{
TCHAR szDriveStr[500];
TCHAR szDrive[3];
TCHAR szDevName[100];
INT cchDevName;
INT i;
//檢查引數
if(!pszDosPath || !pszNtPath )
return FALSE;
//獲取本地磁碟字串
if(GetLogicalDriveStrings(sizeof(szDriveStr), szDriveStr)) //"szDriveStr包含各個分割槽c:\\, d:\\, e:\\, f:\\"
{
for(i = 0; szDriveStr[i]; i += 4)
{
if(!lstrcmpi(&(szDriveStr[i]), _T("A:\\")) || !lstrcmpi(&(szDriveStr[i]), _T("B:\\")))
continue;
szDrive[0] = szDriveStr[i];
szDrive[1] = szDriveStr[i + 1];
szDrive[2] = '\0';
if(!QueryDosDevice(szDrive, szDevName, 100))//查詢 Dos 裝置,並給szDevName賦值為:\\Device\\HarddiskVolume2
return FALSE;
cchDevName = lstrlen(szDevName);
if(_tcsnicmp(pszDosPath, szDevName, cchDevName) == 0)//命中
{
lstrcpy(pszNtPath, szDrive);//複製驅動器
lstrcat(pszNtPath, pszDosPath + cchDevName);//複製路徑
return TRUE;
}
}
}
lstrcpy(pszNtPath, pszDosPath);
return FALSE;
}
BOOL GetProcessFullPath(DWORD dwPID, TCHAR pszFullPath[MAX_PATH])
{
TCHAR szImagePath[MAX_PATH];
HANDLE hProcess;
if(!pszFullPath)
return FALSE;
pszFullPath[0] = '\0';
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, dwPID);
if(!hProcess)
return FALSE;
if(!GetProcessImageFileName(hProcess, szImagePath, MAX_PATH)) //獲取程序路徑名(包含裝置地址)\\Device\\HarddiskVolume2\\Program files\\**
{
CloseHandle(hProcess);
return FALSE;
}
if(!DosPathToNtPath(szImagePath, pszFullPath)) //將路徑名從包含裝置地址的字串中提取出來
{
CloseHandle(hProcess);
return FALSE;
}
CloseHandle(hProcess);
return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{
int num=0;
TCHAR exe_name[20]=_T("notepad++.exe");//要查詢的程序名
TCHAR pszFullPath[MAX_PATH];
PROCESSENTRY32 pe32;//用於存放程序資訊的結構體
HANDLE hProcessSnap=::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);//建立程序快照
pe32.dwSize=sizeof(pe32);
if(hProcessSnap==INVALID_HANDLE_VALUE)
{
printf("CreateToolhelp32Snapshot failed!\n");
return -1;
}
BOOL bMore=::Process32First(hProcessSnap,&pe32);//獲取第一個程序資訊到pe32結構體中
while(bMore)
{
printf("name is: %ls\n",pe32.szExeFile);
printf("num is: %d\n",num);
printf("ID is: %d\n",pe32.th32ProcessID);
if(!_tcscmp(exe_name,pe32.szExeFile))//發現要尋找的程序後結束查詢
{
printf("find the file you want: %ls\n",pe32.szExeFile);
break;
}
num++;
bMore=::Process32Next(hProcessSnap,&pe32);
}
if(!_tcscmp(exe_name,pe32.szExeFile))
{
if(GetProcessFullPath(pe32.th32ProcessID, pszFullPath))//根據程序ID獲取程序路徑名
printf("the path of the process is: %ls\n\n",pszFullPath);
HANDLE hprocess=::OpenProcess(PROCESS_ALL_ACCESS,FALSE,pe32.th32ProcessID);
if(hprocess!=NULL)
{
::TerminateProcess(hprocess,0);//關閉程序
printf("I have close the process you choose!\n");
::CloseHandle(hprocess);
}
}
CloseHandle(hProcessSnap);
getchar();//讓程式有輸入,在結束
return 0;
}