29 April, 2011

How to Press and Hold Keyboard key Programmatically in C#, VB.NET, C/C++


                       using sendkey function we can send specified amount of keys at a time so it is not possible to press and hold any key using sendkey. therefore instead of using sendkey function i am going to use keybd_event function of user32.dll library which let us create any type of keyboard event manually. so now to use this function first we need to declare this function before using it which can be done as following.
  1. IN C#
            public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

  2. IN VB
            <DllImport("user32.dll")> _
            Public Shared Sub keybd_event(bVk As Byte, bScan As Byte, dwFlags As UInteger,     dwExtraInfo As UInteger)
            End Sub

  3. IN C/C++
           #include <windows.h>
Once you have imported user32.dll and declared your keybd_event function now is the time to use it. before using it we must now about all the arguments of this function.

bVk [in]
Type: BYTE A virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual Key Codes.
bScan [in]
Type: BYTE A hardware scan code for the key.
dwFlags [in]
Type: DWORD Controls various aspects of function operation. This parameter can be one or more of the following values.

If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).

If specified, the key is being released. If not specified, the key is being depressed.
dwExtraInfo [in]
Type: ULONG_PTR An additional value associated with the key stroke.

//these are virtual key codes for keys
const int VK_UP = 0x26; //up key
        const int VK_DOWN = 0x28;  //down key
        const int VK_LEFT = 0x25;
        const int VK_RIGHT = 0x27;
        const uint KEYEVENTF_KEYUP = 0x0002;
        const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
        int press()

//Press the key
            keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
            return 0;
        int release()
//Release the key
            keybd_event((byte)VK_RIGHT, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
            return 0;