Digital Ape Digital Ape - 1 year ago 125
C# Question

C# SendKeys or InputManager but only send DownKey OR UpKey>

I Have a program which where a button exist. When the button is pressed, it should simulate a key pressed. However, using

only sends a specific key, but not a key press.

I want a method that when the button is pressed, it simulates a key down, and when released it sends a key up to the keyboard.

Answer Source

This should work

Add using System.Runtime.InteropServices;

    [DllImport("user32.dll", SetLastError = true)]
    private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
    public static void PressKey(Keys key, bool up)
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
        if (up)
            keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
            keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);

    private void buttonUp_MouseDown(object sender, MouseEventArgs e)
        PressKey(Keys.Up, false);

    private void buttonUp_MouseUp(object sender, MouseEventArgs e)
        PressKey(Keys.Up, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download