C#实现鼠标拖动自定义窗口

  1. 首先要把Winform默认的边框去掉:

this.FormBorderStyle = FormBorderStyle.None;

    

图1 默认窗口                    图2 去掉默认边框

 

  1. 在窗体上拖入一个panel,设置panel属性,并拖入自己想要的控件。
  1. panel1.Dock = DockStyle.Fill;
  2. panel1.BackgroundImage = 诚信.Properties.Resources.login;
  3. panel1.BackgroundImageLayout = ImageLayout.Stretch;
    1. 给panel添加三个事件: MouseUp、MouseMove、MouseDown。即可实现鼠标拖动窗体移动。
  4. private bool formMove = false;//窗体是否移动
  5. private Point formPoint;//记录窗体的位置
  6.  
  7. #region 拖动窗体移动
  8. private void panel1_MouseUp(object sender, MouseEventArgs e)
  9. {
  10.  
  11.     if (e.Button == MouseButtons.Left)//按下的是鼠标左键
  12.     {
  13.          formMove = false;//停止移动
  14.     }
  15.  
  16. }
  17.  
  18. private void panel1_MouseMove(object sender, MouseEventArgs e)
  19. {
  20.     if (formMove == true)
  21.     {
  22.         Point mousePos = Control.MousePosition;
  23.         mousePos.Offset(formPoint.X, formPoint.Y);
  24.         Location = mousePos;
  25.     }
  26. }
  27.  
  28. private void panel1_MouseDown(object sender, MouseEventArgs e)
  29. {
  30.     formPoint = new Point();
  31.     int xOffset;
  32.     int yOffset;
  33.     if (e.Button == MouseButtons.Left)
  34.     {
  35.         xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
  36.         yOffset = -e.Y - SystemInformation.FrameBorderSize.Height;//SystemInformation.CaptionHeight -
  37.         formPoint = new Point(xOffset, yOffset);
  38.         formMove = true;//开始移动
  39.     }
  40. }
  41. #endregion
    1. 运行结果

      图3 运行结果

posted @ 2015-04-22 14:49  小白托罗夫斯基  阅读(1384)  评论(0编辑  收藏  举报