找回密码
 加入
搜索
查看: 937|回复: 0

[AU3基础] AutoIt3 使用进程名获取窗口句柄

[复制链接]
发表于 2022-2-18 00:17:21 | 显示全部楼层 |阅读模式
背景

需要用AutoIt3控制QQ音乐播放器,首先要获取QQ音乐的窗口句柄

问题

WinGetHandle方法不能满足要求
QQ音乐的Title会根据当前播放的歌曲动态改变
而QQ音乐与QQ的窗口Class又相同,同时打开时无法用窗口Class拿到QQ音乐窗口句柄

解决办法

自己写一个_WinGetHandleByPnmAndCls方法,使用进程名(QQMusic.exe)和窗口Class(TXGuiFoundation)获得窗口句柄

代码如下

#include <MsgBoxConstants.au3>
#include <WindowsConstants.au3>
#include <WinAPI.au3>

Local $hWnd = _WinGetHandleByPnmAndCls("QQMusic.exe", "TXGuiFoundation")

If Not $hWnd Then
   MsgBox($MB_SYSTEMMODAL, "", "窗口没找到")
   Exit
EndIf

WinActivate($hWnd)


; 根据pname和class获取窗口句柄,找不到则返回0
Func _WinGetHandleByPnmAndCls($pname, $class)
   ; 根据进程名查找进程id
   Local $pid = ProcessExists($pname)
   ; 如果进程存在,继续
   If $pid Then
      return _WinGetHandleByPidAndCls($pid, $class)
   Else
      Return 0
   EndIf
EndFunc

; 根据pid和class获取窗口句柄,找不到则返回0
Func _WinGetHandleByPidAndCls($pid, $class)
   ; 这里使用枚举所有顶层窗口方法,WinList方法会返回大量隐藏窗口
   Local $winArr = _WinAPI_EnumWindowsTop()
   ; 遍历所有窗口,进程id与指定进程id比较
   For $i=1 To $winArr[0][0]
      If $pid=WinGetProcess($winArr[$i][0]) And $winArr[$i][1]=$class Then
         ; 一个进程会有多个窗口,所以要用class来筛选
         return $winArr[$i][0]
      EndIf
   Next
   Return 0
EndFunc
————————————————
版权声明:本文为CSDN博主「有暗香盈袖」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/moonshine_1988/article/details/48006043

您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|手机版|小黑屋|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2024-5-3 11:56 , Processed in 0.070848 second(s), 19 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表