如何从用户当前使用的任何代码编辑器中获取文本? - 自动化

How do I get the text from whatever code editor the user is currently using? - Autoit

我想创建可以自动为我生成代码的热键。这是我的开始。

Func test1()
    Global $endString
    Global $nOutput
    Send("^a^c")
    $clipboard = ClipGet ()
    $endString = "Hello World"
    $nOutput = StringRegExpReplace($clipboard, "}[\n]*\z$", $endString)
    ClipPut($nOutput);
    Send("^v")
EndFunc   ;==>test

为了修改脚本,我发送了热键来复制所有内容,编辑它,然后粘贴所有内容。它有点奇怪,但它一直有效,直到我尝试使用您在上面看到的正则表达式来找到文档中的最后一个}。我怀疑剪贴板没有它 \z。知道如何执行此操作并正确复制当前正在处理的文件吗?如果不是...不同的正则表达式?

谢谢大家

HotKeySet('^r', '_test1')
HotKeySet('^q', '_Quit')

While 1
    Sleep(10)
WEnd

Func _test1()
    Local Static $endString = "; Hello World"
    Local $sOutput

    ; End the tool tip.
    ToolTip("")

    ; Get the window handle and keep it active on send.
    $hWin = WinGetHandle("")
    SendKeepActive($hWin)

    ; Select all and copy to clipboard.
    Send("^a^c")
    Sleep(200)

    ; Get text from clipboard and check if empty.
    $clipboard = ClipGet()
    If $clipboard == "" Then
        ToolTip("Clipboard is empty.")
        AdlibRegister('_TimeOut', 1000)
        Return
    EndIf

    ; Replace }$ with }$endString$.
    $sOutput = StringRegExpReplace($clipboard, "(*ANYCRLF)(?m)\}$", "}" & $endString)

    ; Put text to the clipboard and then paste the text.
    If @extended Then
        ClipPut($sOutput)
        Send("^v")
    Else
        ToolTip("No replacements to paste.")
        AdlibRegister('_TimeOut', 1000)
        ClipPut("")
    EndIf

    ; Deactivate send keep active window handle.
    SendKeepActive("")
EndFunc

Func _TimeOut()
    ; End the tool tip.
    ToolTip("")
    AdlibUnRegister('_TimeOut')
EndFunc

Func _Quit()
    Exit
EndFunc

该示例做了更多检查,以便您可以看到 是否工作正常。

如果您使用 Send() 然后考虑 SendKeepActive() 以确保 window 在使用 Send() 之前激活。

没有理由变量需要 Global 所以我将它们设置为 LocalStatic 只分配一次变量值,所以它只是保存 每次调用函数时重新分配。

正则表达式(PCRE)中的字符}是为了 字符或组重复,即 a{4} 是一种模式 找到 aaaa。要使用}文艺,需要转义 它带有反斜杠,即 \}.

PCRE 模式允许任何 CRLF 序列。采用 多行处理 (?m) 所以主题被处理 逐行并允许使用行尾 锚 $.

注意 Send("^a^c") 之后的 Sleep() 因为它改进了 select 全部复制成功的几率。我曾是 查看高达 50% 的副本作为脚本的失败 对于系统来说进展太快了。许多剪贴板管理器 也使用睡眠。

我使用 ToolTip() 来通知问题并使用 AdlibRegister() 取消提示,否则它们仍然存在。

使用热键 Ctrl + R 替换 和 Ctrl + Q 退出。