tags:

views:

564

answers:

4

I want to convert a string into a series of Keycodes, so that I can then send them via PostMessage to a control. I need to simulate actual keyboard input, and I'm wondering if a massive switch statement is the only way to convert a character into the correct keycode, or if there's a simpler method.

====

Got my solution - http://msdn.microsoft.com/en-us/library/ms646329(VS.85).aspx

VkKeyScan will return the correct keycode for any character.

(And yes, I wouldn't do this in general, but when doing automated testing, and making sure that keyboard presses are responded to correctly, it works reliably enough).

+1  A: 

Raymond says this is a bad idea.

http://blogs.msdn.com/oldnewthing/archive/2005/05/30/423202.aspx

Paul Betts
And Raymond even suggests a better technique.
Max Lybbert
A: 

For A-z 1-9 you could try build the char into a keycode string string.Format("KEY_KEY_{0}", char.ToString()) then use Enum.Parse to extract the Enum value, but it's a bit of a cludge

Or look at How to convert uint keycode to Keys enum on expert sexchange, and just work around the tricky cases.

I agree a switch statement is kinda awful

johnc
+1  A: 

Got my solution - http://msdn.microsoft.com/en-us/library/ms646329(VS.85).aspx

VkKeyScan will return the correct keycode for any character.

(And yes, I wouldn't do this in general, but when doing automated testing, and making sure that keyboard presses are responded to correctly, it works reliably enough).

Andrew Ducker
A: 

A much more reliable wait to send a string of keystrokes to a window is to use the SendKeys class

 System.Windows.Forms.SendKeys("This is a test");
 System.Windows.Forms.SendKeys("This is sends CTRL+J ^j");

This will be more predictable and should save you some time.

Stefan Rusek
Unfortunately it only works if your window will definitely have the focus. Which mine won't.
Andrew Ducker
It may also drop characters.
Greg