win32com.client - SendKeys() 不发送 backets

win32com.client - SendKeys() not sending backets

我正在使用 win32com 进行 windows 自动化,我正在尝试将密钥发送到某些应用程序,但它没有发送 backets 示例:(尝试发送)

name = "Jayesh (Nick Name)"
shell.SendKeys(name)

预期输出:

Jayesh (Nick Name)

但输出是

Jayesh Nick Name

如何解决? 谢谢

您需要将括号括在大括号中才能使其正常工作:

shell.SendKeys("Jayesh {(}Nick Name{)}")

您可以使用以下 send_keys() 功能。这将自动转换您的文本以适合与该功能一起使用。

import time
import win32api
import win32com.client

def send_keys(text):
    for src, dst in [('{', '['), ('}', ']'), ('(', '{(}'), (')','{)}'), ('+', '{+}'), ('^', '{^}'), (r'%', r'{%}'), ('~', '{~}')]:
        text = text.replace(src, dst)
    shell.SendKeys(text)

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("notepad")
time.sleep(1)
shell.AppActivate("Notepad")
send_keys(r"Testing + ^ % ~ ()  +/- {")

加号+、插入符^、百分号%、波浪线~和圆括号( )都需要用卷曲包裹起来括号。

大括号本身也需要换行,但不幸的是,在尝试发送这些时 Python 中似乎出现问题,导致 pywintypes.com_error 异常。因此,该函数通过将字符转换为方括号 [ ].

来避免这种情况