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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
}
回答2:
Hold Down : Keyboard.PressModifierKeys(ModifierKeys.Control);
Release : Keyboard.ReleaseModifierKeys(ModifierKeys.Control);