How to hold the Ctrl key down through code

99封情书 提交于 2019-12-07 17:21:59

问题


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);



来源:https://stackoverflow.com/questions/10839040/how-to-hold-the-ctrl-key-down-through-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!