首页 > 解决方案 > 我是否错误地引用了 hwnd?无法使用 AutoHotkey 从简单的记事本窗口中获取文本

问题描述

当我运行这个脚本时,我打开了一个记事本窗口,其中包含“test.txt - 记事本”作为文本。id 变量被子函数 ControlListHwnd 中的 hwnd 数组正确填充。然后它循环遍历它为记事本找到的所有控制项(很少)。

脚本:

!t::  ;To retrieve the formatted text and paste:
{
    DetectHiddenText, On
    DetectHiddenWindows, On

    MsgBox, Starting

    WinGet, id, ControlListHwnd, test.txt - Notepad, , Program Manager
    Loop, Parse, id, `n
    {
         this_id := %A_LoopField%
         ;this_id := id%id_Index%
         ;this_id := id
         ;WinActivate, ahk_id %this_id%
         WinGetClass, this_class, ahk_id %this_id%
         WinGetTitle, this_title, ahk_id %this_id%
         ;MsgBox, 4, , Visiting All Windows`n%A_Index% of %id%`nahk_id %this_id%`nahk_class %this_class%`n%this_title%`n`nContinue?


         ControlHwnd := %A_LoopField%
         ControlGetText, outputText, , ahk_id %ControlHwnd%
         MsgBox, 4, , All Controls`n id - %A_LoopField% `n Control Text - %outputText%`n Class - %this_class% `n Title - %this_title% `n `n Continue?

         IfMsgBox, NO, break
    }

    MsgBox, Finished - %id% - end

    return
}

当它循环时,它应该显示一个消息框,其中包含来自所查询控件的文本、类和标题。

看起来我错误地传递了 hwnd 吗?或者有没有更好的方法来做到这一点?

过去,我使用对 User32\GetWindow 的直接 Dll 调用,希望我可以使用 AutoHotkey 及其现有功能来做到这一点。

标签: autohotkey

解决方案


这是将遗留语法与新表达式语法混淆的典型错误。
这两行具体:
this_id := %A_LoopField%
ControlHwnd := %A_LoopField%

在遗留赋值 ( =) 中,您确实可以通过将变量包装在 中来引用它% %,但是在表达式中(您在使用时得到:=的)您只需键入变量即可引用变量:

this_id := A_LoopField
ControlHwnd := A_LoopField

没有%

杂项:
热键标签不需要包裹在{ }s 中,以防你不知道。
而且不需要设置

DetectHiddenText, On
DetectHiddenWindows, On 

每次运行热键时。您可以在脚本顶部设置一次。


这是使用表达式语法的完整脚本。
总的来说,我建议停止使用遗留语法,它不再是 2008 年了。您可以在此处
开始学习遗留语法和表达式语法之间的区别

DetectHiddenText,在 DetectHiddenWindows,在

!t::
     MsgBox, Starting

     ;parameters that are started with a % followed up by a space
     ;are automatically evaluated as expressions
     ;using it to just be able to quate straight text parameters
     ;could be considered overkill, but I'll just convert everything
     ;to expression syntax for the sake of the demonstration

     ;also, I'd change "test.txt - Notepad" to "ahk_exe notepad.exe"
     WinGet, id, ControlListHwnd, % "test.txt - Notepad", , % "Program Manager"
     Loop, Parse, id, `n
     {
          this_id := A_LoopField
          WinGetClass, this_class, % "ahk_id " this_id
          WinGetTitle, this_title, % "ahk_id " this_id

          ControlHwnd := A_LoopField
          ControlGetText, outputText, , % "ahk_id " ControlHwnd
          MsgBox, 4, , % "All Controls`n id - " A_LoopField "`n Control Text - " outputText "`n Class - " this_class "`n Title - " this_title "`n `n Continue?"

          IfMsgBox, No
               break
     }
     MsgBox, % "Finished - " id " - end"
return

推荐阅读