为什么“GetDeviceCaps”函数总是返回屏幕尺寸的一半?

Jim*_*Jim 2 c++ winapi c++20

我一直在尝试使用 <Windows.h> 的函数获取屏幕尺寸GetDeviceCaps(GetDC(NULL), HORZRES),但每当我运行代码时,它总是返回屏幕分辨率的一半。

有谁知道为什么我的电脑会发生这种情况?它在大多数其他显示器上运行良好。

我的屏幕分辨率是 (2736x1824) (surface pro)。

#include <Windows.h>
#include <iostream>
int main()
{
    HDC display = GetDC(NULL);
    const int x = GetDeviceCaps(display, HORZRES), y = GetDeviceCaps(display, VERTRES); //returns (1368, 912)
    std::cout << x << ", " << y << "\n";
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*ica 5

您的程序几乎肯定“遭受”了DPI 感知问题

在我的系统上运行您的代码会出现类似的问题;但是,添加对该SetThreadDpiAwarenessContext函数的调用可以解决该问题:

#include <Windows.h>
#include <iostream>
int main()
{
    SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_SYSTEM_AWARE); // This line fixes the issue.
    HDC display = GetDC(NULL);
    const int x = GetDeviceCaps(display, HORZRES), y = GetDeviceCaps(display, VERTRES); //returns (1368, 912)
    std::cout << x << ", " << y << "\n";
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果没有添加该调用,程序将显示“1536, 864”的输出。添加后,我看到(正确的)值:“1920, 1080”。

  • @АлексейНеудачин哪里说控制台应用程序无权访问“kernel32.dll”或“User32.dll”?甚至您的答案也使用 Windows.h 中声明的函数。 (3认同)
  • @АлексейНеудачин 嗯,我已经这样做很多年了......而且我发布的代码示例工作没有问题。此外,Stack Overflow 上有“许多”答案,它们在基于控制台的“int main()”应用程序中使用 DC 和其他“windows.h”内容。 (3认同)