pywin32 SetFocus 导致 'Access is denied' 错误

pywin32 SetFocus resulting in 'Access is denied' error

我正在创建一个将鼠标输入发送到特定 window 的脚本。我发现这样做的唯一方法是将焦点设置到 window。如果有其他方法请说明。 无论如何,这是无效的代码。

from win32gui import *
us_ip = input('Version of Minecraft: ')

minecraft_handle = FindWindow(None, f'Minecraft {us_ip}')
SetFocus(minecraft_handle)

我可以检索 HWND,但是当我 运行 程序时出现此错误。

Traceback (most recent call last):
  File "c:\Users\Jacob Daniels\Desktop\python\autoclicker\windows api experimentation\py.py", line 5, in <module>
    SetFocus(minecraft_handle)
pywintypes.error: (5, 'SetFocus', 'Access is denied.')

如有任何帮助,我们将不胜感激。 图书馆文件: http://timgolden.me.uk/pywin32-docs/win32_modules.html 编辑:发布了错误的错误消息

根据[MS.Docs]: SetFocus function重点是我的):

Sets the keyboard focus to the specified window. The window must be attached to the calling thread's message queue.

...

By using the AttachThreadInput function, a thread can attach its input processing to another thread. This allows a thread to call SetFocus to set the keyboard focus to a window attached to another thread's message queue.

显然“远程”window 没有附加到 Python 脚本(主)线程,因此需要注意(需要一些额外的工作)。

code00.py:

#!/usr/bin/env python

import sys
import win32gui as wgui
import win32process as wproc
import win32api as wapi


def main(*argv):
    if not argv:
        window_name = input("Enter window name: ")
    else:
        window_name = argv[0]

    handle = wgui.FindWindow(None, window_name)
    print("Window `{0:s}` handle: 0x{1:016X}".format(window_name, handle))
    if not handle:
        print("Invalid window handle")
        return
    remote_thread, _ = wproc.GetWindowThreadProcessId(handle)
    wproc.AttachThreadInput(wapi.GetCurrentThreadId(), remote_thread, True)
    prev_handle = wgui.SetFocus(handle)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main(*sys.argv[1:])
    print("\nDone.")

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q062649124]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code00.py "Untitled - Notepad"
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 64bit on win32

Window `Untitled - Notepad` handle: 0x0000000004A520AA

Done.

不用说记事本window就在Cmd终端前弹出了。
请注意,对于某些 windows,它可能不起作用。