用网上的源程序,编译成32位应用时没问题,64位时值为0。是为什么。 function GetHWndByPID(const hPID: THandle): THandle; type PEnumInfo = ^TEnumInfo; TEnumInfo = record ProcessID: DWORD; HWND: THandle; end;
function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall; 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;
//窗体枚举结构 TEnumInfo = record ProcessID: DWORD; //进程ID HWND: THandle; //窗体句柄 HTHD: THandle; //窗体线程句柄 CaptionFlag: array[0..254] of char; //窗体标题关键字 end;
//通过进程ID枚举找到进程主窗体 //EI:包含进程信息的结构体(可扩展) function EnumWindowsProc(Wnd: DWORD; var EI: TEnumInfo): Bool; stdcall; var PID: DWord; h: THandle; arr: array[0..254] of Char; tmpIsFlag:Boolean; tmpThreadID:THandle; begin Result := True; tmpThreadID:=GetWindowThreadProcessID(Wnd, @PID); if PID = EI.ProcessID then //是指定进程的窗体 begin h := GetWindowLong(Wnd, GWL_HWNDPARENT); if h = 0 then begin tmpIsFlag:=true; if EI.CaptionFlag<>'' then //需要按标题过滤 begin tmpIsFlag:=false; GetWindowText(Wnd,@arr, SizeOf(arr)); if Pos(EI.CaptionFlag,arr)>0 then //标题包含指定关键字 tmpIsFlag:=true; end;
if tmpIsFlag then begin EI.HWND := Wnd; //窗体句柄 EI.HTHD:=tmpThreadID; //窗体线程句柄 Result := False; end; end; end; if not Result then EI.HWND := WND; end;
if tmpIsFlag then begin EI.HWND := Wnd; //窗体句柄 EI.HTHD:=tmpThreadID; //窗体线程句柄 //Result := False; Result:=(PID <> EI.ProcessID) or (not IsWindowVisible(WND)) or (not IsWindowEnabled(WND)); end;