WinForm 实现鼠标拖动控件跟随效果(图文)

2021-01-18 10:14:28 浏览数 (1)

1. 运行初始窗口如下:

2. 拖动后效果如下:

3. 代码如下:

代码语言:javascript复制

public partial class Form1 : Form
{
    /*
     * 理解了下面的几个概念,就能完全明白相对坐标的变化.
     * MouseEventArgs e 为事件鼠标参数,因此,e.Location 指示了位于事件源上的光标坐标
     * Cursor.Position 获取的是相对于用户屏幕的光标坐标
     * PointToClient() 方法可将屏幕坐标 Cursor.Position 换算成工作区的坐标
     * 因此,换算后的 Cursor.Position 减去 e.Location 得到的始终是事件源的 Location
    */

    /// <summary>
    /// 鼠标按下为true
    /// </summary>
    private bool Mousedown;

    /// <summary>
    /// 鼠标在事件源的位置
    /// </summary>
    private int CurX = 0;
    private int CurY = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void Controls_MouseDown(object sender, MouseEventArgs e)
    {
        CurX = e.X;
        CurY = e.Y;
        Mousedown = true;
        if (sender is TextBox)
        {
            ((TextBox)sender).Cursor = Cursors.Arrow;
        }
    }

    private void Controls_MouseMove(object sender, MouseEventArgs e)
    {
        if (Mousedown)
        {
            // 获取当前屏幕的光标坐标
              Point pTemp = new Point(Cursor.Position.X, Cursor.Position.Y);
            // 转换成工作区坐标
              pTemp = this.PointToClient(pTemp);
            // 定位事件源的 Location
            Control control = sender as Control;
            control.Location = new Point(pTemp.X - CurX, pTemp.Y - CurY);                
        }
    }

    private void Controls_MouseUp(object sender, MouseEventArgs e)
    {
        Mousedown = false;
        if (sender is TextBox)
        {
            ((TextBox)sender).Cursor = Cursors.IBeam;
        }
    }
}

0 人点赞