The GetWindowThreadProcessId function retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window. This function supersedes the GetWindowTask function.
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function EnumWindowsProc (Wnd: HWND; lb: TListbox): BOOL; stdcall;
var
caption: array [0..128] of Char;
begin
Result := True;
if IsWindowVisible(Wnd) and
((GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) or
(HWND(GetWindowLong(Wnd, GWL_HWNDPARENT)) = GetDesktopWindow)) and
((GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW) = 0)
then begin
SendMessage( Wnd, WM_GETTEXT, Sizeof( caption ), integer(@caption));
lb.Items.AddObject( caption, TObject( Wnd ));
end;
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var
theClassname,path: array [0..255] of Char;
Wnd,hModule,hProcess: HWND;
tid, pid,Needed: DWORD;
begin
with Sender as TListbox do begin
If ItemIndex >= 0 then begin
Wnd:= HWND(Items.Objects[ itemindex ]);
If Wnd <> 0 then begin
Windows.GetClassname( Wnd, theClassname, Sizeof( classname ));
tid := GetWindowThreadProcessID( Wnd, @pid );
hProcess:=OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,False,PID);
if hProcess>0 then
begin
EnumProcessModules(hProcess,@hModule,SizeOf(hModule),Needed);
GetModuleFileNameEx(hProcess,hModule,Path,SizeOf(Path));
GetShortPathName(Path,Path,256);
end;
label1.caption :=
Format(
'HWND: %8.8x'#13#10+
'Class: %s'#13#10+
'Process ID: %8.8x'#13#10+
'Thread ID: %8.8x'#13#10+
'Path:%s',
[Wnd, theClassname, pid, tid, path] );
end;
end;
end;
end;
//还有别忘了在 uses 部分加上TLHelp32单元
function GetAppName(const AWindowHandle: THandle): string;
var
PI: DWORD;
ContinueLoop:BOOL;
SnapshotHandle:THandle;
ProcessEntry32:TProcessEntry32;
begin
Result := '';
GetWindowThreadProcessId(AWindowHandle, @PI);
SnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
ProcessEntry32.dwSize := Sizeof(ProcessEntry32);
ContinueLoop := Process32First(SnapshotHandle,ProcessEntry32);
while ContinueLoop do
begin
if ProcessEntry32.th32ProcessID = PI then
begin
Result := ProcessEntry32.szExeFile;
break;
end;
ContinueLoop:=Process32Next(SnapshotHandle, ProcessEntry32);
end;
CloseHandle(SnapshotHandle);
end;