C#-WinForm鼠标在界面的任意位置移动窗体(组件方法实现)
前言
有的时候窗体需要被设计成“无边框”的形式,也就是FormBorderStyle属性被设置成None(如图所示),窗体没有了标题栏就无法拖动很不方便,本文就是在实际生产中遇到该问题的解决方案。
源代码
组件
创建组件类
我对其的命名是:MouseMoveController.cs ,也可以根据自己需要命名。
组件类源代码
向组件类中写入代码:
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace Landriesnidis.Control.Component
{
public partial class MouseMoveController : Component
{
public Form Form { get; set; }
private List<Control> Controls { get; set; } = new List<Control>();
private Dictionary<object, Point> dictMouseDowmPoint = new Dictionary<object, Point>();
private bool leftFlag = false;
public MouseMoveController()
{
InitializeComponent();
}
public MouseMoveController(IContainer container)
{
container.Add(this);
InitializeComponent();
}
/// <summary>
/// 添加一个控件
/// </summary>
/// <param name="control">控件(或窗体)对象</param>
public void Add(Control control)
{
InitControlEvents(control);
}
/// <summary>
/// 添加一组控件
/// </summary>
/// <param name="controls">控件(或窗体)对象的集合</param>
public void Add(ICollection<Control> controls)
{
InitAllControlsEvents(controls);
}
/// <summary>
/// 移除一个控件
/// </summary>
/// <param name="control">控件(或窗体)对象</param>
/// <returns></returns>
public bool Remove(Control control)
{
dictMouseDowmPoint.Remove(control);
return Controls.Remove(control);
}
/// <summary>
/// 清除所有受控的控件
/// </summary>
public void Clear()
{
dictMouseDowmPoint.Clear();
Controls.Clear();
}
private void InitControlEvents(Control control)
{
control.MouseDown += (obj, args) => {
if (args.Button == MouseButtons.Left)
{
Point mouseSet = Control.MousePosition;
if (dictMouseDowmPoint.ContainsKey(obj))
{
dictMouseDowmPoint[obj] = new Point(-(mouseSet.X - Form.Location.X), -(mouseSet.Y - Form.Location.Y));
}
else
{
dictMouseDowmPoint.Add(obj, new Point(-(mouseSet.X - Form.Location.X), -(mouseSet.Y - Form.Location.Y)));
}
leftFlag = true;
}
};
control.MouseMove += (obj, args) => {
if (leftFlag)
{
Point mouseSet = Control.MousePosition;
mouseSet.Offset(dictMouseDowmPoint[obj].X, dictMouseDowmPoint[obj].Y);
Form.Location = mouseSet;
}
};
control.MouseUp += (obj, args) => {
if (leftFlag)
{
leftFlag = false;
}
};
}
private void InitAllControlsEvents(ICollection<Control> controls)
{
foreach (Control control in controls)
{
InitControlEvents(control);
}
}
}
}
编译
在解决方案资源管理器中右键单击项目,选择 “生成”。新创建的组件在没有编译前不会出现在工具箱中(此时使用的是VS2017),所以需要执行一次生成。
在窗体中应用
从工具箱中拖拽出组件
从工具箱中将新组件拖进窗体设计界面中,此时组件默认命名为 “mouseMoveController1”。
编写窗体代码
代码如下:
using System;
using System.Windows.Forms;
namespace Landriesnidis.Control.Component
{
public partial class SettingsForm : Form
{
public SettingsForm()
{
InitializeComponent();
}
private void Settings_Load(object sender, EventArgs e)
{
// 添加跟随移动的窗体
mouseMoveController1.Form = this;
// 添加接收鼠标拖拽的控件或窗体
mouseMoveController1.Add(new Control[] { this, panelContent, panelTitle, labTitle });
}
}
}
效果展示
空白区域是Panel,文字区域是Label,均可拖拽移动移动。
参考资料
代码实现参考了文章:https://blog.csdn.net/wang1042857591/article/details/79182561