在运行时在 WinForm 上移动标签,可以通过以下步骤实现:
以下是一个示例代码:
private bool isLabelMoving = false;
private Point mouseOffset;
private void label1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isLabelMoving = true;
mouseOffset = new Point(e.X, e.Y);
}
}
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (isLabelMoving)
{
Point mousePos = this.PointToClient(Cursor.Position);
label1.Location = new Point(mousePos.X - mouseOffset.X, mousePos.Y - mouseOffset.Y);
}
}
private void label1_MouseUp(object sender, MouseEventArgs e)
{
isLabelMoving = false;
}
在上面的示例代码中,我们首先定义了一个布尔变量 isLabelMoving
和一个 mouseOffset
变量,用于存储鼠标在标签控件上的位置。然后,在鼠标按下事件处理程序中,我们检查鼠标按下的按钮是否为左键,如果是,则将 isLabelMoving
设置为 true,并将鼠标在标签控件上的位置存储在 mouseOffset
变量中。在鼠标移动事件处理程序中,我们检查 isLabelMoving
是否为 true,如果是,则获取鼠标在窗体上的位置,并将标签控件的位置更新为鼠标位置减去 mouseOffset
变量的值。最后,在鼠标释放事件处理程序中,我们将 isLabelMoving
设置为 false。
通过以上步骤,我们可以在运行时在 WinForm 上移动标签。
领取专属 10元无门槛券
手把手带您无忧上云