环境:.NET Framework 2.0,VS 2008。
我正在尝试创建某些 .NET 控件(标签、面板)的子类,这些控件将通过某些鼠标事件(MouseDown
、MouseMove
、MouseUp
) 到其父控件(或顶级表单)。我可以通过在标准控件的实例中为这些事件创建处理程序来做到这一点,例如:
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);
}
}
我无法将事件处理程序移动到控件的子类中,因为在父控件中引发事件的方法是 protected ,而且我没有父控件的限定符:
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
方法,但希望有人能给我一个更清晰的解决方案。
最佳答案
是的。经过大量搜索,我找到了这篇文章 "Floating Controls, tooltip-style" ,它使用 WndProc
将消息从 WM_NCHITTEST
更改为 HTTRANSPARENT
,使 Control
对鼠标事件透明。
为此,创建一个继承自 Label
的控件并简单地添加以下代码。
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);
}
}
我已经在 Visual Studio 2010 中使用 .NET Framework 4 Client Profile 对此进行了测试。
关于c# - 将鼠标事件传递给父控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/547172/