windows获取屏幕显示比例 读取注册表法

static int GetDesktopScale()
{
    int desktop_scale = 100;
    HINSTANCE hUser32 = LoadLibrary(L"user32.dll");
    if (hUser32)
    {
        typedef BOOL(WINAPI* LPSetProcessDPIAware)(void);
        LPSetProcessDPIAware pSetProcessDPIAware = (LPSetProcessDPIAware)GetProcAddress(hUser32, "SetProcessDPIAware");
        if (pSetProcessDPIAware)
        {
            //去掉系统的放大,不应该调用
            //pSetProcessDPIAware();
            std::wstring value;
            HKEY hKEY;
            long ret = 0;
            ret = ::RegOpenKeyEx(HKEY_CURRENT_USER, L"CONTROL PANEL\\DESKTOP\\WINDOWMETRICS", 0, KEY_ALL_ACCESS, &hKEY);
            if (ret != ERROR_SUCCESS)  //该键值不存在
            {
                ::RegCloseKey(hKEY);
            }
            else
            {
                DWORD datasize = 4;
                int data;
                DWORD dType = REG_DWORD;
                ret = ::RegQueryValueEx(hKEY, L"AppliedDPI", NULL, &dType, (LPBYTE)&data, &datasize);
                if (ret != ERROR_SUCCESS)
                {
                    ::RegCloseKey(hKEY);
                }
                else
                {
                    if (data > 0)
                    {
                        desktop_scale = data * 100 / 96;
                    }
                    ::RegCloseKey(hKEY);
                }
            }
        }
        FreeLibrary(hUser32);
    }
    return desktop_scale;
}

在我的电脑上测试过。更改显示比例后,需要注销才能生效。估计是通过注销来写入注册表的。

posted on 2017-08-22 16:10  zyz913614263  阅读(1402)  评论(0编辑  收藏  举报

导航