unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ShellAPI, TlHelp32;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TEnumData = record
hW: HWND;
pID: DWORD;
end;
function EnumProc( hw: HWND; var data: TEnumData ): Bool; stdcall;
var
pID: DWORD;
begin
Result := True;
if (GetWindowLong(hw, GWL_HWNDPARENT) = 0) and
(IsWindowVisible( hw ) or IsIconic(hw)) then
begin
GetWindowThreadProcessID( hw, @pID );
If pID = data.pID then
begin
data.hW := hW;
Result := False;
end; { If }
end; { If }
end; { EnumProc }
function WindowFromProcessID( pID: DWORD ): HWND;
var
data: TEnumData;
begin
data.pID := pID;
data.hW := 0;
EnumWindows( @EnumProc, longint(@data) );
Result := data.hW;
end; { WindowFromProcessID }
function WindowFromAppname32( appname: String ): HWND;
{ Take only the application filename, not full path!
Need to pass the extension as well. }
var
snapshot: THandle;
processEntry : TProcessEntry32;
begin
Result := 0;
appName := UpperCase( appname );
snapshot := CreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS,
0 );
if snapshot <> 0 then
try
processEntry.dwSize := Sizeof( processEntry );
if Process32First( snapshot, processEntry ) then
repeat
if AnsiCompareText(
appname,
ExtractFilename( StrPas(processEntry.szExeFile))
) = 0
then
begin
Result:= WindowFromProcessID( processEntry.th32ProcessID);
Break;
end; { If }
until not Process32Next( snapshot, processEntry );
finally
CloseHandle( snapshot );
end; { try }
end; { WindowFromAppname32 }
procedure TForm1.Button1Click(Sender: TObject);
var
x: THandle;
begin
ShellExecute(0, 'open', 'c:\WINDOWS\notepad.exe','', '', SW_SHOW);
x := WindowFromAppname32('NotePad.exe');
ShowMessage(IntToStr(x));
end;
end.
|