Python判断前台窗口标题含指定字符串的实现问题求助
解决Python检测前台窗口标题包含指定字符串的问题
你的代码存在几个明显问题:
re.search()未传入匹配模式和目标字符串参数- 最后一行的
time.sleep缺少括号,无法执行休眠操作 - 实际上
find/index方法可以正常工作,只是你之前的使用方式有误
下面给出几种可行的实现方案:
方案1:直接用in操作符(最简洁)
这是你最初想要实现的类似用法,直接判断子串是否存在于目标字符串中:
from win32gui import GetWindowText, GetForegroundWindow import time while True: time.sleep(1) window_title = GetWindowText(GetForegroundWindow()) target = 'Microsoft Edge' if target in window_title: print("当前前台是Microsoft Edge")
方案2:使用find方法
find方法找不到子串时返回-1,找到则返回子串起始索引,只需判断结果不等于-1即可:
from win32gui import GetWindowText, GetForegroundWindow import time while True: time.sleep(1) window_title = GetWindowText(GetForegroundWindow()) target = 'Microsoft Edge' if window_title.find(target) != -1: print("当前前台是Microsoft Edge")
方案3:使用index方法(需捕获异常)
index方法找不到子串会抛出ValueError,因此需要用try-except块处理异常:
from win32gui import GetWindowText, GetForegroundWindow import time while True: time.sleep(1) window_title = GetWindowText(GetForegroundWindow()) target = 'Microsoft Edge' try: window_title.index(target) print("当前前台是Microsoft Edge") except ValueError: pass
方案4:使用正则表达式(修正你的原代码)
正确调用re.search方法,它会在找到匹配时返回匹配对象,未找到则返回None:
from win32gui import GetWindowText, GetForegroundWindow import time import re while True: time.sleep(1) window_title = GetWindowText(GetForegroundWindow()) target = 'Microsoft Edge' if re.search(target, window_title): print("当前前台是Microsoft Edge")
注意:如果目标字符串包含正则元字符(如.、*等),需要用re.escape(target)对其转义,避免匹配逻辑出错。
内容的提问来源于stack exchange,提问作者DrWizard
相关产品推荐
相关产品推荐

