捕获MS Word的keydown事件

时间:2015-07-17 07:58:52

标签: vba events ms-word word-vba keydown

我想捕获退格事件,只需执行退格操作,然后添加其他操作,但我不确定退格的原始操作:选择。删除,-1?

Sub AddKeyBinding()
    With Application
         ' \\ Do customization in THIS document
        .CustomizationContext = ThisDocument

         ' \\ Add keybinding to this document Shorcut: Backspace
        .KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyBackspace), _
            KeyCategory:=wdKeyCategoryCommand, Command:="TestKeybinding"
    End With
End Sub

 ' \\ Test sub for keybinding
Sub TestKeybinding()
    Selection.Delete , -1 ' I am not sure how to impl the original command
    If Selection.Style = "Some...Style" And Selection.Range.ListFormat.ListString = "" Then
            Selection.Style = "DefaultStyle"
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

最后我尝试使用autohotkey来解决这个问题,有些代码如下:


     #IfWinActive,ahk_class OpusApp

      ;回车键
      enter::
         send {enter}
         checkStyle()
         return

     backspace::
         send {backspace}
         checkStyle()
         return



     checkStyle(){
    word:=ComObjActive("word.application")
    if(word.Selection.Style.NameLocal="ListItemStyle" and word.Selection.Range.ListFormat.ListString = "")
    {
        word.Selection.Style := "someStyle"
        TrayTip, hint, style chnaged, 3, 17
    }
     }

答案 1 :(得分:0)

这有点笨拙,但它有效:

Public blnCatchBackspace As Boolean

Public Sub CatchBackspace()
    If blnCatchBackspace Then
        ToggleBackspaceCatch 'Remove the backspace key binding
            SendKeys "{BACKSPACE}"
            DoEvents
            'insert code here
        ToggleBackspaceCatch 'Reapply the backspace key binding
    End If
End Sub

Public Sub ToggleBackspaceCatch()
    Dim lngProtection As Long

    With ActiveDocument
        'key binding will error if the document is protected
        'save the current protection state and unprotect the document
        lngProtection = .ProtectionType
        If lngProtection <> wdNoProtection Then .Protect wdNoProtection
    End With

    With Application
        If blnCatchBackspace Then 'clear the key binding
            blnCatchBackspace = False
            FindKey(wdKeyBackspace).Clear
        Else 'apply the key binding
            blnCatchBackspace = True
            .CustomizationContext = ActiveDocument
            .KeyBindings.Add KeyCategory:=wdKeyCategoryMacro, _
                Command:="CatchBackspace", _ 
                KeyCode:=BuildKeyCode(wdKeyBackspace)
        End If
    End With
    'reapply the original document protection
    ActiveDocument.Protect lngProtection
End Sub