Hey I'm making a small application for my gaming buddies, and I have a picturebox that I'm drawing on.

The problem is, it appears as though the Location property of the MouseEventArgs is wrong, and it becomes even more so toward the bottom + right portion of the picture, like a lack of precision that gets multiplied as x and y increase.

Do I need to use a different way to get the mouse cursor location?

Dani AI

Generated

As discovered, the root cause is a coordinate-space mismatch: mouse events report points relative to the PictureBox control, while drawing onto the raw Image uses the image's pixel coordinates. If the PictureBox scales or centers the image (SizeMode other than Normal), those two spaces do not line up and the error grows toward the bottom/right.

Prefer one of two robust patterns: update a backing Bitmap (use a Graphics from the bitmap) and then call pictureBox.Invalidate() so the control repaints, or do all drawing in the PictureBox Paint handler using the supplied PaintEventArgs.Graphics. Avoid CreateGraphics for persistent drawing because its output is ephemeral and will be lost on resize/repaint. See the docs for Graphics.FromImage and the Paint pattern for details (Graphics.FromImage, Control.Paint).

If the PictureBox SizeMode is Zoom (or StretchImage), convert the mouse point to image coordinates before drawing. Example conversion for Zoom:

Point ToImageCoords(PictureBox pb, Point mouse)
{
    Image img = pb.Image;
    double imgW = img.Width, imgH = img.Height;
    double pbW = pb.ClientSize.Width, pbH = pb.ClientSize.Height;
    double scale = Math.Min(pbW / imgW, pbH / imgH);
    int dispW = (int)(imgW * scale), dispH = (int)(imgH * scale);
    int offsetX = (pbW - dispW) / 2, offsetY = (pbH - dispH) / 2;
    int x = (int)((mouse.X - offsetX) / scale);
    int y = (int)((mouse.Y - offsetY) / scale);
    x = Math.Max(0, Math.Min((int)imgW - 1, x));
    y = Math.Max(0, Math.Min((int)imgH - 1, y));
    return new Point(x, y);
}

Other caveats: account for DPI differences, control borders/padding, and interpolation rounding when the image is scaled. Converting coordinates explicitly and using the Paint/backing-bitmap approach prevents the drifting precision you saw.

Wow, nevermind.

I had created my a Graphics object from the image like this:

Graphics g = Graphics.FromImage( pictureBox.Image );

Which is wrong, and it should be:

Graphics g = pictureBox.CreateGraphics();

Now it's working just fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.