在我们写窗口程序的时候,会将窗口的边框属性设置为无,即:
FormBorderStyle = FormBorderStyle.None;
此时会有一些问题,比如 不能最小、最大化和关闭按钮,还有一个更重要的问题,窗口不能移动
这个是本篇要讲解的主题:
代码如下:
private bool formMove = false;//窗体是否移动
private Point formPoint;//记录窗体的位置
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
formPoint = new Point();
if (e.Button == MouseButtons.Left)
{
formPoint = new Point(e.X,e.Y);//获取鼠标在窗口上的坐标
formMove = true;//开始移动
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (formMove == true)
{
Point mousePos = Control.MousePosition;//获取鼠标在屏幕上的坐标
Point point = new Point(mousePos.X - formPoint.X, mousePos.Y - formPoint.Y);
this.Location = point; //设置窗口坐标
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//按下的是鼠标左键
{
formMove = false;//停止移动
}
}
以上是在拖动窗口就可以移动,一般来说都是在点击标题栏进行移动,所以我们在窗口的顶部插入一个 Panel (橘红色部分)
根据上面的代码,可以知道,只要创建三个 panel的鼠标事件
1. MouseMove
1. MouseDown
1. MouseUp
代码如下:
(这个代码与上面的代码有一点点不同,相当于第二种方法,或者说是上面代码的改进版)
private bool formMove = false;//窗体是否移动
private Point formPoint;//记录窗体的位置
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
formPoint = new Point();
if (e.Button == MouseButtons.Left)
{
formPoint = new Point(-e.X,-e.Y);//获取鼠标在窗口上的坐标
//formPoint = new Point(e.X,e.Y);
formMove = true;//开始移动
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (formMove == true)
{
Point mousePos = Control.MousePosition;//获取鼠标在屏幕上的坐标
mousePos.Offset(formPoint.X, formPoint.Y);
//mousePos.Offset(-formPoint.X, -formPoint.Y);
//Offset 是将此矩形的位置调整指定的量,但是给的是相对绝对值的,所以是整数,
//这时候鼠标移动就会再原来的坐标基础上追加,导致窗体的坐标与鼠标的坐标不一致,
//又因为屏幕坐标是左上角为00,向下和向右都是追加的不是递减的,
//所以需要用负数减去偏移量,这时候就能保障窗体是紧跟着鼠标的
this.Location = point; //设置窗口坐标
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//按下的是鼠标左键
{
formMove = false;//停止移动
}
}
本篇就讲解到这,欢迎大家到我的主页逛逛哦!!!