中国领先的工业平台

返回贤集网 返回微头条
贤集网技术微头条APP获取

C# WinForm实现窗体上控件自由拖动功能示例

 山东大明消毒科技有限公司

下载贤集网APP入驻自媒体

本文实例讲述了C# WinForm实现窗体上控件自由拖动功能。分享给大家供大家参考,具体如下:

说明:首先在窗体上放一个PictrueBox控件,命名为pb1,拖动完整代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. namespace WinFormDrag
  10. {
  11. public partial class Form1 : Form
  12. {
  13. //鼠标按下坐标(control控件的相对坐标)
  14. Point mouseDownPoint = Point.Empty;
  15. //显示拖动效果的矩形
  16. Rectangle rect = Rectangle.Empty;
  17. //是否正在拖拽
  18. bool isDrag = false;
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. }
  23. private void Form1_Paint(object sender, PaintEventArgs e)
  24. {
  25. if (rect != Rectangle.Empty)
  26. {
  27. if (isDrag)
  28. {//画一个和Control一样大小的黑框
  29. e.Graphics.DrawRectangle(Pens.Black, rect);
  30. }
  31. else
  32. {
  33. e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
  34. }
  35. }
  36. }
  37. ///
  38. /// 按下鼠标时
  39. ///
  40. ///
  41. ///
  42. private void pb1_MouseDown(object sender, MouseEventArgs e)
  43. {
  44. if (e.Button == MouseButtons.Left)
  45. {
  46. mouseDownPoint = e.Location;
  47. //记录控件的大小
  48. rect = pb1.Bounds;
  49. }
  50. }
  51. ///
  52. /// 移过时
  53. ///
  54. ///
  55. ///
  56. private void pb1_MouseMove(object sender, MouseEventArgs e)
  57. {
  58. if (e.Button == MouseButtons.Left)
  59. {
  60. isDrag = true;
  61. //重新设置rect的位置,跟随鼠标移动
  62. rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y));
  63. this.Refresh();
  64. }
  65. }
  66. ///
  67. /// 释放鼠标按钮时
  68. ///
  69. ///
  70. ///
  71. private void pb1_MouseUp(object sender, MouseEventArgs e)
  72. {
  73. if (e.Button == MouseButtons.Left)
  74. {
  75. if (isDrag)
  76. {
  77. isDrag = false;
  78. //移动control到放开鼠标的地方
  79. pb1.Location = rect.Location;
  80. this.Refresh();
  81. }
  82. reset();
  83. }
  84. }
  85. //重置变量
  86. private void reset()
  87. {
  88. mouseDownPoint = Point.Empty;
  89. rect = Rectangle.Empty;
  90. isDrag = false;
  91. }
  92. //把相对与control控件的坐标,转换成相对于窗体的坐标。
  93. private Point getPointToForm(Point p)
  94. {
  95. return this.PointToClient(pb1.PointToScreen(p));
  96. }
  97. }
  98. }
复制代码
最新回复

还没有人回复哦,抢沙发吧~

发布回复

为您推荐

热门交流