What is the C# equivalent of ChrW(e.KeyCode)?

蓝咒 提交于 2020-01-03 06:53:07

问题


In VB.NET 2008, I used the following statement:

MyKeyChr = ChrW(e.KeyCode)

Now I want to convert the above statement into C#.

Any Ideas?


回答1:


Looks like the C# equivalent would be

var MyKeyChr = char.ConvertFromUtf32((int) e.KeyCode)

However, e.KeyCode does not contain a Unicode codepoint, so this conversion is meaningless.




回答2:


The quick-and-dirty equivalent of ChrW in C# is simply casting the value to char:

char MyKeyChr = (char)e.KeyCode;

The longer and more expressive version is to use one of the conversion classes instead, like System.Text.ASCIIEncoding.

Or you could even use the actual VB.NET function in C# by importing the Microsoft.VisualBasic namespace. This is really only necessary if you're relying on some of the special checks performed by the ChrW method under the hood, ones you probably shouldn't be counting on anyway. That code would look something like this:

char MyKeyChr = Microsoft.VisualBasic.Strings.ChrW(e.KeyCode);

However, that's not guaranteed to produce exactly what you want in this case (and neither was the original code). Not all the values in the Keys enumeration are ASCII values, so not all of them can be directly converted to a character. In particular, casting Keys.NumPad1 et. al. to char would not produce the correct value.




回答3:


The most literal way to translate the code is to use the VB.Net runtime function from C#

MyKeyChr = Microsoft.VisualBasic.Strings.ChrW(e.KeyCode);

If you'd like to avoid a dependency on the VB.Net runtime though you can use this trimmed down version

MyKeyChr = Convert.ToChar((int) (e.KeyCode & 0xffff));


来源:https://stackoverflow.com/questions/6060576/what-is-the-c-sharp-equivalent-of-chrwe-keycode

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