C#开发winform窗口实现无边框移动
效果展示:
教程:
- 创建窗体,选中窗体属性设置BorderStyle = None, 这样窗体就是无边框了
- 按f7, 将核心移动代码复制到窗体代码后台
将以下代码复制:
#region 无边框窗体移动
// 鼠标按下
private bool isMouse = false; // 鼠标是否按下
// 原点位置
private int originX = 0;
private int originY = 0;
// 鼠标按下位置
private int mouseX = 0;
private int mouseY = 0;
private void windowMove_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) { // 判断鼠标按键
isMouse = true;
// 屏幕坐标位置
originX = this.Location.X;
originY = this.Location.Y;
// 鼠标按下位置
mouseX = originX + e.X;
mouseY = originY + e.Y;
}
}
// 鼠标移动
private void windowMove_MouseMove(object sender, MouseEventArgs e)
{
if (isMouse) {
// 移动距离
int moveX = (e.X + this.Location.X) - mouseX;
int moveY = (e.Y + this.Location.Y) - mouseY;
int targetX = originX + moveX;
int targetY = originY + moveY;
this.Location = new Point(targetX, targetY);
}
}
// 鼠标释放
private void windowMove_MouseUp(object sender, MouseEventArgs e)
{
if (isMouse) {
isMouse = false;
}
}
#endregion
- 设置控件鼠标事件:鼠标按下,鼠标移动,鼠标松开