欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm实现鼠标拖动控件跟随效果

程序员文章站 2023-12-18 23:00:46
本文实例为大家分享了winform实现鼠标拖动控件跟随效果的具体代码,供大家参考,具体内容如下 1. 运行初始窗口如下: 2. 拖动后效果如下: 3. 代码如...

本文实例为大家分享了winform实现鼠标拖动控件跟随效果的具体代码,供大家参考,具体内容如下

1. 运行初始窗口如下:

WinForm实现鼠标拖动控件跟随效果

2. 拖动后效果如下:

WinForm实现鼠标拖动控件跟随效果

3. 代码如下:

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;
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: