如何使用 AutoHotkey 删除当前行?

How do I delete the current line using AutoHotkey?

使用 AutoHotkey 脚本我想设置键盘命令 Ctrl+D 以删除任何活动 Windows 应用程序中的当前行。

怎么做?

^d::Send {Home}{ShiftDown}{End}{Right}{ShiftUp}{Del}

可能无法在所有边缘情况下工作,但在记事本中通过了一些非常 的基本测试。 =~)

HaveSpacesuit 的答案有效,但在使用一段时间后我意识到它会删除活动行,有时会重新定位下方行的间距。

这让我重新考虑他的解决方案。我没有从队伍的前面走到后面,而是试着从后面走到前面。这解决了重新定位问题。

SendInput {End}
SendInput +{Home}
SendInput ^+{Left}
SendInput {Delete}

不过还有个小问题。如果光标在空行上,上面有更多空行,则所有空行都将被删除。

我不知道要替换 ^+{Left} 的组合键没有这种行为,所以我不得不编写一个更全面的解决方案。

^d:: DeleteCurrentLine()

DeleteCurrentLine() {
   SendInput {End}
   SendInput +{Home}
   If get_SelectedText() = "" {
      ; On an empty line.
      SendInput {Delete}
   } Else {
      SendInput ^+{Left}
      SendInput {Delete}
   }
}

get_SelectedText() {

    ; See if selection can be captured without using the clipboard.
    WinActive("A")
    ControlGetFocus ctrl
    ControlGet selectedText, Selected,, %ctrl%

    ;If not, use the clipboard as a fallback.
    If (selectedText = "") {
        originalClipboard := ClipboardAll ; Store current clipboard.
        Clipboard := ""
        SendInput ^c
        ClipWait .2
        selectedText := ClipBoard
        ClipBoard := originalClipboard
    }

    Return selectedText
}

据我所知,这不会产生意外行为。

但是,如果您使用剪贴板管理器,请小心,因为此脚本会在必要时使用剪贴板作为获取所选文本的媒介。这将影响剪贴板管理器的历史记录。

如果您 运行 遇到需要针对不同程序的不同行为的问题,您可以 "duplicate" 针对特定程序的 ^d 命令,如下所示:

SetTitleMatchMode, 2 ; Makes the #IfWinActive name searching flexible
^d::Send {Home}{ShiftDown}{End}{Right}{ShiftUp}{Del} ; Generic response to ^d.

#IfWinActive, Gmail ; Gmail specific response
  ^d::Send {Home}{ShiftDown}{End}{Right}{ShiftUp}{Del} ; adapt this line for gmail
#IfWinActive ; End of Gmail's specific response to ^d

#IfWinActive, Excel ; Excel specific response.
  ^d::Send {Home}{ShiftDown}{End}{Right}{ShiftUp}{Del} ; adapt this line for Excel
#IfWinActive ; End of Excel's specific response to ^d

这样,您的 ^d 命令在 Excel 和 Gmail 中的工作方式将有所不同。

我有一个简单的方法可以解决重新定位的问题。不使用剪贴板。

重新定位问题是由于需要处理 2 个不同的案例。

  1. 如果一行中有现有文本, 我们要 select 它们全部,并删除文本(退格键 1) 并再次退格一次以删除空行(退格 2)

  2. 如果是空行, 我们要删除空行(退格键 1)

为了满足以上两种情况,我引入了一个虚拟字符。 这将确保两种情况都以相同的方式行事。 所以退格 2 次,每次都会产生相同的转换。

简单地说,

; enable delete line shortcut
^d::
    Send {Home}
    Send {Shift Down}{End}{Shift Up}
    Send d
    Send {Backspace 2}
    Send {down}
return 

这种方法的缺点, 撤消时会出现虚拟字符 "d"。不错的权衡,因为我不经常撤消删除行。