ygoe
ygoe

Reputation: 20364

How does a Windows Forms control know when its form was (de)activated?

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?

Upvotes: 3

Views: 1345

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273219

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;
}

Upvotes: 3

Related Questions