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

问题描述 投票:0回答:4

使用此事件标签就消失了,我该怎么办?

    private void label4_MouseMove(object sender, MouseEventArgs e)
    {
        label4.Location = new Point(Cursor.Position.X, Cursor.Position.Y);
    }
c# label move
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
投票

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

您需要调整位置。例如,如果容器是

Form
,您可以找到它在屏幕中的位置,并通过它计算光标相对于屏幕的位置。

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


3
投票

使用表单的 PointToClient() 函数将鼠标 X/Y 坐标转换为相对于表单的点,这样就可以了。

编辑:改用鼠标事件参数对象属性:

Label1.Location = New Point(e.X, e.Y)

PS 请原谅 VB,这台电脑上没有 C#


2
投票

元素的位置是相对于其父元素的。在这种情况下,尽管您使用绝对鼠标位置作为其位置。

您需要将鼠标位置转换到父元素的坐标系中。

在标签的父元素上使用

PointToClient
方法。

© www.soinside.com 2019 - 2024. All rights reserved.