如何在Windows平台的Delphi中激活指定DirectX 9游戏窗口?
Delphi中激活无边框全屏DirectX9游戏窗口的实现方法
核心思路
要实现指定游戏窗口的捕捉与激活,需分两步:定位游戏窗口句柄,然后调用Windows API强制将其前置并激活。针对无边框全屏的DirectX9游戏,常规的SetForegroundWindow可能失效,需要结合多个API确保生效。
步骤1:获取游戏窗口句柄
可通过两种方式定位窗口:
- 通过窗口标题:使用
FindWindow函数(需准确知道游戏窗口标题) - 通过进程名:遍历所有窗口,匹配对应进程ID(适合窗口标题不固定的场景)
示例:通过进程名获取窗口句柄
function GetWindowHandleByProcessName(const ProcessName: string): HWND; var hWnd: HWND; PID: DWORD; begin Result := 0; hWnd := GetWindow(GetDesktopWindow(), GW_CHILD); while hWnd <> 0 do begin if IsWindowVisible(hWnd) then begin GetWindowThreadProcessId(hWnd, @PID); if PID <> 0 then begin if LowerCase(GetProcessName(PID)) = LowerCase(ProcessName) then begin Result := hWnd; Break; end; end; end; hWnd := GetWindow(hWnd, GW_HWNDNEXT); end; end; function GetProcessName(PID: DWORD): string; var hProcess: THandle; Buffer: array[0..MAX_PATH] of Char; begin Result := ''; hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if hProcess <> 0 then begin if GetModuleFileNameEx(hProcess, 0, Buffer, SizeOf(Buffer)) > 0 then Result := ExtractFileName(Buffer); CloseHandle(hProcess); end; end;
步骤2:激活并前置窗口
针对无边框全屏的DX9游戏,需先恢复窗口状态(若最小化),再通过AttachThreadInput解决线程关联问题,确保SetForegroundWindow生效:
按钮点击事件示例
procedure TForm1.Button1Click(Sender: TObject); var GameHWND: HWND; CurrentThreadID, GameThreadID: DWORD; begin // 替换为你的游戏进程名,例如'Game.exe' GameHWND := GetWindowHandleByProcessName('Game.exe'); if GameHWND = 0 then begin ShowMessage('未找到游戏窗口'); Exit; end; // 若窗口最小化,先恢复正常状态 if IsIconic(GameHWND) then ShowWindow(GameHWND, SW_RESTORE); // 关联线程,确保窗口激活生效 CurrentThreadID := GetCurrentThreadId(); GameThreadID := GetWindowThreadProcessId(GameHWND, nil); if AttachThreadInput(CurrentThreadID, GameThreadID, True) then try SetForegroundWindow(GameHWND); SetFocus(GameHWND); // 可选:先强制置顶再取消,确保窗口前置 SetWindowPos(GameHWND, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE); SetWindowPos(GameHWND, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE); finally AttachThreadInput(CurrentThreadID, GameThreadID, False); end; end;
注意事项
- 权限匹配:如果游戏以管理员身份运行,你的Delphi程序也需以管理员权限启动,否则无法修改游戏窗口状态。
- 单元引用:确保项目
uses中包含Windows, SysUtils, Psapi,否则相关API无法调用。 - 标题变动处理:若游戏窗口标题动态变化,优先使用进程名方式定位窗口。
内容的提问来源于stack exchange,提问作者Shaun Roselt
相关产品推荐
相关产品推荐

