Converting mouse position

拜拜、爱过 提交于 2019-12-11 18:57:02

问题


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:


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
}


来源:https://stackoverflow.com/questions/23968530/converting-mouse-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!