Tuesday, November 2, 2010

C# Tutorial: Get Mouse Coordinates [Display them]

Here is the code

int x = 0, y = 0;
protected override void OnMouseMove(MouseEventArgs e)
    // Create the graphics object
    Graphics g = CreateGraphics();
    // Create the pen that will draw the line
    Pen p = new Pen(Color.Navy);
    // Create the pen that will erase the line
    Pen erase = new Pen(Color.White);
    g.DrawLine(erase, 0, 0, x, y);
    // Save the mouse coordinates
    x = e.X; y = e.Y;
    g.DrawLine(p, 0, 0, x, y);
    label1.Location = new Point(x - label1.Width, y); // Place the label on the mouse left 
    label2.Location = new Point(x, y - label2.Height); // Place the label on the mouse right
    label1.Text = x.ToString(); label2.Text = y.ToString();   

Or download the solution


  1. Nice site, nice and easy on the eyes and great content too.

  2. very nice, but I want to control also the position of the mouse out of the C# windows, I meant the complete OS area (desktop).
    Do zoy ynow how to do it?