Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the control with last focus

Tags:

c#

.net

winforms

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);
            }
        }
    }
}
like image 742
Thunder Avatar asked Dec 13 '10 10:12

Thunder


1 Answers

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;
    }
}
like image 65
Cody Gray Avatar answered Oct 29 '22 05:10

Cody Gray