Jonathan Lam
Jonathan Lam

Reputation: 185

Visual Basic Script - KeyPress Detection?

I want to terminate the program once the key F1 is pressed. Not sure sure how to write the do while loop. Any Ideas?

Set WshShell = WScript.CreateObject("WScript.Shell")
Do While {F1} is not pressed
'...
Loop

Upvotes: 4

Views: 20346

Answers (2)

Mark Llewellyn
Mark Llewellyn

Reputation: 51

I use a hybrid VBS script with a small C# program embedded in it using adodb.stream.

This example updates the clipboard with each step (e.g. for logins), but it can be easily modified to trigger other events.

You can remove the clean-up line, and the .exe can be placed in the temp directory.

For brevity the hex_ section has been truncated but the whole file is available at http://excelxll.com/VBS/keypress.txt

Dim wsh, exe, HexKeyCode
Set wsh = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

HexKeyCode = "70" 'F1=70 F12=7B ALT-GR=A5 ESC=1B
exe = "Press F1 to step script until I disappear.exe"

if not fso.FileExists(exe) then call create_binary_file_

'EACH TIME F1 IS PRESSED UPDATE THE CLIPBOARD 
'############################################
wsh.Run "cmd.exe /c """ & exe  & """ " & HexKeyCode, 0, TRUE
wsh.Run "cmd.exe /c echo 1| clip", 0, TRUE

wsh.Run "cmd.exe /c """ & exe  & """ " & HexKeyCode, 0, TRUE
wsh.Run "cmd.exe /c echo 2| clip", 0, TRUE

'OPTIONAL TIDY-UP
'################
fso.DeleteFile exe


sub create_binary_file_()
'########################
hex_="4D5A90...0000"

'FOR THE BINARY FILE WRITE
'#########################
dim str
set str = WScript.CreateObject("adodb.stream") 
str.type = 2 
str.charset = "iso-8859-1" 
str.open

for x = 1 to len(hex_) step 2

high_ = asc(mid(hex_,x,1))
    if high_ < 58 then 
        high_ = (high_-48)*16
    else
        high_ = (high_-55)*16
    end if

low_ = asc(mid(hex_,x+1,1))
    if low_ < 58 then 
        low_ = (low_-48)
    else
        low_ = (low_-55)
    end if

str.writeText(chrW(high_ + low_))
next

str.saveToFile exe, 2 
str.close 

end sub

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

This isn't possible in plain VBScript, but you may be able to get it to work with an HTA:

<head>
<title>Test</title>
<HTA:APPLICATION ID="oHTA"
  APPLICATIONNAME="Test"
>
</head>

<script language="VBScript">
Sub CheckKey
  If window.event.keyCode = 112 Then self.close()
End Sub
</script>

<body onKeyUp="CheckKey">
...
</body>

Upvotes: 4

Related Questions