【问题标题】:Issues Adding Variable To getWindowsWithTitle向 getWindowsWithTitle 添加变量的问题
【发布时间】:2022-01-19 05:16:30
【问题描述】:

所以我在使用 pygetwindow 的 getWindowsWithTitle 函数时遇到问题。当我在 getWindowsWithTitle 调用之前要求输入时,我收到以下错误:

Traceback (most recent call last):
  File "*****\main.py", line 79, in <module>
    handle.activate()
  File "*****\venv\lib\site-packages\pygetwindow\_pygetwindow_win.py", line 246, in activate
    _raiseWithLastError()
  File "*****\venv\lib\site-packages\pygetwindow\_pygetwindow_win.py", line 99, in _raiseWithLastError
    raise PyGetWindowException('Error code from Windows: %s - %s' % (errorCode, _formatMessage(errorCode)))
pygetwindow.PyGetWindowException: Error code from Windows: 0 - The operation completed successfully.

如果我注释掉我的 Input 调用,getWindowsWithTitle 就可以正常工作。以下是我目前的代码

import win32gui
import time
from pynput.keyboard import Key, Controller
import pygetwindow as window


target = input("** Instance Name Is The Title When You Hover Over The Application ** \nSelect Instance Name: ")
handle = window.getWindowsWithTitle('Command')[0]

keyboard = Controller()
handle.activate()
handle.maximize()
time.sleep(2)
keyboard.press('a')
keyboard.release('a')

我正在尝试获取输入以选择要选择的窗口,但即使将“目标”放在 getWindowsWithTitle 中,它也会给我同样的错误。有谁知道为什么我在输入后会收到此错误?

【问题讨论】:

  • 有人能帮忙吗?

标签: python pycharm pywin32


【解决方案1】:

我已经简要地查看了[GitHub]: asweigart/PyGetWindow - PyGetWindow。我强烈建议不要使用它,因为它有问题(至少是当前版本):

  1. 主要的、通用的、概念性的缺陷。它使用 CTypes,但方式不正确。我想知道为什么没有很多针对它的错误提交。更多详情请查看[SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)

  2. 在您的特定情况下,会引发异常。该行为是不正确的(您会得到错误代码0,这意味着成功(ERROR_SUCCESS)。 [MS.Docs]: SetForegroundWindow function (winuser.h) 没有指定在函数失败时使用 GetLastError (没有做它应该做的事情)。只是因为上面提到的一些原因,窗口不能被带到前面

由于您为 PyWin32 标记了您的问题,因此您可以使用它。

code00.py

#!/usr/bin/env python

import sys
import time
import pynput
import win32con as wcon
import win32gui as wgui


# Callback
def enum_windows_proc(wnd, param):
    if wgui.IsWindowVisible(wnd):
        text = wgui.GetWindowText(wnd)
        if param[0] in text.upper():
            print(wnd, text)  # Debug purposes only
            param[1].append(wnd)


def windows_containing_text(text):
    ret = []
    wgui.EnumWindows(enum_windows_proc, (text.upper(), ret))
    return ret


def send_char(wnd, char):
    kb = pynput.keyboard.Controller()
    kb.press(char)
    kb.release(char)


def main(*argv):
    txt = input("Enter text contained by window title: ")
    #txt = "notepad"
    wnds = windows_containing_text(txt)
    print(wnds)
    wnd = wnds[1]  # Notepad in my case (this example only, list might have fewer elements!!!!!)
    try:
        wgui.SetForegroundWindow(wnd)  # Activate
    except:
        print(sys.exc_info())
    wgui.ShowWindow(wnd, wcon.SW_MAXIMIZE)  # Maximize
    time.sleep(1)
    send_char(wnd, "a")


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

查看[SO]: Get the title of a window of another program using the process name (@CristiFati's answer) 了解有关此WinAPI 区域的更多详细信息。

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q070373526]> "e:\Work\Dev\VEnvs\py_pc064_03.08.07_test0\Scripts\python.exe" code00.py
Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)] 064bit on win32

Enter text contained by window title: notepad
394988 e:\Work\Dev\StackOverflow\q070373526\code00.py - Notepad++ [Administrator]
4264044 *Untitled - Notepad
[394988, 4264044]

Done.

一个“achar被插入到记事本窗口的光标位置。

【讨论】:

  • 感谢您的回复,非常有帮助。因此,当我运行您的代码时,我遇到了一些事情。首先,如果我只有一个项目的 1 个副本,则打开 wnd = wnds[1] 错误导致索引超出范围,因此我将其更改为 wnd = wnds[0]。现在我似乎遇到了“pywintypes.error: (126, 'SetForegroundWindow', 'The specified module could not be found.')”
  • 有趣的是,我发现如果我在设置windows之前和之后执行send_char命令,它工作得很好,但是如果我之前不这样做,SetForegroundWindow就会出错。
  • wnd = wnds[1] # Notepad in my case 正如评论所暗示的那样,在我的情况下,尤其是对于此示例,该列表有 2 个条目。关于您遇到的错误,这很奇怪。我想这取决于您要激活的窗口,以及用户类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多