I have a c# windows forms application with several textboxes and a button. I would like to find out the textbox which has focus and do something with it. I have written following code but of course it won't work because the button will get focus as soon as it is pressed.
private void button1_MouseDown(object sender, MouseEventArgs e)
{
foreach (Control t in this.Controls)
{
if (t is TextBox)
{
if (t.Focused)
{
MessageBox.Show(t.Name);
}
}
}
}
There's no built in property or functionality for keeping track of the previous-focused control. As you mentioned, whenever the button is clicked, it will take the focus. If you want to keep track of the textbox that was focused before that, you're going to have to do it yourself.
One way of going about this would be to add a class-level variable to your form that holds a reference to the currently focused textbox control:
private Control _focusedControl;
And then in the GotFocus
event for each of your textbox controls, you would just update the _focusedControl
variable with that textbox:
private void TextBox_GotFocus(object sender, EventArgs e)
{
_focusedControl = (Control)sender;
}
Now, whenever a button is clicked (why are you using the MouseDown
event as shown in your question instead of the button's Click
event?), you can use the reference to the previously-focused textbox control that is saved in the class-level variable however you like:
private void button1_Click(object sender, EventArgs e)
{
if (_focusedControl != null)
{
//Change the color of the previously-focused textbox
_focusedControl.BackColor = Color.Red;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With