Reputation: 5490
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).
Upvotes: 2
Views: 3189
Reputation: 4767
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.
Upvotes: 0
Reputation: 5490
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).
Upvotes: 0
Reputation: 40223
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
Upvotes: 0
Reputation: 74654
Raymond says this is a bad idea.
http://blogs.msdn.com/oldnewthing/archive/2005/05/30/423202.aspx
Upvotes: 2