您的位置:首页 > 编程语言 > Delphi

Delphi 获取其他程序窗口句柄

2018-01-30 11:02 861 查看
var
 HCurrentWindow:HWnd;
 Str:String;
begin
 HCurrentWindow:= GetWindow(Handle,GW_HWNDFIRST);
 while HCurrentWindow <>0 do
 begin
 Str:=GetWndText(HCurrentWindow);
  if UpperCase(Str)='frmMain(//窗口的标题)' then
  begin
   Syslog('获取成体句柄成功');
  end;
 HCurrentWindow:=Get(HCurrentWindow, GW_HWNDNEXT);
 end;
end;

--------------------------------------------我是分割线-----------------------------------------------
需引入 TLHelp32;
uses TLHelp32;
var
ProcessName:String;   // 进程名
FSeapshotHandle:THandle; // 进程快照句柄
FProcessEntry32:TProcessEntry32;  // 进程入口的结构体信息
ContinueLoop:Bool;      // 是否继续循环
MyHwnd:THandle;    
begin
 FSnapshotHandle:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);  // 创建一个进程快照
 FProcessEntry32.dwSize := Sizeof(FprocessEntry32);
 ContinueLoop :=Process32First(FSnapshotHandle,FProcessEntry32);  // 得到系统中的第一个进程
 while ContinueLoop do
 begin
 ProcessName:= FProcessEntry32.szExeFile;
  if (ProcessName = '程序名称.exe')  then
   begin
   MyHwnd := GetHWndByPID(FProcessEntry32.th32ProcessID);
    end;
    ContinueLoop := Process32Next(FSnapshotHandle,FProcessEntry32);
 end;
  CloseHandle(FSnapshotHandle);   // 释放快照句柄
end;
// 根据ProcessId 获取进程窗口的句柄
function TForm1.GetHWndByPID(const hPid:THandle): Thandle;
type
PEnuminfo = ^TEnuminfo;
TEnuminfo = record
ProcessID: DWORD;
HWND:THandle;
end;
Function EnumWindowsProc(Wnd:DWORD; var EI:TEnumInfo): Bool;
var
PID:DWORD;
begin
GetWindowThreadProcessID(Wnd,@PID);
Result := (PID<> EI.ProcessID) or
(not IsWindowVisible(WND)) or
(not IsWindowEnabled(WND));
if not Result then EI.HWND := WND;
end;
function FindMainWindow(PID: DWORD):DWORD;

var
EI:TEnumInfo;
begin
EI.ProcessID := PID;
EI.HWND := 0;
EnumWindows(@EnumWindowsProc,Integer(@EI));
Result := EI.HWND;
end;
begin
if hPID <> 0 then
Result := FindMainWindow(hPID)
else
Result:=0;
end;

引用::http://blog.csdn.net/chinazhd/article/details/6566535
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: