在Winform编程中可能我们会觉得windows自己的窗体样式有点丑,想要好看一些的,可是我们将窗体边框隐藏之后又发现窗体没办法移动,这时我们就需要自己做一些操作,让鼠标不管点着窗体什么地方都可以移动窗体。
我的做法时做一个父窗体,其他需要无边框可移动的窗体都继承它,请看代码
/// <summary>
/// 一个可移动窗体无Border父窗体类
///
/// </summary>
public partial class FormParent : Form
{
public FormParent()
{
InitializeComponent();
}
//鼠标拖动变量
protected bool isMouseDown = false;
protected Point FormLocation;
protected Point mouseOffset;
//鼠标按下时记录窗体位置
protected void FormParent_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
FormLocation = this.Location;
mouseOffset = Control.MousePosition;
}
}
//鼠标移动时改变窗体位置
protected void FormParent_MouseMove(object sender, MouseEventArgs e)
{
int x = 0;
int y = 0;
if (isMouseDown)
{
Point pt = Control.MousePosition;
x = mouseOffset.X - pt.X;
y = mouseOffset.Y - pt.Y;
this.Location = new Point(FormLocation.X - x, FormLocation.Y - y);
}
}
//鼠标松开后释放窗体跟随
protected void FormParent_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
}