一、
Point point = new Point();
bool isMove = false;//是否移动
private void MainMenu_MouseDown(object sender, MouseEventArgs e)
{
point = e.Location;//按住的点
isMove = true;
}
private void MainMenu_MouseMove(object sender, MouseEventArgs e)
{
Point pointNew;
if (e.Button == MouseButtons.Left && isMove)
{
this.WindowState = FormWindowState.Normal;
if (width <= 0 || height <= 0)
{
//屏幕大小
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
}
else
{
this.Width = width;
this.Height = height;
}
this.StartPosition = FormStartPosition.Manual; //窗体的位置由Location属性决定
this.Refresh();
pointNew = e.Location;//按住的点拖动到的位置
Point fPointNew = new Point(pointNew.X - point.X, pointNew.Y - point.Y);//相对于原来起点的距离点的描述
this.Location += new Size(fPointNew);
}
}
二、
private Point mouseOff; //抓取窗体Form中的鼠标的坐标,需要设置一个参数
private bool leftFlag; //标签,用来标记鼠标的左键的状态
private void MainMenu_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) //判断鼠标左键是否被按下
{
mouseOff = new Point(e.X, e.Y); //通过结构,将鼠标在窗体中的坐标(e.X,e.Y)赋值给mouseOff参数
leftFlag = true; //标记鼠标左键的状态
}
}
private void MainMenu_MouseMove(object sender, MouseEventArgs e)
{
if (leftFlag) //判断,鼠标左键是否被按下
{
this.WindowState = FormWindowState.Normal;
if (width <= 0 || height <= 0)
{
//屏幕大小
this.Width = Screen.PrimaryScreen.WorkingArea.Width;
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
}
else
{
this.Width = width;
this.Height = height;
}
this.StartPosition = FormStartPosition.Manual; //窗体的位置由Location属性决定
this.Refresh();
Point mouseSet = Control.MousePosition; //抓取屏幕中鼠标光标所在的位置
mouseSet.Offset(-mouseOff.X, -mouseOff.Y); //两个坐标相减,得到窗体左上角相对于屏幕的坐标
Location = mouseSet; //将上面得到的坐标赋值给窗体Form的Location属性
}
}
private void MainMenu_MouseUp(object sender, MouseEventArgs e)
{
if (leftFlag)
{
leftFlag = false;
}
}