我是否错误地引用了 hwnd?无法使用 AutoHotkey 从简单的记事本 window 中获取文本

Am I referencing hwnd's incorrectly? Unable to get text out of a simple notepad window using AutoHotkey

当我 运行 这个脚本时,我有一个记事本 window 打开并以 "test.txt - Notepad" 作为文本。 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
}

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

看起来我传递的 hwnd 有误吗?或者有更好的方法吗?

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

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

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

this_id := A_LoopField
ControlHwnd := A_LoopField

没有%s.

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

DetectHiddenText, On
DetectHiddenWindows, On 

每次 运行 您的热键。您只需在脚本顶部设置一次即可。


这是使用表达式语法的完整脚本。
总的来说,我建议停止使用旧语法,现在已经不是 2008 年了。
您可以开始学习传统语法和表达式语法之间的区别 here

检测隐藏文本,打开 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