问题描述
我测试了以下code:
I am testing the following code:
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
Rectangle leftRect = new Rectangle(0, 0, 32, this.Height);
if (leftRect.Contains(e.Location))
{
MessageBox.Show("Hello World");
}
}
我们的想法是,当鼠标进入某个区域32个像素宽,容器控件的左边,出现一则消息(OK,在R / L就会去做别的事情,但是这纯粹是测试目前如此)。
The idea is that when the mouse enters a region 32 pixels wide, to the left of the container control, a message appears (OK, in R/L it will do something else, but this is purely testing for now).
的问题是,当一个孩子控制填充矩形区域中,一个ContainerControl不接收MouseMove事件,因为它正在由子控制处理
The issue is that when a child control populates the rectangle region, the ContainerControl does not receive the MouseMove event, as it is being handled by the child control.
所以我的问题是,如何让我的一个ContainerControl接收MouseMove事件,即使它的子填充相同的矩形区域?
So my question is, how to I get my ContainerControl to receive the MouseMove event, even when its children populate the same rectangle region?
推荐答案
WPF是很多,在这样的事情更好。我用这样的函数有很多:
WPF is a lot better at this sort of thing. I use a function like this a lot :
public static List<Control> GetAllControlsRecurs(List<Control> list,
Control parent)
{
if (parent == null)
return list;
else
{
list.Add(parent);
}
foreach (Control child in parent.Controls)
{
GetAllControlsRecurs(list, child);
}
return list;
}
这将返回所有子控件和他们的孩子,等名单,给定父控件中。然后,你可以这样做:
This returns a list of all child controls and their children, etc, within a given parent control. You could then do something like :
private void Form1_Load(object sender, EventArgs e)
{
List<Control> ctlList = new List<Control>();
GetAllControlsRecurs(ctlList, this);
foreach (Control ctl in ctlList) ctl.MouseMove += Form1_MouseMove;
}
您将不得不处理与 ControlAdded
动态添加(和删除)的控制,但这至少应该给你一个开始。这里注意,这将不执行code在被覆盖的的OnMouseMove
的方法,而是在表单的的MouseMove
事件处理程序。还有一些其他的解决方案,为建立此成一个派生类,但这里重要的一点是,发现并钩住子控件到单个事件的手段。
You would have to handle dynamically added (and removed) controls with ControlAdded
but this should at least give you a start. Note here that this will not execute code in the overriden OnMouseMove
method but rather in the form's MouseMove
event handler. There are a number of other solutions for building this into a derived class but the important point here is the means of identifying and hooking up child controls to a single event.
这篇关于在一个ContainerControlÇ检测鼠标的位置#.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!