Reputation: 1193
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.
Upvotes: 3
Views: 5303
Reputation: 1
Hold Down : Keyboard.PressModifierKeys(ModifierKeys.Control);
Release : Keyboard.ReleaseModifierKeys(ModifierKeys.Control);
Upvotes: 0
Reputation: 54897
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);
}
Upvotes: 4