34

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

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

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

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

4

3 回答 3

69

是的。经过大量搜索,我找到了文章“浮动控件,工具提示样式”,它用于WndProc将消息从 更改WM_NCHITTESTHTTRANSPARENT,使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 客户端配置文件对此进行了测试。

于 2011-12-26T12:11:38.340 回答
3

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

或者

这是你想要的吗?

public class MyLabel : Label
{
    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        //Do derived class stuff here
    }
}
于 2009-02-13T18:47:26.967 回答
3

扩展的WS_EX_TRANSPARENT窗口样式实际上是这样做的(它是就地工具提示使用的)。您可能想要考虑应用这种风格,而不是编写大量的处理程序来为您完成。

为此,请覆盖该CreateParams方法:

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

进一步阅读:

于 2009-02-13T18:54:43.470 回答