c# - 将鼠标事件传递给父控件

标签 c# winforms mouseevent

环境:.NET Framework 2.0,VS 2008。

我正在尝试创建某些 .NET 控件(标签、面板)的子类,这些控件将通过某些鼠标事件(MouseDownMouseMoveMouseUp ) 到其父控件(或顶级表单)。我可以通过在标准控件的实例中为这些事件创建处理程序来做到这一点,例如:

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 type System.Windows.Forms.Control; the qualifier must be of type TheProject.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/

相关文章:

javascript - 使用 onscroll 检测鼠标滚轮

java - 在线程中运行时,While 循环不起作用

javafx-2 - JavaFX - 动态关闭 TabPane 中的选项卡

c# - MVC ajax调用如何处理错误响应

C# - 在 MessageBox 中按下 Enter 触发控件 KeyUp 事件

c# - 单元格事件参数中的动态 DataGridView 引用

window 尺寸

c# - 上传到内存流时无法访问已关闭的文件

c# - Web Api 帮助页面 - 只显示一些 Controller 而不显示其他 Controller

c# - UWP 推送通知