[英]How to hold the Ctrl key down through code
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! 我正在编写一个单元测试,如果(Control.ModifierKeys == Keys.Control),某个函数将被深入调用堆栈。我可以为运行单元测试的特定情况添加一个标志或者其他东西,但是太脏了! How can I set ModifierKeys to Ctrl through code?
如何通过代码将ModifierKeys设置为Ctrl? I'm using C#.Net 4.0.
我正在使用C#.Net 4.0。
You could use P/Invoke to call the keybd_event
function for synthesizing keystrokes. 您可以使用P / Invoke调用
keybd_event
函数来合成击键。
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);
}
Hold Down : Keyboard.PressModifierKeys(ModifierKeys.Control); 按住:Keyboard.PressModifierKeys(ModifierKeys.Control);
Release : Keyboard.ReleaseModifierKeys(ModifierKeys.Control); 发布:Keyboard.ReleaseModifierKeys(ModifierKeys.Control);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.