I have a Windows Forms application in C# .NET. It contains a user-drawn control that also handles the keyboard focus. If a part of the control has the focus, a focus highlight border is painted around it. When the form that contains the control is deactivated, the focus border must disappear from the control, obviously. But the control doesn't even get a notification about it. It only receives the "Leave" event when another control is focused, not another window. How can the control know about that?
+2
A:
When the Form+Control are loaded, the Control can subscribe to the Activate and DeActivated events of the Form.
If it is a UserControl, you have the Control.Load event to do this. For a CustomControl I would have to look it up.
Anyway, be sure to implement Dispose in your Control to unsubscribe to the events.
Just gave it a try:
private void UserControl1_FormActivate(object sender, EventArgs e)
{
label1.Text = "Acitve";
}
private void UserControl1_FormDeActivate(object sender, EventArgs e)
{
label1.Text = "InAcitve";
}
private void UserControl1_Load(object sender, EventArgs e)
{
this.ParentForm.Activated += UserControl1_FormActivate;
this.ParentForm.Deactivate += UserControl1_FormDeActivate;
}
Henk Holterman
2010-03-03 13:25:23
Thanks. I was hoping there was a more intuitive way. I added both event handlers in my OnLoad method. Now I get a strange OutOfMemory exception in another part of my control; and ParentForm is null in the Dispose method so I cannot deregister the events anymore! Any ideas?
LonelyPixel
2010-03-05 12:07:41
All right, marked this as answer. It works, and I managed to work around that other error. I assume that unsubscribing from the events is not necessary as the ParentForm is null anyway in the Dispose method. Please anybody answer me if they disagree.
LonelyPixel
2010-03-10 14:49:36
@Lonely, its not critical unless you frequently add/remove this control at runtime.
Henk Holterman
2010-03-10 15:15:25