简体   繁体   中英

How can I convert the mouse cursor coordinates when click on pictureBox are to the screen relative mouse cursor coordinates?

In my program I added this code so when I move my mouse all over the screen I will get the mouse cursor coordinates in real time:

Form1 Load:

private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
            t1.Interval = 50;
            t1.Tick += new EventHandler(timer1_Tick);
            t1.Enabled = true;;
        }

Then the method that get the mouse position:

public static Point GetMousePosition()
        {
            var position = System.Windows.Forms.Cursor.Position;
            return new Point(position.X, position.Y);
        }

Then the timer1 tick event:

private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = string.Format("X={0}, Y={1}", GetMousePosition().X, GetMousePosition().Y);
        }

Then I ran some application and moved the mouse over a specific location on the screen where the application window is and I found this coordinates:

358, 913

Now I have in my program a listBox with items each item present application screenshot. And if I click on the pictureBox for example in this case on the BATTLEFIELD 3 area I get the mouse cursor coordinates according to the pictureBox area.

屏幕截图

So I did:

    Point screenCoordinates;
    Point pictureBoxSnapCoordinates;
    private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
    {
        screenCoordinates = pictureBoxSnap.PointToScreen(e.Location);
        pictureBoxSnapCoordinates = e.Location;
    }

Now when I click in the pictureBox at the same location as I found the coordinates 358, 913 but on the pictureBox so the results are:

screenCoordinates 435, 724

pictureBoxSnapCoordinates 23,423

The screenCoordinates isn't the same coordinates as I found with the mouse move 358, 913 it's not even close. There is a big difference between 358,913 and 437,724

e.Location is relative to the Control's top left corner. If you want to use e.Location to get the screen coordinates, then you have to first do pictureBoxSnap.PointToScreen(Point.Empty); and then offset by the e.Location .

Also, Cursor.Position returns a Point object, so making a new Point(...) is point less.

I must add, if you are dealing with images, and you need to interact with mouse, and do any task related with offset, scroll, etc, I recommend you that library, it is open source and have a lot of examples and methods that will help you

https://github.com/cyotek/Cyotek.Windows.Forms.ImageBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM