Espero no estar reinventando la rueda, pero aquí te dejo un par de funciones que pueden resultarte útiles:
Código Delphi
[-]
type
TWindowRec = record
ProcessId: Cardinal;
Handle: THandle;
end;
PWindowRec = ^TWindowRec;
function EnumWindowsProc(Handle: Thandle; lParam: LPARAM): BOOL; stdcall;
var
ProcessId: Cardinal;
begin
Result:= TRUE;
ProcessId:= 0;
GetWindowThreadProcessId(Handle, ProcessId);
if ProcessId = PWindowRec(lParam).ProcessId then
begin
PWindowRec(lParam).Handle:= Handle;
Result:= FALSE;
end;
end;
function GetWindowFromProcessId(ProcessId: Cardinal): THandle;
var
WindowRec: TWindowRec;
begin
FillChar(WindowRec,Sizeof(WindowRec),0);
WindowRec.ProcessId:= ProcessId;
EnumWindows(@EnumWindowsProc, LPARAM(@WindowRec));
Result:= WindowRec.Handle;
end;
function Ejecutar(Cmd: string; Timeout: Cardinal): THandle;
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
Ticks: Cardinal;
begin
Result:= 0;
FillChar(StartupInfo,Sizeof(StartupInfo),0);
StartupInfo.wShowWindow:= SW_SHOW;
Ticks:= GetTickCount;
if CreateProcess(nil,PChar(Cmd),nil,nil, FALSE, CREATE_NEW_CONSOLE or
NORMAL_PRIORITY_CLASS,nil,nil,StartupInfo, ProcessInfo) then
while (Result = 0) and (GetTickCount - Ticks < TimeOut) do
begin
Result:= GetWindowFromProcessId(ProcessInfo.dwProcessId);
if Result = 0 then Sleep(200);
end;
end;
procedure PonerDelante(Handle: THandle);
var
FgThreadId : DWORD;
AppThreadId : DWORD;
begin
FgThreadId := GetWindowThreadProcessId(GetForegroundWindow, nil);
AppThreadId := GetWindowThreadProcessId(Handle, nil);
AttachThreadInput(AppThreadId, FgThreadId, true);
SetForegroundWindow(Handle);
AttachThreadInput(AppThreadId, FgThreadId, false);
end;
Un ejemplo de como usar las funciones anteriores seria el siguiente:
Código Delphi
[-]
var
H: THandle;
begin
H:= Ejecutar('Notepad',5000);
if H <> 0 then
begin
PonerDelante(H);
keybd_event($41, 0, 0, 0);
keybd_event($41, 0, KEYEVENTF_KEYUP, 0);
end;
end;