C#实现窗体和任意控件的拖动
下面的这个窗体拖动类呐,是在http://www.webjx.com/htmldata/2005-02-27/1109468136.html这里学习相关知识后实践的结果,也不知道有哪些缺点,还望看过的朋友指正一下!
程序内有大部分注释了,欢迎大家指正了!
Code
[copy to clipboard]
CODE:
1using System;
2using System.Drawing;
3using System.Windows.Forms;
4
5namespace Yoker.FormUtils
6{
7 /**//// <summary>
8 /// <para>说明:窗体拖动类,通过这个类提供的方法实现窗体上任意控件可辅助拖动窗体</para>
9 /// <para>作者:Yoker.Wu</para>
10 /// <para>原创地址:http://Yoker.cnblogs.com</para>
11 /// </summary>
12 public class dragFormClass
13 {
14 private static bool isMouseDown = false;
15 private static Point mouseOffset;
16 private static Form _form;
17 public dragFormClass() { }
18
19 /**//// <summary>
20 /// 在窗体上增加拖拽事件
21 /// </summary>
22 /// <param name="control">控件对象</param>
23 public static void bindControl(Control control)
24 {
25 //如果控件为空
26 if (control == null)
27 {
28 return;
29 }
30 _form = control.FindForm();
31 //增加鼠标拖动窗体移动事件
32 control.MouseMove += new MouseEventHandler(control_MouseMove);
33 control.MouseDown += new MouseEventHandler(control_MouseDown);
34 control.MouseUp += new MouseEventHandler(control_MouseUp);
35 }
36 /**//// <summary>
37 /// 鼠标按下之时,保存鼠标相对于窗体的位置
38 /// </summary>
39 /// <param name="sender"></param>
40 /// <param name="e"></param>
41 private static void control_MouseDown(object sender, MouseEventArgs e)
42 {
43 if (e.Button == MouseButtons.Left)
44 {
45 Control control = sender as Control;
46 int offsetX = - e.X;
47 int offsetY = - e.Y;
48 //判断是窗体还是控件,从而改进鼠标相对于窗体的位置
49 if (!(control is System.Windows.Forms.Form))
50 {
51 offsetX = offsetX - control.Left;
52 offsetY = offsetY - control.Top;
53 }
54 //判断窗体有没有标题栏,从而改进鼠标相对于窗体的位置
55 if (_form.FormBorderStyle != FormBorderStyle.None)
56 {
57 offsetX = offsetX - SystemInformation.FrameBorderSize.Width;
58 offsetY = offsetY - SystemInformation.FrameBorderSize.Height - SystemInformation.CaptionHeight;
59 }
60 mouseOffset = new Point(offsetX, offsetY);
61 isMouseDown = true;
62 }
63 }
64 /**//// <summary>
65 /// 移动鼠标的时候改变窗体位置
66 /// </summary>
67 /// <param name="sender"></param>
68 /// <param name="e"></param>
69 private static void control_MouseMove(object sender, MouseEventArgs e)
70 {
71 if (isMouseDown)
72 {
73 Point mouse = Control.MousePosition;
74 mouse.Offset(mouseOffset.X, mouseOffset.Y);
75 _form.Location = mouse;
76 }
77 }
78 /**//// <summary>
79 /// 松开鼠标的时候,重设事件
80 /// </summary>
81 /// <param name="sender"></param>
82 /// <param name="e"></param>
83 private static void control_MouseUp(object sender, MouseEventArgs e)
84 {
85 if (e.Button == MouseButtons.Left)
86 {
87 isMouseDown = false;
88 }
89 }
90 }
91}
92