Get cursor coordinates in C#

Asked

Viewed 302 times

1

I’m using the Control.MousePosition to get the mouse coordinates in windows 10.

Then use the following function to get a Printscreen:

public static Bitmap PrintScreen(Point Source,Point Destination)
    {
        Rectangle R = new Rectangle(Source.X, Source.Y, Destination.X - Source.X, Destination.Y - Source.Y);
        Bitmap printscreen = new Bitmap(R.Width,R.Height);
        Graphics graphics = Graphics.FromImage(printscreen as Image);
        graphics.CopyFromScreen(R.Left,R.Top,0,0, printscreen.Size);
        graphics.Dispose();
        return printscreen;

    }

My problem is that the source is with 125% and when I send the coordinates of mouse position to obtain the printscreen it goes to the "real" coordinates, this is without the Scale.

How to solve the problem?

  • My screen has the resolution of 1920*1080. But when I put in the right end the Control.Mouseposition Returns 1535 instead of 1920...

  • Zoom will always be set at 125%?

  • Not always. It can be changed. And in this case I wanted to make sure it would work anyway. If it was fixed, just multiply by 1.25

  • Just to clarify, what do you mean by the source is 125%? What you’re considering as this "source"?

  • I think it’s that Windows zoom, @Randrade. That’s right, Leandro?

  • @jbueno I also imagined this, but it wasn’t clear.

  • @Randrade your interpretation is correct. The source is 125%

  • @Leandrorodrigues Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, see [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.

Show 3 more comments

1 answer

3

In Windows Forms you can use Cursor.Position.

Out of it you will probably have to access the Windows API. A response in the OS teaches to do this.

[StructLayout(LayoutKind.Sequential)]
public struct Point {
    public int X;
    public int Y;

    public static implicit operator Point(Point point) {
        return new Point(point.X, point.T);
    }
}

[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition() {
    Point lpPoint;
    GetCursorPos(out lpPoint);
    //bool success = User32.GetCursorPos(out lpPoint);
    // if (!success)
    return lpPoint;
}

I put in the Github for future reference.

I think I could use the existing structure on . NET to receive the point.

  • I have also experienced it. But I have the same problem, mentioned in the above comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.