在运行时移动窗体上的控件






4.92/5 (92投票s)
仅使用一个帮助类和一行代码,在运行时移动窗体上的控件
引言
在某些情况下,使用鼠标在窗体上移动控件会很有用。在这个项目中,有一个辅助类可以完成所有需要的工作。不仅可以移动控件,还可以移动其容器。
只需一行代码即可使控件可移动(不是难看的拖放)
Helper.ControlMover.Init(this.button1);
真的吗?是的!!
背景
这段代码使用匿名委托来完成繁重的工作。其优点之一是辅助类 ControlMover
只有 static
方法。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Helper
{
class ControlMover
{
public enum Direction
{
Any,
Horizontal,
Vertical
}
public static void Init(Control control)
{
Init(control, Direction.Any);
}
public static void Init(Control control, Direction direction)
{
Init(control, control, direction);
}
public static void Init(Control control, Control container, Direction direction)
{
bool Dragging = false;
Point DragStart = Point.Empty;
control.MouseDown += delegate(object sender, MouseEventArgs e)
{
Dragging = true;
DragStart = new Point(e.X, e.Y);
control.Capture = true;
};
control.MouseUp += delegate(object sender, MouseEventArgs e)
{
Dragging = false;
control.Capture = false;
};
control.MouseMove += delegate(object sender, MouseEventArgs e)
{
if (Dragging)
{
if (direction != Direction.Vertical)
container.Left = Math.Max(0, e.X + container.Left - DragStart.X);
if (direction != Direction.Horizontal)
container.Top = Math.Max(0, e.Y + container.Top - DragStart.Y);
}
};
}
}
}
Using the Code
项目源代码文件中提供了一个如何使用此代码的示例。所有控件都可以通过鼠标移动。此外,还提供了一个使用工具栏的简单分割器。另一个包含工具栏的面板可以通过其工具栏移动。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MoveYourControls
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Make your controls movable by a mouseclick
Helper.ControlMover.Init(this.button1);
Helper.ControlMover.Init(this.checkBox1);
Helper.ControlMover.Init(this.groupBox1);
Helper.ControlMover.Init(this.textBox1);
Helper.ControlMover.Init(this.label1);
// Move a panel by its toolstrip
Helper.ControlMover.Init(this.toolStrip2, this.panel3,
Helper.ControlMover.Direction.Any);
// Make a splitter from toolstrip
Helper.ControlMover.Init(this.toolStrip1, Helper.ControlMover.Direction.Vertical);
this.toolStrip1.LocationChanged += delegate(object sender, EventArgs e)
{
this.panel1.Height = this.toolStrip1.Top;
};
}
}
}
移动所有控件后的窗体。
关注点
有时,控件可能只能在一个方向上移动。这对于分割器等控件是正确的。辅助类有一个方向枚举器,可以使事情变得非常容易
Helper.ControlMover.Init(this.button1);
Helper.ControlMover.Init(this.button2, Helper.ControlMover.Direction.Any);
Helper.ControlMover.Init(this.button3, Helper.ControlMover.Direction.Horizontal);
Helper.ControlMover.Init(this.button4, Helper.ControlMover.Direction.Vertical);
玩得开心!!
历史
- 截至发布时,已提供版本 1.0.0.0。