首页 文章

将鼠标事件传递给父控件

提问于
浏览
31

环境:.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);
    }
}

我无法将事件处理程序移动到控件的子类中,因为引发父控件中的事件的方法受到保护,并且我没有父控件的限定符:

无法通过System.Windows.Forms.Control类型的限定符访问受保护的成员System.Windows.Forms.Control.OnMouseDown(System.Windows.Forms.MouseEventArgs);限定符必须是TheProject.NoCaptureLabel类型(或从中派生) .

我正在研究覆盖我的子类中控件的 WndProc 方法,但希望有人可以给我一个更清洁的解决方案 .

3 回答

  • 3

    是 . 经过大量的搜索,我找到了文章"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对此进行了测试 .

  • 59

    您需要在基类中编写一个public / protected方法,这将为您引发事件 . 然后从派生类中调用此方法 .

    要么

    这是你想要的吗?

    public class MyLabel : Label
    {
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            //Do derived class stuff here
        }
    }
    
  • 3

    WS_EX_TRANSPARENT 扩展窗口样式实际上是这样做的(它就是就地工具提示使用的) . 您可能需要考虑应用此样式而不是编写大量处理程序来为您执行此操作 .

    为此,请覆盖 CreateParams 方法:

    protected override CreateParams CreateParams
    {
      get
      {
        CreateParams cp=base.CreateParams;
        cp.ExStyle|=0x00000020; //WS_EX_TRANSPARENT
        return cp;
      }
    }
    

    进一步阅读:

相关问题