QT調用Window系統API獲取屏幕分辯率及縮放比例

GetSystemMetrics()函數,獲取屏幕的分辯率,這個分辯表示的是當前顯示的分辨率。

通過設置標識符獲取相應的值 ,例如,獲取屏幕的寬度和高度

int width = GetSystemMetrics(SM_CXSCREEN); //屏幕寬度

int height = GetSystemMetrics(SM_CYSCREEN); //屏幕高度

 

GetDeviceCaps 獲取指定設備的性能參數該方法將所取得的硬件設備信息保存到一個D3DCAPS9結構中

GetDeviceCaps 與GetSystemMetrics的區別的,GetDeviceCaps是設備的物理屬性,而GetSystemMetrics是可調節的,

下面以2K的顯示器(1920 X 1080)爲例

把顯示器的顯示比例調成125%

這個時候,width  = 1536,  而GetDeviceCaps獲取的寬度爲1920,代碼實現如下

int nScreenWidth = ::GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = ::GetSystemMetrics(SM_CYSCREEN);
qDebug() << "nScreenWidth=========" << nScreenWidth << "nScreenHeight====" << nScreenHeight;

HWND hwd = ::GetDesktopWindow();
HDC hdc = ::GetDC(hwd);
int width = GetDeviceCaps(hdc, DESKTOPHORZRES);
int height = GetDeviceCaps(hdc, DESKTOPVERTRES);

double dWidth = (double)width;
double dScreenWidth = (double)nScreenWidth;
double scale = dWidth / dScreenWidth;
qDebug() << "width=========" << width << "=nScreenWidth==" << nScreenWidth << "height====" << height << "==scale===" << scale;
qDebug() << "dWidth=========" << dWidth << "=dScreenWidth==" << dScreenWidth << "==scale===" << scale;
    
  
QApplication a(argc, argv);

運行結果

使用的時候在.cpp文件中要添加這幾個頭文件

#include <Windows.h>//這個一定要添加,不然會報"No Target Architecture" 錯誤
#include <WinUser.h>
#include <wingdi.h>

 

.pro文件中添加

win32 {
    msvc:LIBS += User32.lib
    msvc:LIBS += gdi32.lib
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章