Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
443 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...