Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 893
Paramu Avatar asked May 19 '11 14:05

Paramu


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is the C in history?

C was originally developed for UNIX operating system to beat the issues of previous languages such as B, BCPL, etc. The UNIX operating system development started in the year 1969, and its code was rewritten in C in the year 1972.


1 Answers

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.

like image 149
Cody Gray Avatar answered Oct 28 '22 23:10

Cody Gray