python - Python 激活同名窗口
问题描述
所以我需要做的是定期更改活动窗口,我的问题是它们都具有相同的名称并且使用它们的 HWND 仅适用于第一个窗口。除此之外,我不想每次都插入它的 HWND
import win32gui, time
def main():
while(1):
win32gui.SetForegroundWindow(788574)#win2
side()
time.sleep(5)
def side():
while(1):
win32gui.SetForegroundWindow(3147934)#win1
main()
time.sleep(5)
if __name__ == '__main__':
main()
解决方案
要循环浏览选定的窗口,有几个步骤:
- 使用win32gui.EnumWindows遍历所有打开的窗口
- 使用win32gui.GetWindowText从窗口中获取标题栏文本
- 使用win32com.client.Dispatch和SendKeys激活切换进程
- 使用win32gui.SetForegroundWindow选择要激活的窗口
这是代码:
import win32com.client as win32
import win32gui
import time
title = "Untitled - Notepad2" # cycle all windows with this title
def windowEnumerationHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
top_windows = [] # all open windows
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
winlst = [] # windows to cycle through
for i in top_windows: # all open windows
if i[1] == title:
winlst.append(i)
for x in range(5): # cycle 5 times
for w in winlst: # each window with selected title
shell = win32.Dispatch("WScript.Shell") # set focus on desktop
shell.SendKeys('%') # Alt key
win32gui.SetForegroundWindow(w[0]) # bring to front, activate
time.sleep(2) # 2 seconds
推荐阅读
- python - 如何在元组中用逗号替换空格?
- sql - 为什么尝试使用日期查询删除旧行时所有行都被删除
- flutter - 使用 dio 上传多图像选择器(包已过期)问题
- android - 设备旋转时如何防止edittext焦点回到第一个edittext
- flutter - 如何使用 Flutter 实现这一点?
- gcc - 运行 rhel6 构建的可执行文件时在 rhel7 机器上导入错误
- asp.net - 如果 nuget 包支持 .Net Standard 2.0,那么我们可以在 asp.net 和 asp.net 核心中使用该包吗?
- jenkins-pipeline - 如何使用 Jenkins 中的 ssh 发布将环境变量传递给远程主机
- java - AuthorizationCodeInstalledApp,意外行为
- amazon-web-services - 您可以将文件设置为隐藏在 S3 存储桶中吗?