按下键时聚焦文本框

时间:2011-06-21 20:21:54

标签: c# winforms

我想在按下某个键时聚焦文本框。 我使用这段代码:

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

在我的表单上使用 KeyPreview = true 。 但是当我这样做时,如果我写'az',我的文本框中只会出现'z'字符。如果我只按'a', textboxCode 为空,但有焦点。

如何不丢失按键?

    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 个答案:

答案 0 :(得分:2)

这很难做到,Windows发送的WM_KEYDOWN消息已经提交到具有焦点的窗口。你希望开展将关键事件转换为打字字符的业务,这是键盘布局上的火箭科学,其中死键仅产生爆炸性火箭。

您可以做的一件事就是重新发布键盘消息,现在使用文本框的窗口句柄。您可以通过覆盖表单的ProcessCmdKey()方法来检测键击并返回true来防止它被进一步处理。像这样:

    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);

答案 1 :(得分:0)

这样的事情:

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