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.
Asked
Active
Viewed 5,107 times
3
-
Try this, you should find answer http://stackoverflow.com/questions/4705428/c-sharp-is-ctrl-key-down – Taldir May 31 '12 at 18:25
2 Answers
4
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);
}

Douglas
- 53,759
- 13
- 140
- 188
0
Hold Down : Keyboard.PressModifierKeys(ModifierKeys.Control);
Release : Keyboard.ReleaseModifierKeys(ModifierKeys.Control);

Max
- 1