Learn about control with the latest focus.

I have an application with windows forms c with several text fields and a button. I would like to know a text box with focus and do something with it. I wrote the following code, but of course this will not work, because the button will receive 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); } } } } 
+8
c # winforms
source share
4 answers

There is no built-in feature or functionality to track a control that targets a previous version. As you already mentioned, whenever a button is pressed, it will be in the spotlight. If you want to track a text field that has been focused before then, you will have to do it yourself.

One way to do this is to add a class level variable to the form containing a link to the current focused text field control:

 private Control _focusedControl; 

And then in the GotFocus event for each of your text field controls, you simply update the _focusedControl variable _focusedControl that text field:

 private void TextBox_GotFocus(object sender, EventArgs e) { _focusedControl = (Control)sender; } 

Now, whenever the button is clicked (why are you using the MouseDown event, as shown in the question, instead of the Click event button?), You can use the link to the previously configured text field control, which is stored in the class level variable, but 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; } } 
+17
source share

Perhaps you can subscribe to the GotFocus event of your text fields, save the text field (you will receive with the sender parameter) in the field and use this field when you click on the button?

+3
source share

I would use the button1_MouseHover event. When this event fires, ActiveControl until it points to the previous control, which you can save as _focusedControl .

Of course, this will not work if the user clicks a button.

+2
source share
  private void BtnKeyboard_Click(object sender, EventArgs e) { if (MasterKeyboard.Visible) { btnKeyboard.ButtonImage = Properties.Resources._001_22; MasterKeyboard.Visible = false; _lastFocusedControl.Focus(); } else { btnKeyboard.ButtonImage = Properties.Resources._001_24; MasterKeyboard.Visible = true; MasterKeyboard.BringToFront(); _lastFocusedControl.Focus(); } } private Control _lastFocusedControl; private void BtnKeyboard_MouseHover(object sender, EventArgs e) { if (ActiveControl!=btnKeyboard) _lastFocusedControl = ActiveControl; } 
0
source share

All Articles