按键时聚焦文本框

本文关键字:文本 聚焦 | 更新日期: 2023-09-27 17:59:45

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

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

按键时聚焦文本框

这很难做到,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);

类似这样的东西:

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