[英]How do I prevent special characters from being generated by the Ctrl key in a C# console application?
I'm building a little hotkey trainer for StarCraft2 (it's a C# Console application). 我正在为StarCraft2(这是一个C#控制台应用程序)构建一个小的热键培训师。 But I'm struggling to capture Ctrl+ combinations, because certain Ctrl-combinations generate special characters.
但是我很难捕获Ctrl +组合,因为某些Ctrl-组合会生成特殊字符。
For example, when pressing Ctrl+O, Console.ReadKey() won't capture the 'o' character, but rather a special starry '☼' character. 例如,当按Ctrl + O时,Console.ReadKey()不会捕获'o'字符,而是一个特殊的繁星'☼'字符。 How do I prevent this and ensure Ctrl just acts as a modifier key and nothing else?
如何防止这种情况,并确保Ctrl仅充当修饰键,而没有其他作用?
PS: I know about handling Ctrl+C specifically, so I'm more concerned about the other keys. PS:我知道专门处理Ctrl + C,因此我更关心其他键。
Here is a simple code example. 这是一个简单的代码示例。 Try capturing and outputting Ctrl+O
尝试捕获并输出Ctrl + O
private static void Main()
{
var pressed = Console.ReadKey();
Console.WriteLine(pressed.KeyChar);
Console.ReadLine();
}
With Console.ReadKey
you have everything you need using Key
instead of KeyChar
: 使用
Console.ReadKey
您可以使用Key
而不是KeyChar
拥有所需的一切:
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine(keyInfo.Key);
Console.WriteLine(keyInfo.Modifier);
As explained on MSDN , the KeyChar
is the representation of the key combination (key + modifiers), and Key
is the key the user pressed. 如MSDN上所述,
KeyChar
是键组合(键+修饰符)的表示,而Key
是用户按下的键。
Additionally, if you don't want the KeyChar
to appear on the screen, you can intercept the key using Console.ReadKey(true)
. 另外,如果您不希望
KeyChar
出现在屏幕上,则可以使用Console.ReadKey(true)
截取该键。
You can get the information from the ConsoleKeyInfo
object returned by Console.ReadKey
您可以从
Console.ReadKey
返回的ConsoleKeyInfo
对象中获取信息Console.ReadKey
For Ctrl + O, the Ctrl key will be the Modifier
property and the O key will be the Key
property. 对于Ctrl + O,Ctrl键将成为
Modifier
属性,而O键将成为Key
属性。
If you are writing a "trainer" , reading StdIn is not going to cut it for you. 如果您正在编写“培训师” ,那么阅读StdIn并不会帮助您。 This will only receive input when the Console App has focus.
仅当控制台应用程序具有焦点时,它才会接收输入。 To read all keyboard input, ie when Start Craft 2 has focus, you need global hooking.
要读取所有键盘输入,即当Start Craft 2成为焦点时,您需要全局挂钩。
See this article for more info. 有关更多信息,请参见本文 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.