首页 > 代码库 > c# 实现窗体移动
c# 实现窗体移动
一般情况下:
1 1.添加下列代码到你的窗体中: 2 #region 轻松移动 3 4 bool isInMove; 5 Point oldPoint; 6 7 void InitializeEasyMove() 8 { 9 isInMove = false;10 11 this.MouseDown += new MouseEventHandler(EasyMove_MouseDown);12 this.MouseUp += new MouseEventHandler(EasyMove_MouseUp);13 this.MouseMove += new MouseEventHandler(EasyMove_MouseMove);14 }15 16 void EasyMove_MouseMove(object sender, MouseEventArgs e)17 {18 if (!isInMove) return;19 Point pt = PointToScreen(e.Location);20 if (pt.X == oldPoint.X || pt.Y == oldPoint.Y) return;21 this.Location = new Point(this.Location.X + pt.X - oldPoint.X, this.Location.Y + pt.Y - oldPoint.Y);22 oldPoint = pt;23 }24 25 void EasyMove_MouseUp(object sender, MouseEventArgs e)26 {27 isInMove = false;28 }29 30 void EasyMove_MouseDown(object sender, MouseEventArgs e)31 {32 isInMove = true;33 oldPoint = PointToScreen(e.Location);34 }35 36 #endregion37 38 2.在你的窗体的构造函数或Load事件中调用:39 InitializeEasyMove();
但是你会发现这样很麻烦,运行时也容易出错。
改进一:
增加mouseleave事件,当mouseleave的时候把isInMove 设置成false
这样虽然改进了一点。但是还有有点别扭
改进二:
使用win32api
1 public partial class Form6 : Form 2 { 3 [DllImport("user32.dll")] 4 public static extern bool ReleaseCapture(); 5 [DllImport("user32.dll")] 6 public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); 7 public const int WM_SYSCOMMAND = 0x0112; 8 public const int SC_MOVE = 0xF010; 9 public const int HTCAPTION = 0x0002;10 11 public Form6()12 {13 InitializeComponent();14 }15 16 private void Form6_MouseDown(object sender, MouseEventArgs e)17 {18 ReleaseCapture();19 SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);20 }21 }
代码量大大减少,直接消除鼠标移快速移动时出现bug的现象。但是当鼠标点击pannel,groupbox等还是没有反应
改进三:
1 public partial class Form1 : Form 2 { 3 [DllImport("user32.dll")] 4 public static extern bool ReleaseCapture(); 5 [DllImport("user32.dll")] 6 public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); 7 public const int WM_SYSCOMMAND = 0x0112; 8 public const int SC_MOVE = 0xF010; 9 public const int HTCAPTION = 0x0002;10 public Form1()11 {12 InitializeComponent();13 foreach (var item in this.Controls)14 {15 if ((item as GroupBox) != null)16 {17 (item as GroupBox).MouseDown += Form6_MouseDown;18 }19 else if ((item as Panel) != null)20 {21 (item as Panel).MouseDown += Form6_MouseDown;22 }23 }24 }25 26 private void Form6_MouseDown(object sender, MouseEventArgs e)27 {28 ReleaseCapture();29 SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);30 }31 }
将GroupBox ,pannel等控件添加mousedown动作
ok,大功告成
c# 实现窗体移动
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。