How to get the current DPI of a system in MFC Appl

2020-06-21 10:25发布

问题:

I have an existing MFC application which runs fine in default DPI ( 96 dpi) in Windows 7. But when I increase the DPI by 150 % the UI gets distorted. I have fixed issues using scroll bars at certain level and referred to msdn article. I am wondering how can I get the current DPI of a system using MFC code so that set the height and widht of a dialog.

Please suggest!!

回答1:

First you need to get the device context for your screen. This is easy, just call GetDC, like this:

HDC screen = GetDC(0);

Then you ask for the device capabilities of that device context. In your case, you need the pixels along the X- and Y-axis per inch:

int dpiX = GetDeviceCaps (screen, LOGPIXELSX);
int dpiY = GetDeviceCaps (screen, LOGPIXELSY);

(see http://msdn.microsoft.com/en-us/library/dd144877(v=vs.85).aspx for more information about GetDeviceCaps).

Finally, release the device context again:

ReleaseDC (0, screen);


回答2:

Following on from Patrick's answer, you might also like to read this Microsoft tutorial on writing high DPI aware user interface:

http://msdn.microsoft.com/en-us/library/dd464659.aspx



回答3:

The below code snippet gave me the correct DPI in Win7

ID2D1Factory* m_pDirect2dFactory;
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pDirect2dFactory);
FLOAT dpiX, dpiY;
m_pDirect2dFactory->GetDesktopDpi( &dpiX, &dpiY );