C# 在鼠标位置上创建新标签

C# 在鼠标位置上创建新标签,c#,.net,winforms,C#,.net,Winforms,你好,我有这个代码: private Label newLabel = new Label(); Int32 mouseX; Int32 mouseY; private void form_MouseMove(object sender, MouseEventArgs e) { mouseY = Cursor.Position.Y; mouseX = Cursor.Position.X; } private void button1_Click

你好,我有这个代码:

private Label newLabel = new Label();
Int32         mouseX;
Int32         mouseY;

private void form_MouseMove(object sender, MouseEventArgs e)
{
    mouseY = Cursor.Position.Y;
    mouseX = Cursor.Position.X;
}

private void button1_Click(object sender, EventArgs e)
{
    int txt = Int32.Parse(textBox1.Text);

    for (int i = 0; i < txt; i++)
    {
        newLabel = new Label();
        newLabel.Location = new Point(mouseY, mouseX);
        newLabel.Size = new System.Drawing.Size(25, 25);
        newLabel.Text = i.ToString();
        newLabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        newLabel.ForeColor = Color.Red;
        newLabel.Font = new Font(newLabel.Font.FontFamily.Name, 10);
        newLabel.Font = new Font(newLabel.Font, FontStyle.Bold);
        newLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
        newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
        newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
        this.Controls.Add(newLabel);
    }
}
private Label newLabel=newLabel();
Int32鼠标;
Int32鼠标;
私有无效表单\u MouseMove(对象发送方,MouseEventArgs e)
{
mouseY=游标.Position.Y;
mouseX=游标.Position.X;
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
int txt=Int32.Parse(textBox1.Text);
对于(int i=0;i
我试图让它根据鼠标所在的位置创建标签,但它似乎是在整个显示器中创建位置。我认为如果我将坐标分配给
表单鼠标移动
,它将获得表单中的坐标。
有人能帮我解决这个问题吗?

光标。位置坐标是相对于整个屏幕的。您需要一个相对于表单左上角的位置。您只需从传递给MouseMove事件处理程序的mouseeventarg中获取该信息

    private void form_MouseMove(object sender, MouseEventArgs e)
    {
        mouseY = e.Location.Y;
        mouseX = e.Location.X;
    }
属性为(根据MSDN)

包含x和y鼠标坐标的点,以像素为单位, 相对于窗体的左上角


光标位置坐标相对于整个屏幕。您需要一个相对于表单左上角的位置。您只需从传递给MouseMove事件处理程序的mouseeventarg中获取该信息

    private void form_MouseMove(object sender, MouseEventArgs e)
    {
        mouseY = e.Location.Y;
        mouseX = e.Location.X;
    }
属性为(根据MSDN)

包含x和y鼠标坐标的点,以像素为单位, 相对于窗体的左上角


Steve是正确的,为了将屏幕坐标转换为控件坐标或窗体坐标,您可以使用此处描述的方法:

就你而言:

Point clientPoint = PointToClient( new Point( e.X, e.Y ) );

Steve是正确的,为了将屏幕坐标转换为控件坐标或窗体坐标,您可以使用此处描述的方法:

就你而言:

Point clientPoint = PointToClient( new Point( e.X, e.Y ) );

这是行不通的,鼠标位置总是非常靠近按钮。你需要考虑一种非常不同的UI,类似于Road + Doop.这是行不通的,鼠标的位置总是非常接近按钮。你需要考虑一种非常不同的UI,类似于拖拽的东西。