Windows下根據程序名稱找到窗口句柄並操作窗口

1、根據程序名稱找到進程

#include "stdafx.h"
#include<iostream>
#include<Windows.h>
#include<TlHelp32.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR c[]={L"cmd.exe"};	//定義字符串並初始化,c爲8長度,最後結尾有'\0',定義一個字符爲'x',  
HANDLE handle;	 //定義CreateToolhelp32Snapshot系統快照句柄 
HANDLE handle1;	 //定義要結束進程句柄 
handle=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);//獲得系統快照句柄 
PROCESSENTRY32 *info;	 //定義PROCESSENTRY32結構字指  

//PROCESSENTRY32  結構的 dwSize 成員設置成 sizeof(PROCESSENTRY32) 
 
info=new PROCESSENTRY32;             
 
info->dwSize=sizeof(PROCESSENTRY32); 
 
//調用一次 Process32First 函數,從快照中獲取進程列表 
 
Process32First(handle,info); 
 
//重複調用 Process32Next,直到函數返回 FALSE 爲止 
 
while(Process32Next(handle,info)!=FALSE) 
{ 
 
info->szExeFile;     //指向進程名字 
 
//比較字符串是否相同 
if( wcscmp(c,info->szExeFile) == 0 ) 
{ 
//根據進程ID打開進程
handle1=OpenProcess(PROCESS_TERMINATE,FALSE,info->th32ProcessID); 
//結束進程 
TerminateProcess(handle1,0); 
} 
}  
//關閉句柄
CloseHandle(handle); 
CloseHandle(handle1);
return 0;
}

2、根據進程ID找到窗口句柄並操作窗口

//定義進程ID和窗口句柄關聯結構體 
struct ProcessWindow 
{ 
DWORD dwProcessId; 
HWND hwndWindow; 
}; 

//定義回調函數
BOOL CALLBACK EnumWindowCallBack(HWND hWnd, LPARAM lParam) 
{ 
    ProcessWindow *pProcessWindow = (ProcessWindow *)lParam; 
DWORD dwProcessId; 
    GetWindowThreadProcessId(hWnd, &dwProcessId); 
// 判斷是否是指定進程的主窗口
if (pProcessWindow->dwProcessId == dwProcessId && IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) 
    { 
        pProcessWindow->hwndWindow = hWnd; 
return FALSE; 
    } 
return TRUE; 
}  
 
//... 
//根據進程ID找到窗口句柄並操作
ProcessWindow procwin; 
procwin.dwProcessId = info->th32ProcessID; //上一步遍歷得到的進程ID
procwin.hwndWindow = NULL;  

// 查找主窗口
EnumWindows(EnumWindowCallBack, (LPARAM)&procwin); 
//根據找到的窗口句柄顯示窗口
ShowWindow(procwin.hwndWindow,SW_SHOWNORMAL); 

//窗口置頂 
SetForegroundWindow(procwin.hwndWindow);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章