Search code examples
vbscripthtaonkeyup

Close an HTA when the user presses the 'Esc' key


I'm trying to capture key presses so that I can close my HTA when the user presses the Esc key.

I have confirmed that the onKeyUp event works (I also capture the length of an input), and also that the example below is not working (by adding a MsgBox which is not fired).

What am I missing here?

Sub window_onKeyUp()

    If window.event.keyCode = 27 Then
        Call CloseHTA()
    End If

End Sub

Solution

  • This works for me.

    <script language="VBScript">
        Sub TestKey()
            intKeyCode = Window.Event.Keycode
            If intKeyCode = 27 Then Window.Close
        End Sub
    </script>
    
    <body onkeyup="TestKey">
    </body>
    

    Edit:

    Alternatively, you can use Document_OnKeyUp() if you want to include your code after the <body> tag.

    <body>
    </body>
    
    <script language="VBScript">
        Sub Document_OnKeyUp()
            intKeyCode = Window.Event.Keycode
            If intKeyCode = 27 Then Window.Close
        End Sub
    </script>