Coordinate Error using GetWindowRect in different

2020-05-06 03:23发布

问题:

I want to capture the coordinate of components in my MFC program.

Now I can perfectly complete this by using GetWindowRect. However, when I set my windows dpi to 150% (120 dpi), I get different coordinates from GetWindowRect.

Therefore, I survey some method to convert new coordinates to that in default dpi (96 dpi).

Finally, I found there was some error when I tried:

Rect.top = Rect.top * (DEFAULT_DPIY / CURRENT_DPIY);
Rect.left = Rect.left * (DEFAULT_DPIX / CURRENT_DPIX);

The converted value is very close, but not equal.

Is there any method to convert it without error ?

回答1:

Your program is subject to DPI virtualization. The right way to deal with this is to make your program high DPI aware but that may well involve more changes than you are prepared to attempt.

If being high DPI aware is not something you wish to tackle, then you can at least make your arithmetic better. Your code uses integer divide. But that's going to be inaccurate. In order to minimise that inaccuracy you should perform the division after the multiplication:

Rect.top = (Rect.top * DEFAULT_DPIY) / CURRENT_DPIY;
Rect.left = (Rect.left * DEFAULT_DPIX) / CURRENT_DPIX;

Of course, the parentheses could be omitted here without changing the meaning, but I think it's nice to be explicit about the ordering of the operations in this case.

Another option would be to use MulDiv:

Rect.top = MulDiv(Rect.top, DEFAULT_DPIY, CURRENT_DPIY);
Rect.left = MulDiv(Rect.left, DEFAULT_DPIX, CURRENT_DPIX);