2
votes

I want to focus a textbox when a key is pressed. I use this code:

    private void MainForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        textBoxCode.Focus();
    }

With KeyPreview = true on my form. But when I do that, if I write 'az', only the 'z' char appear in my textbox. If I press only 'a', textboxCode is empty but have the focus.

How not to lose the key pressed?

SOLUTION:

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (textBox1.Focused == false)
        {
            textBox1.Text += e.KeyChar.ToString();
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.Focus();
        }
    }
2

2 Answers

3
votes

This is pretty hard to do, the WM_KEYDOWN message that Windows sends is already committed to the window that has the focus. You do not want to get in the business of translating key-down events into typing characters, that's a rocket science on keyboard layouts with dead keys that produces only exploding rockets.

One thing you can do is re-post the keyboard message, now with a window handle of the textbox. You can do this by overriding the form's ProcessCmdKey() method to detect the keystroke and return true to prevent it from being processed any further. Like this:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
        if (!textBox1.Focused) {
            PostMessage(textBox1.Handle, msg.Msg, msg.WParam, msg.LParam);
            textBox1.Focus();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr PostMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
0
votes

Something like this:

private void MainForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        textBoxCode.Focus();
        textBoxCode.Text = (char)e.KeyCode;
    }