winform程序中为无边框窗体手动添加窗体拖动代码
Point oldMousePoint;//记录开始移动窗口前鼠标点下箭头的位置
Point oldFormPoint;//记录开始移动窗口前窗体位置
/// <summary>
/// 窗体鼠标按下事件中初始化oldMousePoint,oldFormPoint
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button ==MouseButtons .Left )
{
oldMousePoint = new Point(Control.MousePosition.X, Control.MousePosition.Y);
oldFormPoint = this.Location;
}
}
Point oldFormPoint;//记录开始移动窗口前窗体位置
/// <summary>
/// 窗体鼠标按下事件中初始化oldMousePoint,oldFormPoint
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button ==MouseButtons .Left )
{
oldMousePoint = new Point(Control.MousePosition.X, Control.MousePosition.Y);
oldFormPoint = this.Location;
}
}
/// 窗体鼠标按下移动事件中分别算出鼠标箭头新的位置与旧位置在X,Y方向上的增量并分别加在原始旧窗口的X,Y方向上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//判断是否是鼠标左键按下
{
int addPointX = Control.MousePosition.X - oldMousePoint.X;
int addPointY = Control.MousePosition.Y - oldMousePoint.Y;
this.Location = new Point(oldFormPoint.X + addPointX, oldFormPoint.Y + addPointY);
}
}
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//判断是否是鼠标左键按下
{
int addPointX = Control.MousePosition.X - oldMousePoint.X;
int addPointY = Control.MousePosition.Y - oldMousePoint.Y;
this.Location = new Point(oldFormPoint.X + addPointX, oldFormPoint.Y + addPointY);
}
}