How to send keys Control + A + B? (keep Control mo

2019-01-27 23:34发布

问题:

When I record this sequence it fails. I know I can send Control + A using Keyboard.SendKeys(control, "A",ModifierKeys.Control) but how do I send a sequence that holds control and releases the letter before pressing the next letter.

Note: the sequence I am looking for is similar to the default Visual Studio shortcut for commenting out a line Control + K + C

Is this maybe something that I just need to use the WinApi for?

回答1:

keybd_event is very convenient for this (much easier to use than the "replacement" SendInput).

keybd_event(Keys.Control, MapVirtualKey(Keys.Control, 0), 0, 0);
keybd_event(Keys.A, MapVirtualKey(Keys.A, 0), 0, 0);
keybd_event(Keys.A, MapVirtualKey(Keys.A, 0), KEYEVENTF_KEYUP, 0);
keybd_event(Keys.B, MapVirtualKey(Keys.B, 0), 0, 0);
keybd_event(Keys.B, MapVirtualKey(Keys.B, 0), KEYEVENTF_KEYUP, 0);
keybd_event(Keys.Control, MapVirtualKey(Keys.Control, 0), KEYEVENTF_KEYUP, 0);

If you only ever need to hold down control, alt, and/or shift, check TCS's answer of SendKeys.Send. keybd_event is more powerful and will let you hold down any key, and release in any order.



回答2:

From what I understand from the SendKeys.Send documentation it would be:

SendKeys.Send("^(KC)")

The following can be found in the remarks:

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)". To specify to hold down SHIFT while E is pressed, followed by C without SHIFT, use "+EC".



回答3:

How about just using

Keyboard.SendKeys(control, "A",ModifierKeys.Control); 
Keyboard.SendKeys(control, "B",ModifierKeys.Control); 

?



回答4:

This worked for me:

Keyboard.SendKeys("^(AB)"); 


回答5:

Simply use the code like below:

Keyboard.SendKeys("^AB");