Coordinate Error using GetWindowRect in different DPI

a 夏天 提交于 2019-12-02 15:03:24

问题


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);


来源:https://stackoverflow.com/questions/32220480/coordinate-error-using-getwindowrect-in-different-dpi

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