Converting mouse position

2019-08-27 02:35发布

I need some help with Mouse position and screen resolution.

I have two applications running on two separate machines:

application1 (resolution: 1920 x 1200) captures the mouse location, and then it sends the location values to application2.

application2 (resolution: 1280 x 800) receives and sets the Cursor position based on those values.

This works just fine, the problem I'm having is, that application1 has a different screen resolution compare to application2, therefore the mouse location send from the application1 do not translate to the screen resolution and cursor position on application2.

Does anybody know how to convert these cursor location ( X, Y ) values into the correct values?, all of this assuming that the application2 form window is fully maximized of course, otherwise a similar value conversion will have to be done instead based on the Form window size.

This is how application1 captures the Mouse location:

    Point mouseLocation;
    public Form1()
    {
        InitializeComponent();
        this.MouseMove += new MouseEventHandler(Form1_MouseMove);
    }

    void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        mouseLocation = e.Location;
        // now we're send the "mouseLocation" values to the application2

    }

and this is how application2 sets the cursor position based on the values it received:

    public Form1()
    {
        InitializeComponent();


        // we bring the position values
        int x_value = int.Parse(position[0].ToString());
        int y_value = int.Parse(position[1].ToString());
        Cursor.Position = new Point(x_value, y_value);
    }

1条回答
聊天终结者
2楼-- · 2019-08-27 03:12

You can write a simple helper method like this:

private static Point Translate(Point point, Size from, Size to)
{
    return new Point((point.X * to.Width) / from.Width, (point.Y * to.Height) / from.Height);
}

private static void Main(string[] args)
{
    Size fromResolution = new Size(1920, 1200);//From resolution
    Size toResolution = new Size(1280, 800);//To resolution

    Console.WriteLine(Translate(new Point(100, 100), fromResolution, toResolution));
    //Prints 66,66
}
查看更多
登录 后发表回答