将鼠标事件传递给父控件 [英] Pass-through mouse events to parent control
问题描述
环境:.NET Framework 2.0,VS 2008.
Environment: .NET Framework 2.0, VS 2008.
我正在尝试创建某些 .NET 控件(标签、面板)的子类,它将通过某些鼠标事件(MouseDown
、MouseMove
、MouseUp
) 到其父控件(或顶级表单).我可以通过在标准控件的实例中为这些事件创建处理程序来做到这一点,例如:
I am trying to create a subclass of certain .NET controls (label, panel) that will pass through certain mouse events (MouseDown
, MouseMove
, MouseUp
) to its parent control (or alternatively to the top-level form). I can do this by creating handlers for these events in instances of the standard controls, e.g.:
public class TheForm : Form
{
private Label theLabel;
private void InitializeComponent()
{
theLabel = new Label();
theLabel.MouseDown += new MouseEventHandler(theLabel_MouseDown);
}
private void theLabel_MouseDown(object sender, MouseEventArgs e)
{
int xTrans = e.X + this.Location.X;
int yTrans = e.Y + this.Location.Y;
MouseEventArgs eTrans = new MouseEventArgs(e.Button, e.Clicks, xTrans, yTrans, e.Delta);
this.OnMouseDown(eTrans);
}
}
我无法将事件处理程序移动到控件的子类中,因为在父控件中引发事件的方法是受保护的,而且我没有父控件的限定符:
I cannot move the event handler into a subclass of the control, because the methods that raise the events in the parent control are protected and I don't have a qualifier for the parent control:
无法通过 System.Windows.Forms.Control 类型的限定符访问受保护成员
System.Windows.Forms.Control.OnMouseDown(System.Windows.Forms.MouseEventArgs)
代码>;限定符必须是 TheProject.NoCaptureLabel
类型(或派生自它).
Cannot access protected member
System.Windows.Forms.Control.OnMouseDown(System.Windows.Forms.MouseEventArgs)
via a qualifier of typeSystem.Windows.Forms.Control
; the qualifier must be of typeTheProject.NoCaptureLabel
(or derived from it).
我正在考虑在我的子类中覆盖控件的 WndProc
方法,但希望有人能给我一个更简洁的解决方案.
I am looking into overriding the WndProc
method of the control in my sub-class, but hopefully someone can give me a cleaner solution.
推荐答案
是的.经过大量搜索,我找到了文章"Floating Controls, tooltip-style",它使用 WndProc
将消息从 WM_NCHITTEST
更改为 HTTRANSPARENT
,使 Control
对鼠标事件.
Yes. After a lot of searching, I found the article "Floating Controls, tooltip-style", which uses WndProc
to change the message from WM_NCHITTEST
to HTTRANSPARENT
, making the Control
transparent to mouse events.
要实现这一点,请创建一个从 Label
继承的控件,然后简单地添加以下代码.
To achieve that, create a control inherited from Label
and simply add the following code.
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x0084;
const int HTTRANSPARENT = (-1);
if (m.Msg == WM_NCHITTEST)
{
m.Result = (IntPtr)HTTRANSPARENT;
}
else
{
base.WndProc(ref m);
}
}
我已经在带有 .NET Framework 4 Client Profile 的 Visual Studio 2010 中对此进行了测试.
I have tested this in Visual Studio 2010 with .NET Framework 4 Client Profile.
这篇关于将鼠标事件传递给父控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!