C# user32.dll keybd_event not working

6.1k views Asked by At

I'm trying to highlight text in text box (with SHIFT+RIGHT_ARROW Win shortcut) by simulating key press with user32.dll keybd_event but it's not working:

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public const int SHIFT_LEFT = 0xA0;
public const int RIGHT = 0x27;

....

keybd_event(SHIFT_LEFT, 0, 0, 0);
keybd_event(RIGHT, 0, 0, 0);
keybd_event(RIGHT, 0, 2, 0);
keybd_event(SHIFT_LEFT, 0, 2, 0);

Cursor moves to right but text is not highlighted... Can anyone explain why?

EDIT: Why is this working with Windows OnScreenKeyboard?


KEYEVENTF_EXTENDEDKEY (0x0001): If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).
So, I did this:

keybd_event(SHIFT_LEFT, 0, 1 | 0, 0);
keybd_event(RIGHT, 0, 1 | 0, 0);
keybd_event(RIGHT, 0, 1 | 2, 0);
keybd_event(SHIFT_LEFT, 0, 1 | 2, 0);

Problem solved!
Detailed explanation about KEYEVENTF_EXTENDEDKEY can be found here.

1

There are 1 answers

0
Nasenbaer On

Some functions are already public available on MSDN I dont need to explain. Here is the elementary information as code which is working on different systems:

    ''' <summary>
    ''' Simulate key down event on Windows machine
    ''' </summary>
    ''' <param name="nCode">key</param>
    ''' <remarks></remarks>
    Public Sub SetKeyDown(ByVal nCode As Integer)
        Dim vKey As Byte = Convert.ToByte(nCode)
        Dim scanCode As Integer = MapVirtualKey(vKey, 0)
        Dim ret As Integer = keybd_event(vKey, CByte(scanCode), KEYEVENTF_EXTENDEDKEY Or 0, IntPtr.Zero)
    End Sub

    ''' <summary>
    ''' Simulate key up event on Windows machine
    ''' </summary>
    ''' <param name="nCode">key</param>
    ''' <remarks></remarks>
    Public Sub SetKeyUp(ByVal nCode As Integer)
        Dim vKey As Byte = Convert.ToByte(nCode)
        Dim scanCode As Integer = MapVirtualKey(vKey, 0)
        Dim ret As Integer = keybd_event(vKey, CByte(scanCode), KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, IntPtr.Zero)
    End Sub

MSDN REFERENCES

Keybd_event:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646304%28v=vs.85%29.aspx

MapVirtualKey:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646306%28v=vs.85%29.aspx