Search code examples
c#keyboard-hook

I want to be able to hold down control by code


I'm using c#, Visual Studio 2010 for a Windows application.

I want to hold down the Ctrl key, then release it after a while.

I tried this but it didnt work.

[DllImport("user32.dll")]
    static extern bool keybd_event(byte bVk, byte bScan, uint dwFlags,
    UIntPtr dwExtraInfo);

    public const uint KEYEVENTF_KEYUP = 0x02;
    public const uint VK_CONTROL = 0x11;

// Press the Control key.
keybd_event(VK_CONTROL,0,0,0);
//release the control key
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);

But I get this error

The best overloaded method match for 'ImageR.Form1.keybd_event(byte, byte, uint, System.UIntPtr)

cannot convert from 'uint' to 'byte'

cannot convert from 'int' to 'System.UIntPtr'


Solution

  • I didn't find any good examples of do SendInput, the examples at http://www.pinvoke.net/default.aspx/user32.keybd_event didn't work for me.

    The best solution to solve this was at http://inputsimulator.codeplex.com/

    Now it's this simple:

    //Press Ctrl
    
    InputSimulator.SimulateKeyDown(VirtualKeyCode.CONTROL);
    
    //Release Ctrl
    
    InputSimulator.SimulateKeyUp(VirtualKeyCode.CONTROL);