[How-to] Listen to the keyboard

Started by Lars-Erik, August 25, 2008, 04:26:21 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Lars-Erik

I got the question on my blog, looked into it, and found that Microsoft has the pretty well explained on there page.
None the less, people seem to lack google skills these days so here goes:

first of all open the Visio VBA editor by pressing Alt + F11. The first thing we will need to create is the class that will listen to the keyboard. So create a new class by right clicking the project explorer and choosing Insert > Class module. Next, use the properties window to change the name to KeyboardListener. That done we will need to fill the class with the required code.

'A class that listens to the keyboard
Dim WithEvents vsoWindow As Visio.Window
'Start listening to the active window
Private Sub Class_Initialize()
Set vsoWindow = ActiveWindow
End Sub
Private Sub Class_Terminate()
Set vsoWindow = Nothing
End Sub
'I only added the KeyUp event, you can ofcouse use the KeyDown and KeyPress aswell
Private Sub vsoWindow_KeyUp(ByVal KeyCode As Long, ByVal KeyButtonStatus As Long, CancelDefault As Boolean)
'Display the key pressed
MsgBox (KeyCode)
End Sub


This code will make sure when a key is pressed you will get a messagebox telling you the number of the key that was released. This can be edited to fit your requirements by, for example making it use KeyPress or KeyDown instead of KeyUp. You can also change the messagebox it displays into calling a sub, where you can filter the keynumber so Visio will only respond to the keys you want.

Hold on though, we're not quite done yet. We will still need Visio to start listening and stop listening at some point. To do this add the following code to you ThisDocument section:

Dim myKeyboardListener As KeyboardListener
'Start listening to the keyboard when the document is opened
Private Sub Document_DocumentOpened(ByVal doc As IVDocument)
Set myKeyboardListener = New KeyboardListener
End Sub
'Stop listening when the document is closed
Private Sub Document_BeforeDocumentClose(ByVal doc As IVDocument)
Set myKeyboardListener = Nothing
End Sub


This should make Visio start listening when you open the document and stop when it is closed.
There are a few other things you should know about this, Visio will still respond to its own shortcut, so pressing F1 will still open the help function. Also because this code is set to only check the active window, alt cannot be used in the way, as it sets the focus to the Visio main program. If you still have questions, don't hesitate to ask them.

Source
Example file

Lars-Erik

It might be nice if anyone knows how to stop it from preforming the default actions, to add on this.
So how for example do I stop Visio opening the help function when I use the code above to watch for the F1 key.

- Lars