楼主参考下面的代码。我电脑上测试过,这里放的是一个Button,你可以换成你的Control。 最初显示在窗体的左上角,这个你很容易就改到右下角了。 可以在窗体上随意拖动,拖动的过程中有一个小黑框跟随鼠标。 private Control control; public Form1() { InitializeComponent(); control = new Button(); control.MouseDown += new MouseEventHandler(control_MouseDown); control.MouseMove += new MouseEventHandler(control_MouseMove); control.MouseUp += new MouseEventHandler(control_MouseUp); this.Controls.Add(control);
InitializeComponent();
UserControl uc = new UserControl;
uc.name = "usercontrol1";
groupBox1.Controls.Add(uc);//把groupBox1放到Form1右下角就可以了
}
既然可以任意移动,最好记录下最后的位置,以便下次启动时移动到上次位置要设置位置很容易,把Location属性设置一下就行了我不知道你的意思是不是怎么才能通过鼠标移动控件?
如果是用户控件,参加二楼。
最初显示在窗体的左上角,这个你很容易就改到右下角了。
可以在窗体上随意拖动,拖动的过程中有一个小黑框跟随鼠标。
private Control control;
public Form1()
{
InitializeComponent(); control = new Button();
control.MouseDown += new MouseEventHandler(control_MouseDown);
control.MouseMove += new MouseEventHandler(control_MouseMove);
control.MouseUp += new MouseEventHandler(control_MouseUp);
this.Controls.Add(control);
}
Point mouseDownPoint = Point.Empty;
Rectangle rect = Rectangle.Empty;
bool isDrag = false;
void control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDownPoint = e.Location;
rect = control.Bounds;
}
}
void control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDrag = true;
rect.Location = getPointToForm(new Point(e.Location.X - mouseDownPoint.X, e.Location.Y - mouseDownPoint.Y));
this.Refresh();
}
}
void control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (isDrag)
{
isDrag = false;
control.Location = rect.Location;
this.Refresh();
}
reset(); }
}
//重置变量
private void reset()
{
mouseDownPoint = Point.Empty;
rect = Rectangle.Empty;
isDrag = false;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (rect != Rectangle.Empty)
{
if (isDrag)
{
e.Graphics.DrawRectangle(Pens.Black, rect);
}
else
{
e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
}
}
}
private Point getPointToForm(Point p)
{
return this.PointToClient(control.PointToScreen(p));
}