当前位置: 移动技术网 > IT编程>开发语言>c# > C# WinForm实现窗体上控件自由拖动功能示例

C# WinForm实现窗体上控件自由拖动功能示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c# winform实现窗体上控件自由拖动功能。分享给大家供大家参考,具体如下:

说明:首先在窗体上放一个pictruebox控件,命名为pb1,拖动完整代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
namespace winformdrag
{
  public partial class form1 : form
  {
    //鼠标按下坐标(control控件的相对坐标)
    point mousedownpoint = point.empty;
    //显示拖动效果的矩形
    rectangle rect = rectangle.empty;
    //是否正在拖拽
    bool isdrag = false;
    public form1()
    {
      initializecomponent();
    }
    private void form1_paint(object sender, painteventargs e)
    {
      if (rect != rectangle.empty)
      {
        if (isdrag)
        {//画一个和control一样大小的黑框
          e.graphics.drawrectangle(pens.black, rect);
        }
        else
        {
          e.graphics.drawrectangle(new pen(this.backcolor), rect);
        }
      }
    }
    /// <summary>
    /// 按下鼠标时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void pb1_mousedown(object sender, mouseeventargs e)
    {
      if (e.button == mousebuttons.left)
      {
        mousedownpoint = e.location;
        //记录控件的大小
        rect = pb1.bounds;
      }
    }
    /// <summary>
    /// 移过时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void pb1_mousemove(object sender, mouseeventargs e)
    {
      if (e.button == mousebuttons.left)
      {
        isdrag = true;
        //重新设置rect的位置,跟随鼠标移动
        rect.location = getpointtoform(new point(e.location.x - mousedownpoint.x, e.location.y - mousedownpoint.y));
        this.refresh();
      }
    }
    /// <summary>
    /// 释放鼠标按钮时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void pb1_mouseup(object sender, mouseeventargs e)
    {
      if (e.button == mousebuttons.left)
      {
        if (isdrag)
        {
          isdrag = false;
          //移动control到放开鼠标的地方
          pb1.location = rect.location;
          this.refresh();
        }
        reset();
      }
    }
    //重置变量
    private void reset()
    {
      mousedownpoint = point.empty;
      rect = rectangle.empty;
      isdrag = false;
    }
    //把相对与control控件的坐标,转换成相对于窗体的坐标。
    private point getpointtoform(point p)
    {
      return this.pointtoclient(pb1.pointtoscreen(p));
    }
  }
}

更多关于c#相关内容感兴趣的读者可查看本站专题:《winform控件用法总结》、《c#窗体操作技巧汇总》、《c#数据结构与算法教程》、《c#常见控件用法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网