检查 Cursor 是否在 groupBox1 或 groupBox2 C#

Check if Cursor is in groupBox1 or groupBox2 C#

我有 2 个 groupBox,都有一个 TextBox 和一个 Button。

当我在 groupBox1 中并在 textBox1 中写一些东西并且我按下 Enter 按钮时,应该按下 groupBox1 中的按钮,当我在 groupBox2 中并在 textBox2 中写一些东西时也是如此。

类似

if (Focus is on groupbox1 == true)
    this.AcceptButton = button1;
else if(Focus is on groupbox2 == true)
    this.AcceptButton = button2;

您可以订阅 TextBox KeyDown 活动:

TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(tb_KeyDown);

static void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //enter key is down
    }
}

使用 enter 事件切换焦点

private void textBox1_Enter(object sender, EventArgs e)
{
    AcceptButton = button1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
    AcceptButton = button2;
}
private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("First button clicked");
}
private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show("Second button clicked ");
}