进程名称获取窗口句柄&进程名杀死进程
如何获得一个已经运行起来,但是仅知道进程名称,没有窗口标题,与调用程序没有特殊关系(如父子关系),并且其它条件(如是否置顶)任意的应用程序的窗口句柄????
加头文件:#include “tlhelp32.h”
C++代码现成如下,感谢分享者,注释添加:C++程序员之家:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
HWND GetXHandle(CString procName) { DWORD iProcID=0; PROCESSENTRY32 pEntry={sizeof(PROCESSENTRY32)}; HANDLE hSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPALL,0); if(hSnapshot!=INVALID_HANDLE_VALUE) { if(Process32First(hSnapshot,&pEntry)) { while (Process32Next(hSnapshot, &pEntry)) { if(lstrcmpi(procName, pEntry.szExeFile) == 0) { iProcID=pEntry.th32ProcessID; CloseHandle(hSnapshot); break; } } } } HWND hwnd=::GetTopWindow(NULL); while(hwnd) { DWORD pid=0; DWORD dwProcessId=GetWindowThreadProcessId(hwnd,&pid); if(dwProcessId!=0) { if(pid==iProcID) { return hwnd; } } hwnd=::GetNextWindow(hwnd,GW_HWNDNEXT); } return NULL; } |
知道进程名,如果结束程序呢(更简单的有taskkill命令)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
BOOL KillProcess(const TCHAR *szName) { BOOL bResult = FALSE; HANDLE hSnapshot = NULL; PROCESSENTRY32 ProcessEntry; DWORD dwPID = 0; hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); ProcessEntry.dwSize = sizeof(PROCESSENTRY32); bResult = Process32First(hSnapshot,&ProcessEntry); while(bResult) { //判断是否为要结束的进程 if (0 == _tcscmp(szName,ProcessEntry.szExeFile) ) { dwPID = ProcessEntry.th32ProcessID; break; } //获取下一个进程 bResult = Process32Next(hSnapshot,&ProcessEntry); } HANDLE hProcess = NULL; hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwPID); //结束进程 if(hProcess) { bResult = TerminateProcess(hProcess,0); } return bResult; } |
知识来源:[and_tt的博客] & CSDN & baike_baidu