在鼠标位置的位置创建新标签

时间:2013-09-30 23:12:58

标签: 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(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);
    }
}

我尝试根据鼠标的位置创建标签,但似乎是在整个显示中创建了位置。我认为如果我将坐标分配给form mouse move,它将获得表格内的坐标。 愿有人帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

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

即可
    private void form_MouseMove(object sender, MouseEventArgs e)
    {
        mouseY = e.Location.Y;
        mouseX = e.Location.X;
    }

MouseEventArgs.Location属性(根据MSDN)

  

包含x和y-鼠标坐标的点(以像素为单位)   相对于表格的左上角。

答案 1 :(得分:0)

史蒂夫是正确的,为了将屏幕坐标转换为控制或形成坐标,您可以使用此处描述的方法:

How to convert screen coordinates to form relative coordinates (winforms)?

在你的情况下:

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