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;
}