代码库のC#可移动按钮“相关代码”
#region 可移动按钮“相关代码”
Point mouse_offset;
private void Button_MouseDown(object sender , MouseEventArgs e)
{
mouse_offset = e.Location; //将当前鼠标相对于“窗体”左上角的坐标赋值给mouse_offset
}
private void Button_MouseMove(object sender , MouseEventArgs e)
{
if ( e.Button == MouseButtons.Left )
{
//将相对屏幕坐标转换为相对工作区的坐标。
int left = PointToClient(Control.MousePosition).X - mouse_offset.X;
int top = PointToClient(Control.MousePosition).Y - mouse_offset.Y;
//左右可能越界
if(left<0)
left=0;
if ( left > this.Width )
left = this.Width - ( (Button)sender ).Width;
//上下可能越界
if ( top < 0 )
top = 0;
if ( top > this.Height )
top = this.Height - ( (Button)sender ).Height;
( (Button)sender ).Left = left;
( (Button)sender ).Top = top;
}
}
#endregion