WINDOWS API ——CREATETOOLHELP32SNAPSHOT——查找进程
原文:http://www.cnblogs.com/wind-net/archive/2012/10/26/2741458.html
//根据进程名获取进程ID DWORD GetPidByProcessName(TCHAR *pProcess) { HANDLE hSnapshot; PROCESSENTRY32 lppe; //创建系统快照 hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); //#include<Tlhelp32.h> if (hSnapshot == NULL) return 0; //初始化 lppe 的大小 lppe.dwSize = sizeof(lppe); //查找第一个进程 if (!::Process32First(hSnapshot, &lppe)) return false; do { if(StrCmp(lppe.szExeFile, pProcess) == 0)//#include<shlwapi.h> { return lppe.th32ProcessID; } } while (::Process32Next(hSnapshot, &lppe)); //查找下一个进程 return 1; } //根据进程ID获取窗口句柄 HWND GetHwndByPid(DWORD dwProcessID) { //返回Z序顶部的窗口句柄 HWND hWnd = ::GetTopWindow(0); while ( hWnd ) { DWORD pid = 0; //根据窗口句柄获取进程ID DWORD dwTheardId = ::GetWindowThreadProcessId( hWnd,&pid); if (dwTheardId != 0) { if ( pid == dwProcessID ) { return hWnd; } } //返回z序中的前一个或后一个窗口的句柄 hWnd = ::GetNextWindow(hWnd , GW_HWNDNEXT); } return hWnd; } //前端显示并置顶窗口 void ShowForeGround(HWND hWnd) { if (hWnd) { //显示窗口 ::ShowWindow(hWnd, SW_NORMAL); //前端显示 ::SetForegroundWindow(hWnd); //窗口置顶 ::SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE); } else { ::MessageBox(NULL, _T("未找到窗口"), _T("提示"),MB_OK); } } void CMFCApplication1Dlg::OnBnClickedMfcbutton1() { // TODO: 在此添加控件通知处理程序代码 DWORD dwPid = GetPidByProcessName(_T("notepad.exe")); HWND hWnd = GetHwndByPid(dwPid); ShowForeGround(hWnd); }