Event to know if Panel lost focus in Winforms application?
I have a simple Form with 4 panels in it. Each of those panels are docked in the parent, to ensure only one is visible at a given time. Now, for Panel2, when it is moving from front to back, I would like to work on that event. I am making panels visible by calling panel.Br开发者_开发问答ingToFront()
Leave
event but that doesn't work. For Form, the event is Deactivate
, what's the event for Panel? I'm thinking LostFocus
is what you're looking for.
Edit
As another strategy, you know that calling panel.BringToFront
will queue an update in your UI. Wherever you are calling panel.BringToFront
, perhaps you could just call one of your own methods, or trigger one of your own events. This way, you know when the event will be triggered, and exactly what will trigger it.
The reason I thought of this is that I doubt your Panel
will ever actually have the focus itself - rather, one of its child controls will likely have the focus. By doing you own event trigger, you don't have to rely on something as volatile as focus. Plus, even if the Panel
did have the focus, it's always possible that it could lose focus in other ways than your own panel switching.
Edit #2
Here's an attempt at a quick implementation of my previous ramblings. I'll be making the assumption that this code be placed somewhere in the same class as all your Panel
instances (i.e. in your Form
class).
// This will be the custom event to which you can subscribe
// in order to detect a switch in panels.
public event EventHandler PanelSwapEvent;
// This reference the currently visible panel - should be set
// to the default panel in the form's constructor, if possible.
private Panel currentPanel;
// This actually switches the panels, to minimize code duplication.
private void switchToPanel(Panel p)
{
Panel lastPanel = currentPanel;
currentPanel = p;
// Move the panels, and invoke the event.
p.BringToFront();
if(PanelSwapEvent != null)
PanelSwapEvent(lastPanel, new EventArgs());
}
// Here's the actual event handler (replaces your
// pnlServiceInfo_LostFocus handler).
private void PanelSwapHandler(object sender, EventArgs e)
{
// whatever you want to do when panels are swapped
}
In this example, the sender
of the event handler is the panel that lost "focus". Using it is as simple as saying switchToPanel(pnl_whatever)
to indicate that you would like to switch from the current panel to the panel named pnl_whatever
.
精彩评论