拖放 - 在 Winforms 中移动标签 [英] Drag and Drop - Moving a Label in Winforms

查看:22
本文介绍了拖放 - 在 Winforms 中移动标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个标签覆盖,可以让我的新控件轻松地在屏幕上移动.

I've created a label override that will allow my new control to be moved around the screen easily.

我附上了下面的代码,但是当我运行应用程序或尝试移动标签时,它总是关闭.它有时也会完全消失,留下痕迹或重置为 0,0 位置.看看截图.

I've attached the code below, but when I run the application or attempt to move the label it's always off. It also will sometimes just completely vanish, leave a trail or reset to the 0,0 location. Have a look at the screenshot.

我曾经让这个 100% 工作,但在最近的一些调整之后它再次出现在狗身上,我不知道如何让它工作.

I used to have this working 100%, but after some recent tweaking it has gone to the dogs again and I'm not sure how to get it working.

屏幕截图:

代码:

internal sealed class DraggableLabel : Label
{

    private bool _dragging;
    private int _mouseX, _mouseY;

    public DraggableLabel()
    {
        DoubleBuffered = true;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
      if (_dragging)
        {
            Point mposition = PointToClient(MousePosition);
            mposition.Offset(_mouseX, _mouseY);

            Location = mposition;
        }
        base.OnMouseMove(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
       if (e.Button == MouseButtons.Left)
        {
           _dragging = true;
           _mouseX = -e.X;
           _mouseY = -e.Y;
           BringToFront();
           Invalidate();
        }
        base.OnMouseDown(e);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        if (_dragging)
        {
            _dragging = false;
            Cursor.Clip = new Rectangle();
            Invalidate();
        }

        base.OnMouseUp(e);
    }

}

推荐答案

OnMouseMove() 代码不好.改为这样做:

The OnMouseMove() code is bad. Do it like this instead:

private Point lastPos;

protected override void OnMouseMove(MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        int dx = e.X - lastPos.X;
        int dy = e.Y - lastPos.Y;
        Location = new Point(Left + dx, Top + dy);
        // NOTE: do NOT update lastPos, the relative mouse position changed
    }
    base.OnMouseMove(e);
}

protected override void OnMouseDown(MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        lastPos = e.Location;
        BringToFront();
        this.Capture = true;
    }
    base.OnMouseDown(e);
}

protected override void OnMouseUp(MouseEventArgs e) {
    this.Capture = false;
    base.OnMouseUp(e);
}

屏幕截图还显示表单未正确重绘的证据.您没有留下任何可能导致这种情况的线索.

The screen shot also shows evidence of the form not redrawing properly. You didn't leave any clue as to what might cause that.

这篇关于拖放 - 在 Winforms 中移动标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆