Search code examples
c#groupboxacceptbutton

Check if Cursor is in groupBox1 or groupBox2 C#


i have 2 groupBoxes, both with one TextBox and one Button.

When i am in groupBox1 and write something in textBox1 and i Press the Enter Button, the Button in groupBox1 should be pushed, same Thing when i am in groupBox2 and write something there in textBox2.

Something like

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

Solution

  • Use the enter event for toggling the focus

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