我正在尝试更改用户控件的BackColor
属性以及其中标签的ForeColor
。以下是我的代码:
private void NRow_MouseLeave(object sender, EventArgs e)
{
BackColor = Color.White;
label1.ForeColor = Color.Black;
}
private void NRow_MouseEnter(object sender, EventArgs e)
{
BackColor = Color.Lime;
label1.ForeColor = Color.White;
}
但它不起作用。即使我试图在BackColor更改行上添加断点,但控件没有到达那里。我还检查了事件绑定,没关系。用户控件被添加到这样的面板:
notContainer.Controls.Add(new NRow());
我不知道发生了什么。请帮忙。
更新
事件处理程序如下所示:
this.MouseEnter += new System.EventHandler(this.NRow_MouseEnter);
this.MouseLeave += new System.EventHandler(this.NRow_MouseLeave);
答案 0 :(得分:2)
如果您的label1
放置在您的用户控件(UC)内部,则您应该同时处理MouseEnter
MouseEvent
和label1
。因为,当你的鼠标在你的UC上移动时,你的UC中的label1
可以处理你的鼠标事件而不是你的UC。
this.MouseEnter += new System.EventHandler(this.NRow_MouseEnter);
this.MouseLeave += new System.EventHandler(this.NRow_MouseLeave);
label1.MouseEnter += new System.EventHandler(this.NRow_MouseEnter);
label1.MouseLeave += new System.EventHandler(this.NRow_MouseLeave);
注意:以上所有行都应放在UC NRow中。
答案 1 :(得分:2)
我能够通过覆盖UserControl's
OnMouseLeave
和OnMouseEnter
并使用PointToClient
方法确定鼠标坐标是否仍在{{}范围内。 1}}在恢复之前,看看这样的东西是否适合你。
UserControl
答案 2 :(得分:1)
您可以尝试使用此代码将消息从child controls
传递到UserControl
,在这种情况下,您需要传递消息WM_MOUSEMOVE
以及一些小代码,以使其按预期工作:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
Dictionary<Control,NativeControl> controls = new Dictionary<Control,NativeControl>();
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
OnMouseLeave(e);
}
protected override void OnControlAdded(ControlEventArgs e)
{
e.Control.HandleCreated += ControlsHandleCreated;
base.OnControlAdded(e);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
e.Control.HandleCreated -= ControlsHandleCreated;
base.OnControlRemoved(e);
}
private void ControlsHandleCreated(object sender, EventArgs e)
{
Control control = sender as Control;
NativeControl nc;
if(!controls.TryGetValue(control, out nc)) {
nc = new NativeControl(this);
controls[control] = nc;
}
nc.AssignHandle(control.Handle);
}
public class NativeControl : NativeWindow
{
public NativeControl(UserControl1 parent)
{
Parent = parent;
}
UserControl1 Parent;
bool entered;
protected override void WndProc(ref Message m)
{
//WM_MOUSEMOVE = 0x200
//WM_LBUTTONDOWN = 0x201
//WM_LBUTTONUP = 0x202
//WM_NCHITTEST = 0x84
if (m.Msg == 0x200 || m.Msg == 0x201 || m.Msg == 0x202 || m.Msg == 0x84){
//Check if Parent is not nul, pass these messages to the parent
if (Parent != null){
m.HWnd = Parent.Handle;
Parent.WndProc(ref m);
}
if (m.Msg == 0x200 && !entered){
entered = true;
Parent.OnMouseEnter(EventArgs.Empty);
}
else entered = false;
}
else if (entered) entered = false;
base.WndProc(ref m);
}
}
}