pi.hProcess 只是一个进程句柄,和窗口句柄是两码事,当然不能混为一谈了。<br><br>通过进程句柄获得主窗口句柄我暂时没有好的办法,只能枚举所有窗口,然后<br>判断每个窗口对应的进程是否为指定进程号。<br>你前面的 MyWinExec 应略作修改:<br><br>function MyWinExec(const CmdLine: string; CmdShow: DWord): THandle;<br>var<br> SI :TStartupInfo;<br> PI :TProcessInformation;<br>begin<br> FillChar(si,SizeOf(si),0);<br> si.cb:=SizeOf(si);<br> si.dwFlags:=STARTF_USESHOWWINDOW;<br> si.wShowWindow:=CmdShow;<br> if CreateProcess(nil,PChar(CmdLine),nil,nil,false,0,nil,nil,si,pi) then<br> Result:=pi.dwProcessId // 这里改成进程号!!!!!<br> else<br> Result:=0;<br>end;<br><br>// 通过进程号查找主窗口句柄<br>function GetApplicationWnd(const ProcessID: DWORD): HWND;<br>type<br> PTopLevelWnd = ^TTopLevelWnd;<br> TTopLevelWnd = record<br> ProcessID: DWORD;<br> Wnd: HWND;<br> end;<br>var<br> TopLevelWnd: TTopLevelWnd;<br><br> function EnumWinProc(Wnd: HWND; Param: PTopLevelWnd): BOOL; stdcall;<br> var<br> PID: DWORD;<br> C: array [0..Length(ClassNameOfTApplication) + 1] of Char;<br> begin<br> GetWindowThreadProcessId(Wnd, @PID);<br> if (PID = Param^.ProcessID) and (GetClassName(Wnd, C, SizeOf(C)) > 0) and<br> (C = ClassNameOfTApplication) then<br> begin<br> Result := False;<br> Param^.Wnd := Wnd;<br> end<br> else<br> Result := True;<br> end;<br><br>begin<br> TopLevelWnd.ProcessID := ProcessID;<br> TopLevelWnd.Wnd := 0;<br> EnumWindows(@EnumWinProc, LPARAM(@TopLevelWnd));<br> Result := TopLevelWnd.Wnd;<br>end;<br><br><br>然后就像这样使用:<br><br>var<br> s: string;<br> pid: DWord;<br> h: THandle;<br>begin<br> pid := MyWinExec('C:/WINNT/system32/notepad.exe', SW_Show);<br> h := GetApplicationWnd(pid);<br> SetLength(s, 255);<br> GetWindowText(h, PChar(s), Length(s));<br> ShowMessage(s);<br>end;<br><br>