1

I want to a label at the cursor position whenever the user clicks the form. From the answer in this question: Getting mouse position in c#

I have used

    private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        Label lbl = new Label();
        lbl.Location = Cursor.Position;
        lbl.Visible = true;
        this.Controls.Add(lbl);
    }

but when i run the program and click the form, nothing happens.

Pls what did i do wrong?

Community
  • 1
  • 1
  • 2
    May be you should you use something like, `lbl.Location = new point(e.X, e.Y)`. Then, you want some text in your label as well, or you will not see it, because it will not be wide enough – T.S. Sep 05 '13 at 22:14
  • I think the cursor.position is relative to the screen and not the form if I remember right. There is a way to get the position relative to the window. – Animal Style Sep 05 '13 at 22:15
  • The e.X and e.Y is the position where the user clicked. – crthompson Sep 05 '13 at 22:17

1 Answers1

1

Your code has a couple of problems. First, Cursor.Position returns the position of the cursor relative the screen, but the location of the label is measured relative to the form. This will result in the label being placed (most likely) somewhere the left and below of where you actually clicked. As Groo points out you could PointToClient to transform from screen coordinates to client (form) coordinates, but that's not necessary in this case, because the MouseEventArgs provides this already.

The second issue is that although you've set the Visible property to true (which actually isn't necessary since it defaults to true), you haven't actually given it any text to display. The label is added but you won't see be able to see it.

Use the location specified in the event (e.Location), and give the label some text (lbl.Text) so you can actually see it:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    Label lbl = new Label();
    lbl.Location = e.Location;
    lbl.Text = "Hello World";
    this.Controls.Add(lbl);
}

Finally, make sure you bind the event to your form correctly if you haven't already:

public Form1()
{
    InitializeComponent();
    this.MouseClick += Form1_MouseClick;
}
Community
  • 1
  • 1
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    +1 It's also worth mentioning that OP's code doesn't work because `Cursor.Position` returns the mouse location in screen coordinates, and label needs to be positioned in coordinates relative to its parent control (`Form`, in this case). Using the [`Form.PointToClient`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.pointtoclient.aspx) method would transform the `Cursor.Position` value into proper client coordinates (but it's unnecessary since event arguments already contain this information). – vgru Sep 05 '13 at 22:26
  • @Groo Thanks, I've added a detailed description of the issues for completeness. – p.s.w.g Sep 05 '13 at 22:36