Friday, April 29, 2011

Forwarding a Keystroke to another Control in WinForms

I am receiving a keystroke in a Form object's OnKeyDown. When some conditions are met (such as the keystroke is a printable character and not a hotkey) I want to forward the key to a text control on the form and set focus to the text control so the user can continue typing. I am able to decode the character typed using MapVirtualKey but I get only the "unshifted" character (always upper case). Using ToUnicodeEx seems like too much of a PITA.

What is the best way to do this? Isn't there a way to simply forward the Windows message itself?

Can't I intercept the ProcessKeyPreview or some such and forward it to the text control's ProcessKeyPreview? Any ideas along similar lines?

Bump: No answers!

From stackoverflow
  • I did this on a single form with the following

    private void MyFunkyForm_KeyDown(object sender, KeyEventArgs e)
        // to avoid duplicate letters in textbox :-)
        if (textBox2.Focused == false)
         // get the char from the Keycode
         char inputChar = (char)e.KeyCode;
         if (char.IsLetterOrDigit(inputChar))
          // if letter or number then add it to the textbox
          textBox2.Text += inputChar;
         // set focus
         // set cursor to the end of text, no selection
         textBox2.SelectionStart = textBox2.Text.Length;


Post a Comment