using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Text;
07.using System.Windows.Forms;
08.
09.namespace WindowsApplication1
10.{
11. public partial class FormDrag : Form
12. {
13. //将被拖动的控件
14. private Control control;
15. public FormDrag()
16. {
17. InitializeComponent();
18.
19. this.Paint += new System.Windows.Forms.PaintEventHandler(this.FormDrag_Paint);
20.
21. control = new Button();
22. control.MouseDown += new MouseEventHandler(control_MouseDown);
23. control.MouseMove += new MouseEventHandler(control_MouseMove);
24. control.MouseUp += new MouseEventHandler(control_MouseUp);
25. this.Controls.Add(control);
26. }
27.
28. //鼠标按下坐标(control控件的相对坐标)
29. Point mouseDownPoint = Point.Empty;
30. //显示拖动效果的矩形
31. Rectangle rect = Rectangle.Empty;
32. //是否正在拖拽
33. bool isDrag = false;
34. void control_MouseDown(object sender, MouseEventArgs e)
35. {
36. if (e.Button == MouseButtons.Left)
37. {
38. mouseDownPoint = e.Location;
39. //记录控件的大小
40. rect = control.Bounds;
41. }
42. }
43. void control_MouseMove(object sender, MouseEventArgs e)
44. {
45. if (e.Button == MouseButtons.Left)
46. {
47. isDrag = true;
48. //重新设置rect的位置,跟随鼠标移动
49. rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y));
50. this.Refresh();
51.
52. }
53. }
54. void control_MouseUp(object sender, MouseEventArgs e)
55. {
56. if (e.Button == MouseButtons.Left)
57. {
58. if (isDrag)
59. {
60. isDrag = false;
61. //移动control到放开鼠标的地方
62. control.Location = rect.Location;
63. this.Refresh();
64. }
65. reset();
66.
67. }
68. }
69. //重置变量
70. private void reset()
71. {
72. mouseDownPoint = Point.Empty;
73. rect = Rectangle.Empty;
74. isDrag = false;
75. }
76. //窗体重绘
77. private void FormDrag_Paint(object sender, PaintEventArgs e)
78. {
79. if (rect != Rectangle.Empty)
80. {
81. if (isDrag)
82. {//画一个和Control一样大小的黑框
83. e.Graphics.DrawRectangle(Pens.Black, rect);
84. }
85. else
86. {
87. e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
88. }
89. }
90. }
91. //把相对与control控件的坐标,转换成相对于窗体的坐标。
92. private Point getPointToForm(Point p)
93. {
94. return this.PointToClient(control.PointToScreen(p));
95. }
96.
97. }
98.}
鼠标拖动效果
最新推荐文章于 2022-08-11 15:06:26 发布