How to hold the Ctrl key down through code

5.2k views Asked by At

I'm writing a unit test and a certain function will be called deep down in the stack if (Control.ModifierKeys == Keys.Control).. I can add a flag or something for the particular case of running a unit test, but it would be too dirty! How can I set ModifierKeys to Ctrl through code? I'm using C#.Net 4.0.

2

There are 2 answers

0
Douglas On BEST ANSWER

You could use P/Invoke to call the keybd_event function for synthesizing keystrokes.

First declare the following:

[DllImport("user32.dll", SetLastError = true)] 
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

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

Then, in your test, use:

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

try
{
    // Perform test.
}
finally
{
    // Release the Control key.
    keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
}
0
Max On

Hold Down : Keyboard.PressModifierKeys(ModifierKeys.Control);

Release : Keyboard.ReleaseModifierKeys(ModifierKeys.Control);