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

后端 未结 7 1274
忘掉有多难
忘掉有多难 2021-01-02 23:23

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 butt

7条回答
  •  滥情空心
    2021-01-02 23:51

    Your approach looks good. If you want to avoid having to add an the event handler to every control you add, you could create a recursive routine to add a GotFocus listener to every control in your form. This will work for any type of control in your form, however you could adjust it to meet your needs.

    private void Form_OnLoad(object obj, EventArgs e)
    {
        AddGotFocusListener(this);
    }
    
    private void AddGotFocusListener(Control ctrl)
    {
        foreach(Control c in ctrl.Controls)
        {
            c.GotFocus += new EventHandler(Control_GotFocus);
            if(c.Controls.Count > 0)
            {
                AddGotFocusListener(c);
            }
        }
    }
    
    private void Control_GotFocus(object obj, EventArgs e)
    {
        // Set focused control here
    }
    

提交回复
热议问题