You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:50:06