I have several controls in a panel, and I want to make a button that removes the one that has focus at the time that the button get clicked. I tried iterating through the co开发者_JS百科ntrols in the panel to check if any of them has focus, but it always evaluates to false. I suspect that this is because the button gets focus as soon as it is clicked. If this is what is happening, can someone please tell me how I can keep track of the last control in the panel to have focus. Maybe an event every time focus changes? And if this is not what is happening, can someone please tell me what they think is happening. Thank you in advance.
You are right -- as soon as the button is pressed, all the other controls will lose focus.
You can work around this by listening for the GotFocus event to remember which was the most recently selected one. For example:
public partial class YourForm
{
private Control _LastFocusedControl;
public YourForm()
{
InitializeComponent();
var controlsToWatchForFocusChange = ...; // Some IEnumerable<Control>, e.g. `new[] { txtTextBox1, txtTextBox2 }`
foreach (var control in controlsToWatchForFocusChange) {
control.GotFocus += (sender, e) => _LastFocusedControl = (Control)sender;
}
}
}
Then when your button is pressed, the last control to have focus will be accessible via _LastFocusedControl
.
Yes, the button has the focus since it was just clicked.
You can use the GotFocus and LostFocus events to keep track of which control was focused before the button was pressed.
精彩评论