C#實現鼠標拖動自定義窗口

  1. 首先要把Winform默認的邊框去掉:

this.FormBorderStyle = FormBorderStyle.None; this

    

圖1 默認窗口                    圖2 去掉默認邊框 spa

 

  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 運行結果orm

相關文章
相關標籤/搜索