模拟拖动窗口标题栏的控件

cae*_*say 6 c# controls drag winforms

我已经构建了一个自定义控件,我想让人们点击并拖动我的控件,就像他们在窗口标题栏上拖动一样.做这个的最好方式是什么?

到目前为止,当窗口需要移动时,我没有成功地利用鼠标按下,向上和移动事件来解密.

SLa*_*aks 10

除了我的其他答案,您可以在控件中手动执行此操作,如下所示:

Point dragOffset;

protected override void OnMouseDown(MouseEventArgs e) {
    base.OnMouseDown(e);
    if (e.Button == MouseButtons.Left) {
        dragOffset = this.PointToScreen(e.Location);
        var formLocation = FindForm().Location;
        dragOffset.X -= formLocation.X;
        dragOffset.Y -= formLocation.Y;
    }
}

protected override void OnMouseMove(MouseEventArgs e) {
    base.OnMouseMove(e);

    if (e.Button == MouseButtons.Left) {
        Point newLocation = this.PointToScreen(e.Location);

        newLocation.X -= dragOffset.X;
        newLocation.Y -= dragOffset.Y;

        FindForm().Location = newLocation;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:测试和修复 - 现在实际上工作.


SLa*_*aks 5

最有效的方法是处理WM_NCHITTEST通知.

覆盖表单的WndProc方法并添加以下代码:

if (m.Msg == 0x0084) {              //WM_NCHITTEST
    var point = new Point((int)m.LParam);
    if(someRect.Contains(PointToClient(point))
        m.Result = new IntPtr(2);   //HT_CAPTION
}
Run Code Online (Sandbox Code Playgroud)

但是,如果此时有控件,我认为不会发送消息.