透明只影响绘图,不影响鼠标事件。复选框正在获取鼠标事件,这反过来意味着当您将鼠标悬停在复选框上时,您的控件会收到一个 MouseLeave 事件。为了确保背景颜色发生变化,即使子控件(在任何级别)获得 MouseEnter 事件,您也需要跟踪感兴趣的控件(或任何子控件、孙子控件等)是否将鼠标悬停在它。为此,递归遍历所有后代控件并为它们拦截适当的事件。为此,请尝试类似于下面的课程。
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;
}
}