Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return the focus to the last used control after clicking a button in a winform app?

Tags:

c#

.net

winforms

I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:

Sample App Screen Shot

The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.

I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:

   public partial class Form1 : Form
    {
        Control _lastEnteredControl;

        private void textBox_Enter(object sender, EventArgs e)
        {
            _lastEnteredControl = (Control)sender;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Do something here");
            _lastEnteredControl.Focus();
        }


    }

So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?

like image 339
Joe Barone Avatar asked Sep 01 '08 00:09

Joe Barone


People also ask

What is focus() in c#?

The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.


1 Answers

For a bit of 'simplicity' maybe try.

public Form1()
    {
        InitializeComponent();

        foreach (Control ctrl in Controls)
        {
            if (ctrl is TextBox)
            {
                ctrl.Enter += delegate(object sender, EventArgs e)
                              {
                                  _lastEnteredControl = (Control)sender;
                              };
            }
        }
    }

then you don't have to worry about decorating each textbox manually (or forgetting about one too).

like image 71
Joshua Turner Avatar answered Sep 25 '22 06:09

Joshua Turner