为了美观,去掉窗体的标题栏,给窗体的FormBorderStyle
属性设置为None
,这时,使用鼠标拖动和缩放窗口就会失效。下面几种简单方法来恢复所需效果。
鼠标的拖动
- 注册 窗体的
MouseDown
和MouseMove
事件,通过设置窗体的Location
来实现移动。(较简单,不需要添加其他元素)
public partial class FmMain : Form {
private Point formPoint = new Point();
public FmMain() {
InitializeComponent();
}
private void FmMain_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
Point myPosittion = MousePosition;
myPosittion.Offset(-formPoint.X, -formPoint.Y);
Location = myPosittion;
}
}
private void FmMain_MouseDown(object sender, MouseEventArgs e) {
formPoint.X = e.X;
formPoint.Y = e.Y;
}
}
- 设置一个透明的 panel 置于底层,通过设置 panel 的
MouseDown
和MouseMove
事件,来实现窗体的拖动。(多添加了一个元素,实现方式和第一种差不多)
public partial class FmMain : Form {
private Point mousePoint = new Point();
public FmMain() {
InitializeComponent();
}
private void panelMain_MouseDown(object sender, MouseEventArgs e) {
base.OnMouseDown(e);
this.mousePoint.X = e.X;
this.mousePoint.Y = e.Y;
}
private void panelMain_MouseMove(object sender, MouseEventArgs e) {
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left) {
this.Top = Control.MousePosition.Y - mousePoint.Y;
this.Left = Control.MousePosition.X - mousePoint.X;
}
}
}
网上还有其他方法,相比较这两种稍微有点复杂。