views:

52

answers:

2

I need to convert Keys.Enter to a char.

This does not work in compact framework: http://stackoverflow.com/questions/2518749/convert-sequence-of-system-windows-forms-keys-to-a-char (KeyInterop.VirtualKeyFromKey)

Any one have any other ideas?


Further clarification: I like using enumerations more than magic numbers/chars. Rather than make my own enumeration that says MyKeys.Enter (that equals '\r\n') I would like to just use what MS has made.

Keys.Enter is just an example.


I am planning to do this to compare the the KeyPressEventArgs.KeyChar. That is why I am trying to compare to a char.

A: 

Keys.Enter is "\r\n" if typed into a text field.

You should be able to get characters by first taking the Keys value, bitwise and'ing it with Keys.KeyCode, and casting to a uint to get the virtual-key code. Then pass it to MapVirtualKey to convert it to a character.

Stephen Cleary
Except that that's two chars.
Michael Todd
@Michael: That's because Enter does not actually represent a character. Neither does Delete, End, PageUp, F1-F12, Shift, ...
BlueRaja - Danny Pflughoeft
Understood (I'm familiar with keyboard scan codes), but there's still the issue that the OP is trying to represent the keypress as a single char. We don't know why (unless they explain), but perhaps a single char is necessary.
Michael Todd
@Michael Todd - See the updated question that clarifies.
Vaccano
Updated answer to match updated question. :)
Stephen Cleary
+1  A: 

The keys in the Keys enumeration are virtual keys. They don't turn into characters until Windows has translated them, using the currently active keyboard layout. Which is a detail that varies from one machine to the next, depending on the user's preference and language. And quite likely the specific kind of mobile device your software is running on. Also, many virtual keys don't produce a character, Keys.F1 would be an obvious example.

Turning virtual keys into characters yourself is something you should really avoid, you are going to get it wrong. Keys.Enter is already translated by Windows, it will generate the KeyPressed event with e.KeyChar = '\r'. On most machines, anyway.

If you want to detect short-cut keys then you use KeyDown. Typing keys that produce characters require KeyPressed.

Hans Passant