Win 10:Cmd 可以将 windows 带到前台,但任何其他终端都不能(即使提升)。为什么会这样?

Win 10: Cmd can bring windows to foreground, but any other terminal can't(even if elevated). Why is this so?

我正在使用 pygetwindow 通过它的标题将 window 带到前台。如果我从 cmd(和 PowerShell)运行 我的 python 脚本,它就可以完美地工作。但是如果我从任何其他终端 运行 它,比如 Alacritty,而不是来到前台,提到的 window 只是开始在任务栏中闪烁。

为什么会这样?我已将 Alacritty 配置为使用 cmd。

以下是我的代码的相关部分:

import pygetwindow
try:
        window = pygetwindow.getWindowsWithTitle('foobar')[0]
        window.activate()
    except Exception as e:
        #raise e
        print("open foobar please")
        exit(1)

下面是我的 alacritty 配置的相关部分

# Shell
# You can set `shell.program` to the path of your favorite shell, e.g. `/bin/fish`.
# Entries in `shell.args` are passed unmodified as arguments to the shell.
# Default:
#   - (macOS) /bin/bash --login
#   - (Linux/BSD) user login shell
#   - (Windows) powershell
  shell:
    program: cmd.exe
    args:
            - /s /k pushd C:\Users\interesting\bug\hunt\Repos

谢谢

您的程序必须符合以下条件之一才能设置活动window(使用API调用SetForegroundWindow).

您可能会发现使用 SendKeys 发送系统击键(如 Ctrl+Tab)对您有用,但您需要能够预测您的 z-order。

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

•The process is the foreground process.

•The process was started by the foreground process.

•The process received the last input event.

•There is no foreground process.

•The process is being debugged.

•The foreground process is not a Modern Application or the Start Screen.

•The foreground is not locked (see LockSetForegroundWindow).

•The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).

•No menus are active.

https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow

这些限制的目的是为了解决程序窃取焦点的问题。所以基本上如果用户点击另一个 window 用户的选择获胜。

启动程序时,程序有两秒钟显示 window。如果用户在两秒内程序显示它的 window 之前单击另一个 window,则该程序仍将成为活动的 window。如果程序花费的时间超过 2 秒并且用户点击离开,则用户的 window 将成为活动的 window。

另见 https://devblogs.microsoft.com/oldnewthing/20090220-00/?p=19083 进行讨论。