固定Form无边框进行拖拽移动两种方法

一、 

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值