环境:.净框架2.0,与2008年。

我试图建立一个亚类的定。净控制(标签,小组)就将穿过某些鼠的事件(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);
    }
}

我无法移动事件的处理程序进入的一个亚类的控制,因为该方法,提高活动在母体控制的保护,并且我没有限定词为父母控制:

不能接受保护的部件 System.Windows.Forms.Control.OnMouseDown(System.Windows.Forms.MouseEventArgs) 通过限定的类型 System.Windows.Forms.Control;限定词必须的类型 TheProject.NoCaptureLabel (或来源于它)。

我找到压倒一切的 WndProc 方法的控制在我的子类,但是希望有人能给我一个更清洁的解决方案。

有帮助吗?

解决方案

是。很多搜索后,我发现文章“浮动控制,工具提示样式” ,该使用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框架4客户端配置文件测试此。

其他提示

您需要写在你的基类中的公共/保护方法,这将引发该事件为您服务。然后调用从派生的类此方法。

OR

这是你想要的吗?

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

WS_EX_TRANSPARENT 扩大窗口的风格实际上没有这个(这是什么地提示使用)。你可能想要考虑采用这种风格,而不是编码很多的处理程序的以为你做它。

要做到这一点,复盖 CreateParams 方法:

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

进一步阅读:

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top