C# 按住鼠标左键移动窗体Form的位置,C#拖动窗体通用类
作者:C/S框架网|www.cscode.ne  发布日期:2021-06-01 10:03:52
  C# 按住鼠标左键移动窗体Form的位置,C#拖动窗体通用类


C# 按住鼠标左键移动窗体Form的位置,C#拖动窗体通用类




C# Code:

private void frmLogin_Load(object sender, EventArgs e)
{
  
//使用方法:在窗体的Load事件调用
  
FormDragDrop.Handle(this);
    
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




FormDragDrop.cs类:



C# Code:

/// <summary>
/// 拖动鼠标移动窗体Form通用类
/// </summary>
public class FormDragDrop
{
  
private Point _MouseOffset;
  
private bool _IsMouseDown = false;
  
private Form _form;
  
  
private FormDragDrop(Form form)
  {
    _form
= form;
  }
  
  
/// <summary>
  
/// 使用方法
  
/// </summary>
  
/// <param name="form"></param>
  
public static void Handle(Form form)
  {
    FormDragDrop F
= new FormDragDrop(form);
    F.HandleEvents();
  }
  
  
private void HandleEvents()
  {
    _form.MouseDown +
= On_MouseDown;
    _form.MouseMove +
= On_MouseMove;
    _form.MouseUp +
= On_MouseUp;
  }
  
  
private void On_MouseDown(object sender, MouseEventArgs e)
  {
    
int xOffset;
    
int yOffset;
    
    
if (e.Button == MouseButtons.Left)
    {
      xOffset
= -e.X;
      yOffset
= -e.Y;
      _MouseOffset
= new Point(xOffset, yOffset);
      _IsMouseDown
= true;
    }
  }
  
  
private void On_MouseMove(object sender, MouseEventArgs e)
  {
    
if (_IsMouseDown)
    {
      Point mousePos
= Control.MousePosition;
      mousePos.Offset(_MouseOffset.X, _MouseOffset.Y);
      _form.Location
= mousePos;
    }
  }
  
  
private void On_MouseUp(object sender, MouseEventArgs e)
  {
    
if (e.Button == MouseButtons.Left)
    {
      _IsMouseDown
= false;
    }
  }
  
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务



上一篇 下一篇