1. 程式人生 > >視窗前端顯示和置頂,傳送訊息

視窗前端顯示和置頂,傳送訊息

首先根據程序名獲取到程序的ID(這裡只是測試,所以只需要得到其中一個ID就行了)GetPidByProcessName
然後根據程序ID獲取視窗控制代碼 GetHwndByPid
最後將視窗前端顯示並置頂 ShowForeGround

//根據程序名獲取程序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) { return lppe.th32ProcessID; } } while (::Process32Next(hSnapshot, &lppe)); //查詢下一個程序 return 1; } //根據程序ID獲取視窗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() { DWORD dwPid = GetPidByProcessName(_T("notepad.exe")); HWND hWnd = GetHwndByPid(dwPid); ShowForeGround(hWnd); //傳送按鍵F1訊息,等同F1被按下 ::PostMessage(m_hwnd, WM_KEYDOWN, VK_F1, 0); ::PostMessage(m_hwnd, WM_KEYUP, VK_F1, 0); }