Emulating keyboard events in .NET

Every now and then, you may need to emulate pressing keys on a keyboard to accomplish things through code. I found I needed to utilize this method for an Outlook programming project. After a little searching, I was able to emulate a user pressing the “ALT” button twice. You can use the keybd_event function (http://msdn2.microsoft.com/en-us/library/ms646304.aspx) to emulate keyboard events:

Imports System.Runtime.InteropServices

‘List of virtual key codes: http://msdn2.microsoft.com/en-us/library/ms645540.aspx
Const VK_SHIFT = &H10
Const VK_NUMLOCK = &H90
Const VK_ESC = &H1B
Const VK_MENU = &H12 ‘This is the ALT key
Const KEYEVENTF_KEYUP As Integer = &H2

<DllImport(“user32”)> _
Public Sub keybd_event(ByVal vk As Byte, ByVal sc As Byte, ByVal Flags As Integer, ByVal dwExtraInfo As Integer)
End Sub

Public Sub PressAltKeyTwice()
‘Simulate Key Press
keybd_event(VK_MENU, vbNull, 0, 0)
‘Simulate Key Release
keybd_event(VK_MENU, vbNull, KEYEVENTF_KEYUP, 0)

Application.DoEvents() ‘This was needed in my code to register the first keypress. If I did not have this, the system acted as though I press it only once.

‘Simulate Key Press
keybd_event(VK_MENU, vbNull, 0, 0)
‘Simulate Key Release
keybd_event(VK_MENU, vbNull, KEYEVENTF_KEYUP, 0)

Application.DoEvents()

End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *