Search code examples
c#timerevent-handling

How to create a label that show continuous coordinates of mouse C#


How to create a label that show continuous coordinates of mouse C#

I tested a few different options, and I feel like a timer tick event would be the best to update the label consistantly. But I am doing something wrong and I can't seem to get it working.

        private void timer1_Tick(object sender, EventArgs e)
        {
            Point position = Cursor.Position;
            position = Cursor.Position;
            int x = position.X;
            int y = position.Y;
            string str = x.ToString() + ":" + y.ToString();
            coords.Text = str;

        }

Solution

  • Why not use a simple MouseMove event?! Assuming you are using WinForms this very simple code shows the mouse location on a Form:

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        label1.Text = $"{e.X:0},{e.Y:0}";
    }
    

    And for the less efficient Timer approach:

    private void timer1_Tick(object sender, EventArgs e)
    {
        label1.Text = $"{Cursor.Position.X:0},{Cursor.Position.Y:0}";
    }
    

    Just make sure to set the Timer.Enabled to True for it to work.