views:

666

answers:

1

Hello - I have created a custom control that gets highlighted when the mouse hovers over it. The custom control also has a checkbox. When the mouse goes over the checkbox, the highlighting of the custom control does not occur. I've tried using WS_EX_TRANSPARENT on the checkbox but it isn't working for me.

        int cbStyle = GetWindowLong(CompletedCheckBox.Handle, GWL_EXSTYLE);
        SetWindowLong(CompletedCheckBox.Handle, GWL_EXSTYLE, cbStyle | WS_EX_TRANSPARENT);

How can I do this?

Thanks

+2  A: 

Transparent only affects drawing, not mouse events. The check box is getting the mouse events, this in turn means that when you mouse over the checkbox, your control receives a MouseLeave event. To ensure that the background color changes, even when a child control ( at any level) gets a MouseEnter event, you need to track that a control of interest -- or any child, grand-child ..etc-- has the mouse over it. To do this, recurse through all descendant controls and intercept the appropriate events for them. To do this, try something similar to the class below.

public partial class MyControl : UserControl
{
    public MyControl()
    {
        InitializeComponent();
        AttachMouseEnterToChildControls(this);
    }

    void AttachMouseEnterToChildControls(Control con)
    {
        foreach (Control c in con.Controls)
        {
            c.MouseEnter += new EventHandler(control_MouseEnter);
            c.MouseLeave += new EventHandler(control_MouseLeave);
            AttachMouseEnterToChildControls(c);
        }
    }
    private void control_MouseEnter(object sender, EventArgs e)
    {
        this.BackColor = Color.AliceBlue;
    }

    private void control_MouseLeave(object sender, EventArgs e)
    {
        this.BackColor = SystemColors.Control;
    }
}
Jason D