如何在运行时移动winform上的标签

3
使用这个事件,标签就会消失,我该怎么做?
    private void label4_MouseMove(object sender, MouseEventArgs e)
    {
        label4.Location = new Point(Cursor.Position.X, Cursor.Position.Y);
    }
4个回答

5
handle these three event ...
Control actcontrol;
 Point   preloc;
 void label1_Mousedown(object sender, MouseEventArgs e)
        {

            actcontrol = sender as Control;
            preloc = e.Location;
            Cursor = Cursors.Default;


        }
        void label1_MouseMove(object sender, MouseEventArgs e)
        {
            if (actcontrol == null || actcontrol != sender)
                return;
            var location = actcontrol.Location;
            location.Offset(e.Location.X - preloc.X, e.Location.Y - preloc.Y);            
            actcontrol.Location = location;

        }
        void label1_MouseUp(object sender, MouseEventArgs e)
        {
            actcontrol = null;
            Cursor = Cursors.Default;

        }

3
使用表单的PointToClient()函数将鼠标X/Y坐标转换为相对于您的表单的点,就可以了。
编辑:改用鼠标事件参数对象属性:
Label1.Location = New Point(e.X, e.Y)

抱歉,这台电脑上没有C#,只有VB。


3
< p > label4 的位置是相对于容器(Form 或父控件)的,光标位置可能相对于屏幕。

您需要调整位置。例如,如果容器是 Form,则可以在屏幕上找到其位置,并计算光标相对于屏幕的位置。

这只是一种可能的原因,但它经常发生 :)


根据这些信息,已经成功地启动并运行了。 - Darkmage

1

元素的位置是相对于其父元素而言的。但在此情况下,你使用的是鼠标的绝对位置作为其所在位置。

你需要将鼠标位置转换为父元素的坐标系。

在标签的父元素上使用PointToClient方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接