I have a panel object that contains a number of controls. I want to change the backColor of that panel whenever the user clicks either on one of the controls or on the panel itself. I suspect I need to detect that the panel "has focus", but I can't figure out how.

Suggestions?

Try:

if (panel1.Focused == true)
{
panel1.BackColor = Color.Black;
}

You can also break out if statements inside of if statements.

if (panel1.Focused == true)
{
if (panel1.BackColor == Color.Blue)
{
panel1.BackColor = Color.Black;
}

else if (panel1.BackColor = Color.Black)
{
panel1.BackColor = Color.Green;
}
}

Panels don't gain focus (they have no focus events). So what you need is to add handlers to the Enter and Leave events.

private void panel1_Enter(object sender, EventArgs e) {
    Panel p = (Panel)sender;
    p.BackColor = Color.Red;
}

private void panel1_Leave(object sender, EventArgs e) {
    Panel p = (Panel)sender;
    p.BackColor = Color.Blue;
}

Ahh well I used a label, didn't know that a panel didn't have focus.

ENTER and LEAVE events don't seem to get triggered for the panel itself. According to the documnetation ENTER occurs "when the control becomes the active control of the form". ENTER doesn't get triggered if I click on a control WITHIN the panel or when I click on the panel itself.

And, although MouseEnter and MouseLeave events DO get triggered for the panel, I really need to detect when the user actually DOES SOMETHING in the panel, not just when the mouse happens to move over it.

I'm wondering if there is some other grouping control, rather than panel, that would do what I need.

This is where you break out if inside of if.

Enter and Leave do get triggered for a Panel, I wrote code to test it before I posted my first reply. If your control isn't gaining focus when you click on it (a button, for example) then you need to make it have focus.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.