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