Search code examples
c#winformscursor

Insert Label at Cursor Location


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?


Solution

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