Home > other >  Why I can not change focus?
Why I can not change focus?

Time:06-01

Im making a calculator.and for the buttons that type numbers, I wrote a condition that if the focus was on text box 1, it would enter the text there, if not, it would enter text box 2. But unfortunately the code does not work and I dont understand the problem. (WindosForm(.Net framework))

if (textBox1.Focus() == true)
        {
 textBox1.Text = textBox1.Text   "1";
        }
else
        {
 textBox2.Text = textBox2.Text   "1";
        }

CodePudding user response:

Subscribe to "Enter" event for your two textbox and save it. Use the same method for the two textboxes.

TextBox focusedTB;
private void textBox_Enter(object sender, EventArgs e)
{
    focusedTB = sender as TextBox;
}
...
this.textBox1.Enter  = new System.EventHandler(this.textBox_Enter);
...
this.textBox2.Enter  = new System.EventHandler(this.textBox_Enter);

Now you know the last textbox that got focus.

private void button1_Click(object sender, EventArgs e)
{
    focusedTB.Text  = "1";
}

CodePudding user response:

I think you talk about Windows Form ? You cannot manage like this but use event "Enter" of your textboxes, when you click inside the textbox, you give the focus to this textbox and you can do anything inside. Here I put the right focuses TextBox in a variable.

private TextBox _textBoxFocused; //this is always the righ TextBox

private void textBox1_Enter(object sender, EventArgs e)
{
    _textBoxFocused = textBox1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
    _textBoxFocused = textBox2;
}
  • Related