Signed-off-by: Yuhang Zhao <2546789017@qq.com>
This commit is contained in:
Yuhang Zhao 2020-03-31 21:40:59 +08:00
parent 973435e5df
commit 00573bdf58
4 changed files with 284 additions and 182 deletions

View File

@ -5,7 +5,7 @@ CONFIG += c++17 strict_c++ utf8_source warn_on
win32 { win32 {
CONFIG -= embed_manifest_exe CONFIG -= embed_manifest_exe
RC_FILE = resources.rc RC_FILE = resources.rc
LIBS += -luser32 -lgdi32 -ldwmapi -luxtheme -ld2d1 LIBS += -luser32 -lshell32 -lgdi32 -ldwmapi -luxtheme -ld2d1
} }
DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII
HEADERS += winnativeeventfilter.h HEADERS += winnativeeventfilter.h

View File

@ -11,7 +11,7 @@ int main(int argc, char *argv[]) {
QApplication application(argc, argv); QApplication application(argc, argv);
WinNativeEventFilter::setup(); WinNativeEventFilter::install();
QWidget widget; QWidget widget;
widget.show(); widget.show();

View File

@ -7,6 +7,7 @@
#include <QWindow> #include <QWindow>
#include <d2d1.h> #include <d2d1.h>
#include <dwmapi.h> #include <dwmapi.h>
#include <shellapi.h>
#include <uxtheme.h> #include <uxtheme.h>
#include <windowsx.h> #include <windowsx.h>
@ -33,20 +34,7 @@
namespace { namespace {
QScopedPointer<WinNativeEventFilter> instance; QScopedPointer<WinNativeEventFilter> instance;
QVector<HWND> m_framelessWindows;
bool isWindowTopLevel(HWND handle) {
if (!handle) {
return false;
}
const auto wid = reinterpret_cast<WId>(handle);
const auto topLevelWindows = QGuiApplication::topLevelWindows();
for (auto &&window : qAsConst(topLevelWindows)) {
if (window->handle() && (window->winId() == wid)) {
return true;
}
}
return false;
}
} // namespace } // namespace
@ -69,6 +57,14 @@ WinNativeEventFilter::WinNativeEventFilter() {
m_GetSystemMetricsForDpi = reinterpret_cast<lpGetSystemMetricsForDpi>( m_GetSystemMetricsForDpi = reinterpret_cast<lpGetSystemMetricsForDpi>(
user32Lib.resolve("GetSystemMetricsForDpi")); user32Lib.resolve("GetSystemMetricsForDpi"));
} }
// Windows 10, version 1709 (10.0.16299)
if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0,
16299)) {
m_SetWindowCompositionAttribute =
reinterpret_cast<lpSetWindowCompositionAttribute>(
user32Lib.resolve("SetWindowCompositionAttribute"));
}
// Windows 10, version 1803 (10.0.17134) // Windows 10, version 1803 (10.0.17134)
if (QOperatingSystemVersion::current() >= if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0, QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0,
@ -78,21 +74,58 @@ WinNativeEventFilter::WinNativeEventFilter() {
} }
} }
WinNativeEventFilter::~WinNativeEventFilter() { WinNativeEventFilter::~WinNativeEventFilter() = default;
if (!m_data.isEmpty()) {
for (auto data : m_data) {
delete data;
}
}
}
void WinNativeEventFilter::setup() { void WinNativeEventFilter::install() {
if (instance.isNull()) { if (instance.isNull()) {
instance.reset(new WinNativeEventFilter); instance.reset(new WinNativeEventFilter);
qApp->installNativeEventFilter(instance.data()); qApp->installNativeEventFilter(instance.data());
} }
} }
void WinNativeEventFilter::uninstall() {
if (!instance.isNull()) {
qApp->removeNativeEventFilter(instance.data());
instance.reset();
}
if (!m_framelessWindows.isEmpty()) {
for (auto &&window : qAsConst(m_framelessWindows)) {
refreshWindow(window);
}
m_framelessWindows.clear();
}
}
QVector<HWND> WinNativeEventFilter::framelessWindows() {
return m_framelessWindows;
}
void WinNativeEventFilter::setFramelessWindows(QVector<HWND> windows) {
if (!windows.isEmpty() && (windows != m_framelessWindows)) {
m_framelessWindows = windows;
install();
}
}
void WinNativeEventFilter::addFramelessWindow(HWND window) {
if (window && !m_framelessWindows.contains(window)) {
m_framelessWindows.append(window);
install();
}
}
void WinNativeEventFilter::removeFramelessWindow(HWND window) {
if (window && m_framelessWindows.contains(window)) {
m_framelessWindows.removeAll(window);
}
}
void WinNativeEventFilter::clearFramelessWindows() {
if (!m_framelessWindows.isEmpty()) {
m_framelessWindows.clear();
}
}
UINT WinNativeEventFilter::windowDpi(HWND handle) const { UINT WinNativeEventFilter::windowDpi(HWND handle) const {
return getDpiForWindow(handle); return getDpiForWindow(handle);
} }
@ -116,6 +149,14 @@ int WinNativeEventFilter::titlebarHeight(HWND handle) const {
getSystemMetricsForWindow(handle, SM_CYCAPTION); getSystemMetricsForWindow(handle, SM_CYCAPTION);
} }
void WinNativeEventFilter::refreshWindow(HWND handle) {
if (handle) {
SetWindowPos(handle, nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOSIZE |
SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
}
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType, bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
void *message, qintptr *result) void *message, qintptr *result)
@ -131,31 +172,44 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
// Anyway, we should skip it in this case. // Anyway, we should skip it in this case.
return false; return false;
} }
if (!isWindowTopLevel(msg->hwnd)) { if (m_framelessWindows.isEmpty()) {
// Only top level windows can be frameless. bool isTopLevel = false;
// QWidgets with Qt::WA_NativeWindow enabled will make them become top
// level windows even if they are not. Try if
// Qt::WA_DontCreateNativeAncestors helps.
const auto topLevelWindows = QGuiApplication::topLevelWindows();
for (auto &&window : qAsConst(topLevelWindows)) {
if (window->handle() &&
(msg->hwnd == reinterpret_cast<HWND>(window->winId()))) {
isTopLevel = true;
break;
}
}
if (!isTopLevel) {
return false; return false;
} }
if (!m_data.contains(msg->hwnd)) { } else if (!m_framelessWindows.contains(msg->hwnd)) {
LPWINDOW _data = new WINDOW; return false;
_data->hwnd = msg->hwnd; }
m_data.insert(msg->hwnd, _data); if (!m_windowData.contains(msg->hwnd)) {
init(_data); // We have to record every window's state.
m_windowData.insert(msg->hwnd, qMakePair(FALSE, FALSE));
init(msg->hwnd);
} }
const auto data = m_data.value(msg->hwnd);
switch (msg->message) { switch (msg->message) {
case WM_NCCREATE: { case WM_NCCREATE: {
// Work-around a long-existing Windows bug. // Work-around a long-existing Windows bug.
const auto userData = const auto userData =
reinterpret_cast<LPCREATESTRUCTW>(msg->lParam)->lpCreateParams; reinterpret_cast<LPCREATESTRUCTW>(msg->lParam)->lpCreateParams;
SetWindowLongPtrW(data->hwnd, GWLP_USERDATA, SetWindowLongPtrW(msg->hwnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(userData)); reinterpret_cast<LONG_PTR>(userData));
break; break;
} }
case WM_NCCALCSIZE: { case WM_NCCALCSIZE: {
if (static_cast<BOOL>(msg->wParam)) { if (static_cast<BOOL>(msg->wParam)) {
if (IsMaximized(data->hwnd)) { if (IsMaximized(msg->hwnd)) {
const HMONITOR monitor = const HMONITOR monitor =
MonitorFromWindow(data->hwnd, MONITOR_DEFAULTTONEAREST); MonitorFromWindow(msg->hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor) { if (monitor) {
MONITORINFO monitorInfo; MONITORINFO monitorInfo;
SecureZeroMemory(&monitorInfo, sizeof(monitorInfo)); SecureZeroMemory(&monitorInfo, sizeof(monitorInfo));
@ -164,6 +218,44 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
auto &params = auto &params =
*reinterpret_cast<LPNCCALCSIZE_PARAMS>(msg->lParam); *reinterpret_cast<LPNCCALCSIZE_PARAMS>(msg->lParam);
params.rgrc[0] = monitorInfo.rcWork; params.rgrc[0] = monitorInfo.rcWork;
// If the client rectangle is the same as the monitor's
// rectangle, the shell assumes that the window has gone
// fullscreen, so it removes the topmost attribute from any
// auto-hide appbars, making them inaccessible. To avoid
// this, reduce the size of the client area by one pixel on
// a certain edge. The edge is chosen based on which side of
// the monitor is likely to contain an auto-hide appbar, so
// the missing client area is covered by it.
if (EqualRect(&params.rgrc[0], &monitorInfo.rcMonitor)) {
APPBARDATA abd;
SecureZeroMemory(&abd, sizeof(abd));
abd.cbSize = sizeof(abd);
const UINT taskbarState =
SHAppBarMessage(ABM_GETSTATE, &abd);
if (taskbarState & ABS_AUTOHIDE) {
int edge = -1;
abd.hWnd = FindWindowW(L"Shell_TrayWnd", nullptr);
if (abd.hWnd) {
const HMONITOR taskbarMonitor =
MonitorFromWindow(abd.hWnd,
MONITOR_DEFAULTTONEAREST);
if (taskbarMonitor &&
(taskbarMonitor == monitor)) {
SHAppBarMessage(ABM_GETTASKBARPOS, &abd);
edge = abd.uEdge;
}
}
if (edge == ABE_BOTTOM) {
params.rgrc[0].bottom--;
} else if (edge == ABE_LEFT) {
params.rgrc[0].left++;
} else if (edge == ABE_TOP) {
params.rgrc[0].top++;
} else if (edge == ABE_RIGHT) {
params.rgrc[0].right--;
}
}
}
} }
} }
// This line removes the window frame (including the titlebar). // This line removes the window frame (including the titlebar).
@ -178,7 +270,7 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
case WM_DWMCOMPOSITIONCHANGED: { case WM_DWMCOMPOSITIONCHANGED: {
// Bring the frame shadow back through DWM. // Bring the frame shadow back through DWM.
// Don't paint the shadow manually using QPainter or QGraphicsEffect. // Don't paint the shadow manually using QPainter or QGraphicsEffect.
handleDwmCompositionChanged(data); handleDwmCompositionChanged(msg->hwnd);
*result = 0; *result = 0;
return true; return true;
} }
@ -191,7 +283,7 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
return true; return true;
} }
case WM_NCPAINT: { case WM_NCPAINT: {
if (data->compositionEnabled) { if (m_windowData.value(msg->hwnd).first) {
break; break;
} else { } else {
// Only block WM_NCPAINT when composition is disabled. If it's // Only block WM_NCPAINT when composition is disabled. If it's
@ -204,21 +296,23 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
case WM_NCACTIVATE: { case WM_NCACTIVATE: {
// DefWindowProc won't repaint the window border if lParam (normally // DefWindowProc won't repaint the window border if lParam (normally
// a HRGN) is -1. // a HRGN) is -1.
*result = DefWindowProcW(data->hwnd, msg->message, msg->wParam, -1); *result = DefWindowProcW(msg->hwnd, msg->message, msg->wParam, -1);
return true; return true;
} }
case WM_NCHITTEST: { case WM_NCHITTEST: {
const auto getHTResult = [this, msg, data]() -> LRESULT { const auto getHTResult = [this](HWND _hWnd, LPARAM _lParam) -> LRESULT {
const LONG ww = data->width; RECT clientRect = {0, 0, 0, 0};
const LONG wh = data->height; GetClientRect(_hWnd, &clientRect);
POINT mouse = {LONG(GET_X_LPARAM(msg->lParam)), const LONG ww = clientRect.right;
LONG(GET_Y_LPARAM(msg->lParam))}; const LONG wh = clientRect.bottom;
ScreenToClient(data->hwnd, &mouse); POINT mouse = {LONG(GET_X_LPARAM(_lParam)),
LONG(GET_Y_LPARAM(_lParam))};
ScreenToClient(_hWnd, &mouse);
// These values are DPI-aware. // These values are DPI-aware.
const LONG bw = borderWidth(data->hwnd); const LONG bw = borderWidth(_hWnd);
const LONG bh = borderHeight(data->hwnd); const LONG bh = borderHeight(_hWnd);
const LONG tbh = titlebarHeight(data->hwnd); const LONG tbh = titlebarHeight(_hWnd);
if (IsMaximized(data->hwnd)) { if (IsMaximized(_hWnd)) {
if (mouse.y < tbh) { if (mouse.y < tbh) {
return HTCAPTION; return HTCAPTION;
} }
@ -253,13 +347,13 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
} }
return HTCLIENT; return HTCLIENT;
}; };
*result = getHTResult(); *result = getHTResult(msg->hwnd, msg->lParam);
return true; return true;
} }
case WM_GETMINMAXINFO: { case WM_GETMINMAXINFO: {
// Don't cover the taskbar when maximized. // Don't cover the taskbar when maximized.
const HMONITOR monitor = const HMONITOR monitor =
MonitorFromWindow(data->hwnd, MONITOR_DEFAULTTONEAREST); MonitorFromWindow(msg->hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor) { if (monitor) {
MONITORINFO monitorInfo; MONITORINFO monitorInfo;
SecureZeroMemory(&monitorInfo, sizeof(monitorInfo)); SecureZeroMemory(&monitorInfo, sizeof(monitorInfo));
@ -286,60 +380,26 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
// composition and theming are disabled. These messages don't paint // composition and theming are disabled. These messages don't paint
// when composition is enabled and blocking WM_NCUAHDRAWCAPTION should // when composition is enabled and blocking WM_NCUAHDRAWCAPTION should
// be enough to prevent painting when theming is enabled. // be enough to prevent painting when theming is enabled.
if (!data->compositionEnabled && !data->themeEnabled) { if (!m_windowData.value(msg->hwnd).first &&
const LONG_PTR oldStyle = GetWindowLongPtrW(data->hwnd, GWL_STYLE); !m_windowData.value(msg->hwnd).second) {
const LONG_PTR oldStyle = GetWindowLongPtrW(msg->hwnd, GWL_STYLE);
// Prevent Windows from drawing the default title bar by temporarily // Prevent Windows from drawing the default title bar by temporarily
// toggling the WS_VISIBLE style. // toggling the WS_VISIBLE style.
SetWindowLongPtrW(data->hwnd, GWL_STYLE, oldStyle & ~WS_VISIBLE); SetWindowLongPtrW(msg->hwnd, GWL_STYLE, oldStyle & ~WS_VISIBLE);
const LRESULT ret = DefWindowProcW(data->hwnd, msg->message, const LRESULT ret = DefWindowProcW(msg->hwnd, msg->message,
msg->wParam, msg->lParam); msg->wParam, msg->lParam);
SetWindowLongPtrW(data->hwnd, GWL_STYLE, oldStyle); SetWindowLongPtrW(msg->hwnd, GWL_STYLE, oldStyle);
*result = ret; *result = ret;
return true; return true;
} }
break; break;
} }
case WM_THEMECHANGED: { case WM_THEMECHANGED: {
handleThemeChanged(data); handleThemeChanged(msg->hwnd);
break; break;
} }
case WM_WINDOWPOSCHANGED: { case WM_WINDOWPOSCHANGED: {
RECT client; InvalidateRect(msg->hwnd, nullptr, TRUE);
GetClientRect(data->hwnd, &client);
const UINT old_width = data->width;
const UINT old_height = data->height;
data->width = client.right;
data->height = client.bottom;
const bool client_changed =
(data->width != old_width) || (data->height != old_height);
if (client_changed ||
(reinterpret_cast<const LPWINDOWPOS>(msg->lParam)->flags &
SWP_FRAMECHANGED)) {
updateRegion(data);
}
if (client_changed) {
// Invalidate the changed parts of the rectangle drawn in WM_PAINT.
RECT rect;
if (data->width > old_width) {
rect = {LONG(old_width - 1), 0, LONG(old_width),
LONG(old_height)};
} else {
rect = {LONG(data->width - 1), 0, LONG(data->width),
LONG(data->height)};
}
if (data->height > old_height) {
rect = {0, LONG(old_height - 1), LONG(old_width),
LONG(old_height)};
} else {
rect = {0, LONG(data->height - 1), LONG(data->width),
LONG(data->height)};
}
InvalidateRect(data->hwnd, &rect, TRUE);
}
*result = 0;
// Don't return true here because return true means we'll take over
// the whole event from Qt and thus it will block Qt's paint events and
// the window will not update itself anymore in the end.
break; break;
} }
default: default:
@ -348,116 +408,116 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
return false; return false;
} }
void WinNativeEventFilter::init(LPWINDOW data) { void WinNativeEventFilter::init(HWND handle) {
// Make sure our window is a normal application window, we'll remove the // Make sure our window is a normal application window, we'll remove the
// window frame later in Win32 events, don't use WS_POPUP to do this. // window frame later in Win32 events, don't use WS_POPUP to do this.
SetWindowLongPtrW(data->hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW); SetWindowLongPtrW(handle, GWL_STYLE,
SetWindowLongPtrW(data->hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_LAYERED); WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetWindowLongPtrW(handle, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_LAYERED);
// Make the window a layered window so the legacy GDI API can be used to // Make the window a layered window so the legacy GDI API can be used to
// draw to it without messing up the area on top of the DWM frame. Note: // draw to it without messing up the area on top of the DWM frame. Note:
// This is not necessary if other drawing APIs are used, eg. GDI+, OpenGL, // This is not necessary if other drawing APIs are used, eg. GDI+, OpenGL,
// Direct2D, Direct3D, DirectComposition, etc. // Direct2D, Direct3D, DirectComposition, etc.
SetLayeredWindowAttributes(data->hwnd, RGB(255, 0, 255), 0, LWA_COLORKEY); SetLayeredWindowAttributes(handle, RGB(255, 0, 255), 0, LWA_COLORKEY);
// Make sure our window has the frame shadow. // Make sure our window has the frame shadow.
handleDwmCompositionChanged(data); handleDwmCompositionChanged(handle);
handleThemeChanged(data); handleThemeChanged(handle);
// Tell the window to redraw itself.
SetWindowPos(data->hwnd, nullptr, 0, 0, 0, 0,
SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
// For debug purposes. // For debug purposes.
qDebug().noquote() << "Window handle:" << data->hwnd; qDebug().noquote() << "Window handle:" << handle;
qDebug().noquote() << "Window DPI:" << windowDpi(data->hwnd) qDebug().noquote() << "Window DPI:" << windowDpi(handle)
<< "Window DPR:" << windowDpr(data->hwnd); << "Window DPR:" << windowDpr(handle);
qDebug().noquote() << "Window border width:" << borderWidth(data->hwnd) qDebug().noquote() << "Window border width:" << borderWidth(handle)
<< "Window border height:" << borderHeight(data->hwnd) << "Window border height:" << borderHeight(handle)
<< "Window titlebar height:" << "Window titlebar height:" << titlebarHeight(handle);
<< titlebarHeight(data->hwnd);
} }
void WinNativeEventFilter::updateRegion(LPWINDOW data) { void WinNativeEventFilter::handleDwmCompositionChanged(HWND handle) {
const RECT old_rgn = data->region;
const RECT null_rgn = {0, 0, 0, 0};
if (IsMaximized(data->hwnd)) {
WINDOWINFO wi;
SecureZeroMemory(&wi, sizeof(wi));
wi.cbSize = sizeof(wi);
GetWindowInfo(data->hwnd, &wi);
// For maximized windows, a region is needed to cut off the
// non-client borders that hang over the edge of the screen.
data->region.left = wi.rcClient.left - wi.rcWindow.left;
data->region.top = wi.rcClient.top - wi.rcWindow.top;
data->region.right = wi.rcClient.right - wi.rcWindow.left;
data->region.bottom = wi.rcClient.bottom - wi.rcWindow.top;
} else if (!data->compositionEnabled) {
// For ordinary themed windows when composition is disabled, a
// region is needed to remove the rounded top corners. Make it as
// large as possible to avoid having to change it when the window is
// resized.
data->region.left = 0;
data->region.top = 0;
data->region.right = 32767;
data->region.bottom = 32767;
} else {
// Don't mess with the region when composition is enabled and the
// window is not maximized, otherwise it will lose its shadow.
data->region = null_rgn;
}
// Avoid unnecessarily updating the region to avoid unnecessary redraws.
if (EqualRect(&data->region, &old_rgn)) {
return;
}
// Treat empty regions as NULL regions.
if (EqualRect(&data->region, &null_rgn)) {
SetWindowRgn(data->hwnd, nullptr, TRUE);
} else {
SetWindowRgn(data->hwnd, CreateRectRgnIndirect(&data->region), TRUE);
}
}
void WinNativeEventFilter::handleDwmCompositionChanged(LPWINDOW data) {
BOOL enabled = FALSE; BOOL enabled = FALSE;
DwmIsCompositionEnabled(&enabled); DwmIsCompositionEnabled(&enabled);
data->compositionEnabled = enabled; const BOOL theme = m_windowData.value(handle).second;
WTA_OPTIONS options; m_windowData[handle] = qMakePair(enabled, theme);
options.dwMask = WTNCA_NODRAWCAPTION | WTNCA_NODRAWICON;
// We should not draw the frame shadow if DWM composition is disabled, in // We should not draw the frame shadow if DWM composition is disabled, in
// other words, a window should not have frame shadow when Windows Aero is // other words, a window should not have frame shadow when Windows Aero is
// not enabled. // not enabled.
// Note that, start from Win8, the DWM composition is always enabled and // Note that, start from Win8, the DWM composition is always enabled and
// can't be disabled. // can't be disabled.
if (enabled) { if (enabled) {
options.dwFlags = WTNCA_NODRAWCAPTION | WTNCA_NODRAWICON;
// The frame shadow is drawn on the non-client area and thus we have to // The frame shadow is drawn on the non-client area and thus we have to
// make sure the non-client area rendering is enabled first. // make sure the non-client area rendering is enabled first.
const DWMNCRENDERINGPOLICY ncrp = DWMNCRP_ENABLED; const DWMNCRENDERINGPOLICY ncrp = DWMNCRP_ENABLED;
DwmSetWindowAttribute(data->hwnd, DWMWA_NCRENDERING_POLICY, &ncrp, DwmSetWindowAttribute(handle, DWMWA_NCRENDERING_POLICY, &ncrp,
sizeof(ncrp)); sizeof(ncrp));
// Negative margins have special meaning to // Negative margins have special meaning to
// DwmExtendFrameIntoClientArea. Negative margins create the "sheet of // DwmExtendFrameIntoClientArea. Negative margins create the "sheet of
// glass" effect, where the client area is rendered as a solid surface // glass" effect, where the client area is rendered as a solid surface
// with no window border. // with no window border.
const MARGINS margins = {-1, -1, -1, -1}; const MARGINS margins = {-1, -1, -1, -1};
DwmExtendFrameIntoClientArea(data->hwnd, &margins); DwmExtendFrameIntoClientArea(handle, &margins);
} }
SetWindowThemeAttribute(data->hwnd, WTA_NONCLIENT, &options, // handleBlurForWindow(handle, enabled);
sizeof(options)); refreshWindow(handle);
updateRegion(data);
} }
void WinNativeEventFilter::handleThemeChanged(LPWINDOW data) { void WinNativeEventFilter::handleThemeChanged(HWND handle) {
data->themeEnabled = IsThemeActive(); const BOOL dwm = m_windowData.value(handle).first;
m_windowData[handle] = qMakePair(dwm, IsThemeActive());
}
void WinNativeEventFilter::handleBlurForWindow(HWND handle,
BOOL compositionEnabled) {
if (!handle) {
return;
}
if (m_SetWindowCompositionAttribute) {
ACCENT_POLICY accent;
accent.AccentFlags = 0;
accent.GradientColor = 0;
accent.AnimationId = 0;
WINDOWCOMPOSITIONATTRIBDATA data;
data.dwAttribute = WCA_ACCENT_POLICY;
data.pvAttribute = &accent;
data.cbAttribute = sizeof(accent);
if (compositionEnabled) {
// Windows 10, version 1709 (10.0.16299)
if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0,
16299)) {
// Acrylic
accent.AccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND;
} else if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion::Windows10) {
// Blur
accent.AccentState = ACCENT_ENABLE_BLURBEHIND;
} else if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion::Windows8) {
// Transparent gradient color
accent.AccentState = ACCENT_ENABLE_TRANSPARENTGRADIENT;
}
} else {
accent.AccentState = ACCENT_DISABLED;
}
m_SetWindowCompositionAttribute(handle, &data);
} else if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion::Windows7) {
// Windows Aero
DWM_BLURBEHIND dwmbb;
dwmbb.dwFlags = DWM_BB_ENABLE;
dwmbb.fEnable = compositionEnabled;
dwmbb.hRgnBlur = nullptr;
dwmbb.fTransitionOnMaximized = FALSE;
DwmEnableBlurBehindWindow(handle, &dwmbb);
}
} }
UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const { UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const {
const auto getScreenDpi = [this]() -> UINT { const auto getScreenDpi = [](UINT defaultValue) -> UINT {
// Available since Windows 7. // Available since Windows 7.
ID2D1Factory *m_pDirect2dFactory = nullptr; ID2D1Factory *m_pDirect2dFactory = nullptr;
if (SUCCEEDED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, if (SUCCEEDED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,
&m_pDirect2dFactory)) && &m_pDirect2dFactory)) &&
m_pDirect2dFactory) { m_pDirect2dFactory) {
m_pDirect2dFactory->ReloadSystemMetrics(); m_pDirect2dFactory->ReloadSystemMetrics();
FLOAT dpiX = m_defaultDPI, dpiY = m_defaultDPI; FLOAT dpiX = defaultValue, dpiY = defaultValue;
m_pDirect2dFactory->GetDesktopDpi(&dpiX, &dpiY); m_pDirect2dFactory->GetDesktopDpi(&dpiX, &dpiY);
// The values of *dpiX and *dpiY are identical. // The values of *dpiX and *dpiY are identical.
return dpiX; return dpiX;
@ -472,7 +532,7 @@ UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const {
// silence a compiler warning. // silence a compiler warning.
return dpiX == dpiY ? dpiX : dpiY; return dpiX == dpiY ? dpiX : dpiY;
} }
return m_defaultDPI; return defaultValue;
}; };
if (!handle) { if (!handle) {
if (m_GetSystemDpiForProcess) { if (m_GetSystemDpiForProcess) {
@ -480,7 +540,7 @@ UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const {
} else if (m_GetDpiForSystem) { } else if (m_GetDpiForSystem) {
return m_GetDpiForSystem(); return m_GetDpiForSystem();
} else { } else {
return getScreenDpi(); return getScreenDpi(m_defaultDPI);
} }
} }
if (m_GetDpiForWindow) { if (m_GetDpiForWindow) {
@ -493,7 +553,7 @@ UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const {
// The values of *dpiX and *dpiY are identical. // The values of *dpiX and *dpiY are identical.
return dpiX; return dpiX;
} }
return getScreenDpi(); return getScreenDpi(m_defaultDPI);
} }
qreal WinNativeEventFilter::getDprForWindow(HWND handle) const { qreal WinNativeEventFilter::getDprForWindow(HWND handle) const {

View File

@ -2,30 +2,45 @@
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
#include <QHash> #include <QHash>
#include <QPair>
#include <QVector>
#include <qt_windows.h> #include <qt_windows.h>
class WinNativeEventFilter : public QAbstractNativeEventFilter { class WinNativeEventFilter : public QAbstractNativeEventFilter {
Q_DISABLE_COPY_MOVE(WinNativeEventFilter) Q_DISABLE_COPY_MOVE(WinNativeEventFilter)
public: public:
typedef struct tagWINDOW {
HWND hwnd = nullptr;
UINT width = 0, height = 0;
RECT region = {0, 0, 0, 0};
BOOL compositionEnabled = FALSE, themeEnabled = FALSE;
} WINDOW, *LPWINDOW;
explicit WinNativeEventFilter(); explicit WinNativeEventFilter();
~WinNativeEventFilter() override; ~WinNativeEventFilter() override;
static void setup(); // Make all top level windows become frameless, unconditionally.
static void install();
// Make all top level windows back to normal.
static void uninstall();
// Frameless windows handle list
static QVector<HWND> framelessWindows();
static void setFramelessWindows(QVector<HWND> windows);
// Make the given window become frameless.
static void addFramelessWindow(HWND window);
static void removeFramelessWindow(HWND window);
static void clearFramelessWindows();
// Dots-Per-Inch of the given window.
UINT windowDpi(HWND handle) const; UINT windowDpi(HWND handle) const;
// Device-Pixel-Ratio of the given window.
qreal windowDpr(HWND handle) const; qreal windowDpr(HWND handle) const;
// DPI-aware border width of the given window.
int borderWidth(HWND handle) const; int borderWidth(HWND handle) const;
// DPI-aware border height of the given window.
int borderHeight(HWND handle) const; int borderHeight(HWND handle) const;
// DPI-aware titlebar height of the given window.
int titlebarHeight(HWND handle) const; int titlebarHeight(HWND handle) const;
// Let the given window redraw itself.
static void refreshWindow(HWND handle);
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
bool nativeEventFilter(const QByteArray &eventType, void *message, bool nativeEventFilter(const QByteArray &eventType, void *message,
qintptr *result) override; qintptr *result) override;
@ -35,26 +50,50 @@ public:
#endif #endif
private: private:
void init(LPWINDOW data); void init(HWND handle);
void updateRegion(LPWINDOW data); void handleDwmCompositionChanged(HWND handle);
void handleDwmCompositionChanged(LPWINDOW data); void handleThemeChanged(HWND handle);
void handleThemeChanged(LPWINDOW data); void handleBlurForWindow(HWND handle, BOOL compositionEnabled);
UINT getDpiForWindow(HWND handle) const; UINT getDpiForWindow(HWND handle) const;
qreal getDprForWindow(HWND handle) const; qreal getDprForWindow(HWND handle) const;
int getSystemMetricsForWindow(HWND handle, int index) const; int getSystemMetricsForWindow(HWND handle, int index) const;
private: private:
// GetDpiForMonitor is only available from Windows 8.1 so we will load it at using WINDOWCOMPOSITIONATTRIB = enum _WINDOWCOMPOSITIONATTRIB {
// run-time instead of linking to it directly. WCA_ACCENT_POLICY = 19
using MONITOR_DPI_TYPE = enum MONITOR_DPI_TYPE { };
using WINDOWCOMPOSITIONATTRIBDATA = struct _WINDOWCOMPOSITIONATTRIBDATA {
DWORD dwAttribute;
PVOID pvAttribute;
DWORD cbAttribute;
};
using ACCENT_STATE = enum _ACCENT_STATE {
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,
ACCENT_INVALID_STATE = 5
};
using ACCENT_POLICY = struct _ACCENT_POLICY {
ACCENT_STATE AccentState;
DWORD AccentFlags;
DWORD GradientColor;
DWORD AnimationId;
};
using MONITOR_DPI_TYPE = enum _MONITOR_DPI_TYPE {
MDT_EFFECTIVE_DPI = 0, MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1, MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2, MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI MDT_DEFAULT = MDT_EFFECTIVE_DPI
}; };
QHash<HWND, LPWINDOW> m_data;
// Window handle, DwmComposition, Theme
QHash<HWND, QPair<BOOL, BOOL>> m_windowData;
const UINT m_defaultDPI = 96; const UINT m_defaultDPI = 96;
const qreal m_defaultDPR = 1.0; const qreal m_defaultDPR = 1.0;
using lpGetSystemDpiForProcess = UINT(WINAPI *)(HANDLE); using lpGetSystemDpiForProcess = UINT(WINAPI *)(HANDLE);
lpGetSystemDpiForProcess m_GetSystemDpiForProcess = nullptr; lpGetSystemDpiForProcess m_GetSystemDpiForProcess = nullptr;
using lpGetDpiForWindow = UINT(WINAPI *)(HWND); using lpGetDpiForWindow = UINT(WINAPI *)(HWND);
@ -66,4 +105,7 @@ private:
using lpGetDpiForMonitor = HRESULT(WINAPI *)(HMONITOR, MONITOR_DPI_TYPE, using lpGetDpiForMonitor = HRESULT(WINAPI *)(HMONITOR, MONITOR_DPI_TYPE,
UINT *, UINT *); UINT *, UINT *);
lpGetDpiForMonitor m_GetDpiForMonitor = nullptr; lpGetDpiForMonitor m_GetDpiForMonitor = nullptr;
using lpSetWindowCompositionAttribute =
BOOL(WINAPI *)(HWND, WINDOWCOMPOSITIONATTRIBDATA *);
lpSetWindowCompositionAttribute m_SetWindowCompositionAttribute = nullptr;
}; };