下面我们来测试下拖动的功能。
创建一个Form窗体,可以再界面上添加你要测试的控件类型,此处我只用TextBox左下测试。在Load的中添加以下代码,将Form中的所有控件挂载上拖拉功能。
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
new MoveControl(ctrl);
}
}
此时,有心人可能会发现VS中拖动控件时,将会出现黑色边框,而处于没有。
这也很简单,我们在MouseMove时加上如下代码即可。
/// <summary>
/// 绘制拖拉时的黑色边框
/// </summary>
public static void DrawDragBound(Control ctrl)
{
ctrl.Refresh();
Graphics g = ctrl.CreateGraphics();
int width = ctrl.Width;
int height = ctrl.Height;
Point[] ps = new Point[5]{new Point(0,0),new Point(width -1,0),
new Point(width -1,height -1),new Point(0,height-1),new Point(0,0)};
g.DrawLines(new Pen(Color.Black), ps);
}
/// <summary>
/// 鼠标移动事件:让控件跟着鼠标移动
/// </summary>
void MouseMove(object sender, MouseEventArgs e)
{
Cursor.Current = Cursors.SizeAll; //当鼠标处于控件内部时,显示光标样式为SizeAll
//当鼠标左键按下时才触发
if (e.Button == MouseButtons.Left)
{
MoveControl.DrawDragBound(this.currentControl);
cPoint = Cursor.Position; //获得当前鼠标位置
int x = cPoint.X - pPoint.X;
int y = cPoint.Y - pPoint.Y;
currentControl.Location = new Point(currentControl.Location.X + x, currentControl.Location.Y + y);
pPoint = cPoint;
}
}
同时要在MoveUp的时候,刷新一下自己,让黑色边框消失掉!
/// <summary>
/// 鼠标弹起事件:让自定义的边框出现
/// </summary>
void MouseUp(object sender, MouseEventArgs e)
{
this.currentControl.Refresh();
}
接着用没有边框的控件测试下就会很明显。如下图所示:

2.通过边框拖拉控件改变大小
此处的主要思路为:点击控件的时候,创建一个自定义的用户控件,该用户控件响应区域就是传入控件的边框区域,同时给它画上虚线与8个小圆圈。
第一、创建用户控件--FrameControl(边框控件),然后增加一个字段用来保存传入的控件,还有加载事件,此处类同前面的MoveControl。
FrameControl
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DragControl
{
public partial class FrameControl : UserControl
{
#region Constructors
public FrameControl(Control ctrl)
{
baseControl = ctrl;
AddEvents();
}
#endregion
#region Fields
Control baseControl; //基础控件,即被包围的控件
#endregion
#region Methods
/// <summary>
/// 加载事件
/// </summary>
private void AddEvents()
{
this.Name = "FrameControl" + baseControl.Name;
this.MouseDown += new MouseEventHandler(FrameControl_MouseDown);
this.MouseMove += new MouseEventHandler(FrameControl_MouseMove);
this.MouseUp += new MouseEventHandler(FrameControl_MouseUp);
}
#endregion
#region Events
/// <summary>
/// 鼠标按下事件:记录当前鼠标相对窗体的坐标
/// </summary>
void FrameControl_MouseDown(object sender, MouseEventArgs e)
{
}
/// <summary>
/// 鼠标移动事件:让控件跟着鼠标移动
/// </summary>
void FrameControl_MouseMove(object sender, MouseEventArgs e)
{
}
/// <summary>
/// 鼠标弹起事件:让自定义的边框出现
/// </summary>
void FrameControl_MouseUp(object sender, MouseEventArgs e)
{
}
#endregion
}
}










