Signed-off-by: Yuhang Zhao <2546789017@qq.com>
This commit is contained in:
Yuhang Zhao 2020-04-01 23:09:48 +08:00
parent a6af30ce2a
commit 9fdabbc33f
4 changed files with 178 additions and 73 deletions

View File

@ -6,7 +6,8 @@ win32 {
CONFIG -= embed_manifest_exe CONFIG -= embed_manifest_exe
RC_FILE = resources.rc RC_FILE = resources.rc
LIBS += -luser32 -lshell32 -lgdi32 -ldwmapi -luxtheme -ld2d1 LIBS += -luser32 -lshell32 -lgdi32 -ldwmapi -luxtheme -ld2d1
HEADERS += winnativeeventfilter.h
SOURCES += winnativeeventfilter.cpp
} }
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 SOURCES += main.cpp
SOURCES += main.cpp winnativeeventfilter.cpp

View File

@ -11,9 +11,11 @@ int main(int argc, char *argv[]) {
QApplication application(argc, argv); QApplication application(argc, argv);
WinNativeEventFilter::install();
QWidget widget; QWidget widget;
WinNativeEventFilter::WINDOWDATA data;
data.blurEnabled = TRUE;
WinNativeEventFilter::addFramelessWindow(
reinterpret_cast<HWND>(widget.winId()), &data);
widget.show(); widget.show();
return QApplication::exec(); return QApplication::exec();

View File

@ -44,7 +44,8 @@ QVector<HWND> m_framelessWindows;
} // namespace } // namespace
WinNativeEventFilter::WinNativeEventFilter() { WinNativeEventFilter::WinNativeEventFilter() {
QLibrary user32Lib(QString::fromUtf8("User32")), shcoreLib(QString::fromUtf8("SHCore")); QLibrary user32Lib(QString::fromUtf8("User32")),
shcoreLib(QString::fromUtf8("SHCore"));
if (QOperatingSystemVersion::current() >= if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion::Windows7) { QOperatingSystemVersion::Windows7) {
m_SetWindowCompositionAttribute = m_SetWindowCompositionAttribute =
@ -109,9 +110,23 @@ void WinNativeEventFilter::setFramelessWindows(QVector<HWND> windows) {
} }
} }
void WinNativeEventFilter::addFramelessWindow(HWND window) { void WinNativeEventFilter::addFramelessWindow(HWND window, WINDOWDATA *data) {
if (window && !m_framelessWindows.contains(window)) { if (window && !m_framelessWindows.contains(window)) {
m_framelessWindows.append(window); m_framelessWindows.append(window);
if (data) {
const auto userData = reinterpret_cast<LPWINDOW>(
GetWindowLongPtrW(window, GWLP_USERDATA));
if (userData) {
userData->windowData = *data;
} else {
LPWINDOW _data = new WINDOW;
_data->hWnd = window;
_data->windowData = *data;
SetWindowLongPtrW(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(_data));
}
refreshWindow(window);
}
install(); install();
} }
} }
@ -196,14 +211,20 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
return false; return false;
} }
LPWINDOW data = nullptr; LPWINDOW data = nullptr;
const auto userData = reinterpret_cast<LPWINDOW>(GetWindowLongPtrW(msg->hwnd, GWLP_USERDATA)); const auto userData =
reinterpret_cast<LPWINDOW>(GetWindowLongPtrW(msg->hwnd, GWLP_USERDATA));
if (userData) { if (userData) {
data = userData; data = userData;
} else { } else {
init(msg->hwnd); LPWINDOW _data = new WINDOW;
data = reinterpret_cast<LPWINDOW>(GetWindowLongPtrW(msg->hwnd, GWLP_USERDATA)); _data->hWnd = msg->hwnd;
SetWindowLongPtrW(msg->hwnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(_data));
data = _data;
}
if (!data->inited) {
init(data);
} }
Q_ASSERT(data);
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.
@ -214,6 +235,7 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
break; break;
} }
case WM_NCCALCSIZE: { case WM_NCCALCSIZE: {
// MSDN: No special handling is needed when wParam is FALSE.
if (static_cast<BOOL>(msg->wParam)) { if (static_cast<BOOL>(msg->wParam)) {
if (IsMaximized(msg->hwnd)) { if (IsMaximized(msg->hwnd)) {
const HMONITOR monitor = const HMONITOR monitor =
@ -266,13 +288,11 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
} }
} }
} }
// This line removes the window frame (including the titlebar).
// But the frame shadow is lost at the same time. We'll bring it
// back later.
*result = WVR_REDRAW;
} else {
*result = 0;
} }
// This line removes the window frame (including the titlebar).
// But the frame shadow is lost at the same time. We'll bring it
// back later.
*result = 0;
return true; return true;
} }
case WM_DWMCOMPOSITIONCHANGED: { case WM_DWMCOMPOSITIONCHANGED: {
@ -308,54 +328,84 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
return true; return true;
} }
case WM_NCHITTEST: { case WM_NCHITTEST: {
const auto getHTResult = [this](HWND _hWnd, LPARAM _lParam) -> LRESULT { const auto getHTResult = [this](HWND _hWnd, LPARAM _lParam,
RECT clientRect = {0, 0, 0, 0}; LPWINDOW _data) -> LRESULT {
GetClientRect(_hWnd, &clientRect); const auto isInIgnoreArea = [](int x, int y,
const LONG ww = clientRect.right; QVector<QRect> areas) -> bool {
const LONG wh = clientRect.bottom; if (areas.isEmpty()) {
POINT mouse = {LONG(GET_X_LPARAM(_lParam)), return false;
LONG(GET_Y_LPARAM(_lParam))}; }
ScreenToClient(_hWnd, &mouse); for (auto &&area : qAsConst(areas)) {
// These values are DPI-aware. if (area.contains(x, y, true)) {
const LONG bw = borderWidth(_hWnd); return true;
const LONG bh = borderHeight(_hWnd); }
const LONG tbh = titlebarHeight(_hWnd); }
return false;
};
RECT winRect = {0, 0, 0, 0};
GetWindowRect(_hWnd, &winRect);
const int mx = GET_X_LPARAM(_lParam);
const int my = GET_Y_LPARAM(_lParam);
const int borderWidth_userDefined = _data->windowData.borderWidth;
const int borderHeight_userDefined = _data->windowData.borderHeight;
const int titlebarHeight_userDefined =
_data->windowData.titlebarHeight;
// These values should be DPI-aware.
const int bw = borderWidth_userDefined > 0 ? borderWidth_userDefined
: borderWidth(_hWnd);
const int bh = borderHeight_userDefined > 0
? borderHeight_userDefined
: borderHeight(_hWnd);
const int tbh = titlebarHeight_userDefined > 0
? titlebarHeight_userDefined
: titlebarHeight(_hWnd);
const bool isTitlebar = (my > winRect.top) &&
(my < (winRect.top + tbh)) &&
!isInIgnoreArea(mx, my, _data->windowData.ignoreAreas);
if (IsMaximized(_hWnd)) { if (IsMaximized(_hWnd)) {
if (mouse.y < tbh) { if (isTitlebar) {
return HTCAPTION; return HTCAPTION;
} }
return HTCLIENT; return HTCLIENT;
} }
if (mouse.y < bh) { const bool isTop =
if (mouse.x < bw) { (my > (winRect.top - bh)) && (my < (winRect.top + bh));
const bool isBottom =
(my > (winRect.bottom - bh)) && (my < (winRect.bottom + bh));
const bool isLeft =
(mx > (winRect.left - bw)) && (mx < (winRect.left + bw));
const bool isRight =
(mx > (winRect.right - bw)) && (mx < (winRect.right + bw));
if (isTop) {
if (isLeft) {
return HTTOPLEFT; return HTTOPLEFT;
} }
if (mouse.x > (ww - bw)) { if (isRight) {
return HTTOPRIGHT; return HTTOPRIGHT;
} }
return HTTOP; return HTTOP;
} }
if (mouse.y > (wh - bh)) { if (isBottom) {
if (mouse.x < bw) { if (isLeft) {
return HTBOTTOMLEFT; return HTBOTTOMLEFT;
} }
if (mouse.x > (ww - bw)) { if (isRight) {
return HTBOTTOMRIGHT; return HTBOTTOMRIGHT;
} }
return HTBOTTOM; return HTBOTTOM;
} }
if (mouse.x < bw) { if (isLeft) {
return HTLEFT; return HTLEFT;
} }
if (mouse.x > (ww - bw)) { if (isRight) {
return HTRIGHT; return HTRIGHT;
} }
if (mouse.y < tbh) { if (isTitlebar) {
return HTCAPTION; return HTCAPTION;
} }
return HTCLIENT; return HTCLIENT;
}; };
*result = getHTResult(msg->hwnd, msg->lParam); *result = getHTResult(msg->hwnd, msg->lParam, data);
return true; return true;
} }
case WM_GETMINMAXINFO: { case WM_GETMINMAXINFO: {
@ -388,8 +438,7 @@ 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->dwmCompositionEnabled && if (!data->dwmCompositionEnabled && !data->themeEnabled) {
!data->themeEnabled) {
const LONG_PTR oldStyle = GetWindowLongPtrW(msg->hwnd, GWL_STYLE); 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.
@ -413,8 +462,10 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
case WM_DPICHANGED: { case WM_DPICHANGED: {
const auto dpiX = LOWORD(msg->wParam); const auto dpiX = LOWORD(msg->wParam);
const auto dpiY = HIWORD(msg->wParam); const auto dpiY = HIWORD(msg->wParam);
// dpiX and dpiY are identical. // dpiX and dpiY are identical. Just to silence a compiler warning.
qDebug().noquote() << "Window DPI changed:" << (dpiX == dpiY ? dpiY : dpiX); const auto dpi = dpiX == dpiY ? dpiY : dpiX;
qDebug().noquote() << "Window DPI changed: new DPI -->" << dpi
<< "new DPR -->" << qreal(dpi) / qreal(m_defaultDPI);
// FIXME: Temporary solution. // FIXME: Temporary solution.
refreshWindow(msg->hwnd); refreshWindow(msg->hwnd);
break; break;
@ -425,30 +476,28 @@ bool WinNativeEventFilter::nativeEventFilter(const QByteArray &eventType,
return false; return false;
} }
void WinNativeEventFilter::init(HWND handle) { void WinNativeEventFilter::init(LPWINDOW data) {
LPWINDOW data = new WINDOW; data->inited = TRUE;
data->hWnd = handle;
SetWindowLongPtrW(handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(data));
// 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(handle, GWL_STYLE, SetWindowLongPtrW(data->hWnd, GWL_STYLE,
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetWindowLongPtrW(handle, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_LAYERED); SetWindowLongPtrW(data->hWnd, GWL_EXSTYLE, WS_EX_APPWINDOW | WS_EX_LAYERED);
// Make the window a layered window so the legacy GDI API can be used to if (!data->windowData.blurEnabled) {
// draw to it without messing up the area on top of the DWM frame. Note: SetLayeredWindowAttributes(data->hWnd, RGB(255, 0, 255), 0,
// This is not necessary if other drawing APIs are used, eg. GDI+, OpenGL, LWA_COLORKEY);
// Direct2D, Direct3D, DirectComposition, etc. }
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(data);
handleThemeChanged(data); handleThemeChanged(data);
// For debug purposes. // For debug purposes.
qDebug().noquote() << "Window handle:" << handle; qDebug().noquote() << "Window handle:" << data->hWnd;
qDebug().noquote() << "Window DPI:" << windowDpi(handle) qDebug().noquote() << "Window DPI:" << windowDpi(data->hWnd)
<< "Window DPR:" << windowDpr(handle); << "Window DPR:" << windowDpr(data->hWnd);
qDebug().noquote() << "Window border width:" << borderWidth(handle) qDebug().noquote() << "Window border width:" << borderWidth(data->hWnd)
<< "Window border height:" << borderHeight(handle) << "Window border height:" << borderHeight(data->hWnd)
<< "Window titlebar height:" << titlebarHeight(handle); << "Window titlebar height:"
<< titlebarHeight(data->hWnd);
} }
void WinNativeEventFilter::handleDwmCompositionChanged(LPWINDOW data) { void WinNativeEventFilter::handleDwmCompositionChanged(LPWINDOW data) {
@ -473,7 +522,7 @@ void WinNativeEventFilter::handleDwmCompositionChanged(LPWINDOW data) {
const MARGINS margins = {-1, -1, -1, -1}; const MARGINS margins = {-1, -1, -1, -1};
DwmExtendFrameIntoClientArea(data->hWnd, &margins); DwmExtendFrameIntoClientArea(data->hWnd, &margins);
} }
// handleBlurForWindow(data); handleBlurForWindow(data);
refreshWindow(data->hWnd); refreshWindow(data->hWnd);
} }
@ -482,37 +531,49 @@ void WinNativeEventFilter::handleThemeChanged(LPWINDOW data) {
} }
void WinNativeEventFilter::handleBlurForWindow(LPWINDOW data) { void WinNativeEventFilter::handleBlurForWindow(LPWINDOW data) {
if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows7) { if (QOperatingSystemVersion::current() <
QOperatingSystemVersion::Windows7) {
return; return;
} }
// We prefer using DWM blur on Windows 7 because it has better appearance. // We prefer using DWM blur on Windows 7 because it has better appearance.
// It's supported on Windows Vista as well actually, but Qt has drop it, so we won't do it for Vista. // It's supported on Windows Vista as well actually, but Qt has drop it, so
if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8) { // we won't do it for Vista.
const BOOL enableBlur =
data->dwmCompositionEnabled && data->windowData.blurEnabled;
if (QOperatingSystemVersion::current() <
QOperatingSystemVersion::Windows8) {
// Windows Aero // Windows Aero
DWM_BLURBEHIND dwmbb; DWM_BLURBEHIND dwmbb;
dwmbb.dwFlags = DWM_BB_ENABLE; dwmbb.dwFlags = DWM_BB_ENABLE;
dwmbb.fEnable = data->dwmCompositionEnabled; dwmbb.fEnable = enableBlur;
dwmbb.hRgnBlur = nullptr; dwmbb.hRgnBlur = nullptr;
dwmbb.fTransitionOnMaximized = FALSE; dwmbb.fTransitionOnMaximized = FALSE;
DwmEnableBlurBehindWindow(data->hWnd, &dwmbb); DwmEnableBlurBehindWindow(data->hWnd, &dwmbb);
} else if (m_SetWindowCompositionAttribute) { } else if (m_SetWindowCompositionAttribute) {
ACCENT_POLICY accentPolicy; ACCENT_POLICY accentPolicy;
accentPolicy.AccentFlags = 0; accentPolicy.AccentFlags = 0;
// GradientColor only has effect when using with acrylic, so we can set it to zero in most cases. // GradientColor only has effect when using with acrylic, so we can set
// It's an AGBR unsigned int, for example, use 0xCC000000 for dark blur behind background. // it to zero in most cases. It's an AGBR unsigned int, for example, use
// 0xCC000000 for dark blur behind background.
accentPolicy.GradientColor = 0; accentPolicy.GradientColor = 0;
accentPolicy.AnimationId = 0; accentPolicy.AnimationId = 0;
WINDOWCOMPOSITIONATTRIBDATA attribData; WINDOWCOMPOSITIONATTRIBDATA attribData;
attribData.dwAttribute = WCA_ACCENT_POLICY; attribData.dwAttribute = WCA_ACCENT_POLICY;
attribData.pvAttribute = &accentPolicy; attribData.pvAttribute = &accentPolicy;
attribData.cbAttribute = sizeof(accentPolicy); attribData.cbAttribute = sizeof(accentPolicy);
if (data->dwmCompositionEnabled) { if (enableBlur) {
// Windows 10, version 1709 (10.0.16299) // Windows 10, version 1709 (10.0.16299)
if (QOperatingSystemVersion::current() >= if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0, QOperatingSystemVersion(QOperatingSystemVersion::Windows, 10, 0,
16299)) { 16299)) {
// Acrylic (Will also blur but is completely different with Windows Aero) // Acrylic (Will also blur but is completely different with
// Windows Aero)
#if 0
// FIXME: Why causes strange problems?
accentPolicy.AccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND; accentPolicy.AccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND;
#else
accentPolicy.AccentState = ACCENT_ENABLE_BLURBEHIND;
#endif
} else if (QOperatingSystemVersion::current() >= } else if (QOperatingSystemVersion::current() >=
QOperatingSystemVersion::Windows10) { QOperatingSystemVersion::Windows10) {
// Blur (Something like Windows Aero in Windows 7) // Blur (Something like Windows Aero in Windows 7)
@ -550,7 +611,7 @@ UINT WinNativeEventFilter::getDpiForWindow(HWND handle) const {
ReleaseDC(nullptr, hdc); ReleaseDC(nullptr, hdc);
// The values of dpiX and dpiY are identical actually, just to // The values of dpiX and dpiY are identical actually, just to
// silence a compiler warning. // silence a compiler warning.
return dpiX == dpiY ? dpiX : dpiY; return dpiX == dpiY ? dpiY : dpiX;
} }
return defaultValue; return defaultValue;
}; };
@ -589,3 +650,33 @@ int WinNativeEventFilter::getSystemMetricsForWindow(HWND handle,
return GetSystemMetrics(index) * getDprForWindow(handle); return GetSystemMetrics(index) * getDprForWindow(handle);
} }
} }
void WinNativeEventFilter::setWindowData(HWND window, WINDOWDATA *data) {
if (window && data) {
const auto userData = reinterpret_cast<LPWINDOW>(
GetWindowLongPtrW(window, GWLP_USERDATA));
if (userData) {
userData->windowData = *data;
} else {
LPWINDOW _data = new WINDOW;
_data->hWnd = window;
_data->windowData = *data;
SetWindowLongPtrW(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(_data));
}
refreshWindow(window);
}
}
WinNativeEventFilter::WINDOWDATA *
WinNativeEventFilter::windowData(HWND window) {
WINDOWDATA *data = nullptr;
if (window) {
const auto userData = reinterpret_cast<LPWINDOW>(
GetWindowLongPtrW(window, GWLP_USERDATA));
if (userData) {
data = &userData->windowData;
}
}
return data;
}

View File

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
#include <QRect>
#include <QVector> #include <QVector>
#include <qt_windows.h> #include <qt_windows.h>
@ -8,9 +9,16 @@ class WinNativeEventFilter : public QAbstractNativeEventFilter {
Q_DISABLE_COPY_MOVE(WinNativeEventFilter) Q_DISABLE_COPY_MOVE(WinNativeEventFilter)
public: public:
using WINDOWDATA = struct _WINDOWDATA {
BOOL blurEnabled = FALSE;
int borderWidth = -1, borderHeight = -1, titlebarHeight = -1;
QVector<QRect> ignoreAreas;
};
typedef struct tagWINDOW { typedef struct tagWINDOW {
HWND hWnd = nullptr; HWND hWnd = nullptr;
BOOL dwmCompositionEnabled = FALSE, themeEnabled = FALSE; BOOL dwmCompositionEnabled = FALSE, themeEnabled = FALSE,
inited = FALSE;
WINDOWDATA windowData;
} WINDOW, *LPWINDOW; } WINDOW, *LPWINDOW;
explicit WinNativeEventFilter(); explicit WinNativeEventFilter();
@ -25,10 +33,13 @@ public:
static QVector<HWND> framelessWindows(); static QVector<HWND> framelessWindows();
static void setFramelessWindows(QVector<HWND> windows); static void setFramelessWindows(QVector<HWND> windows);
// Make the given window become frameless. // Make the given window become frameless.
static void addFramelessWindow(HWND window); static void addFramelessWindow(HWND window, WINDOWDATA *data = nullptr);
static void removeFramelessWindow(HWND window); static void removeFramelessWindow(HWND window);
static void clearFramelessWindows(); static void clearFramelessWindows();
static void setWindowData(HWND window, WINDOWDATA *data);
static WINDOWDATA *windowData(HWND window);
// Dots-Per-Inch of the given window. // Dots-Per-Inch of the given window.
UINT windowDpi(HWND handle) const; UINT windowDpi(HWND handle) const;
// Device-Pixel-Ratio of the given window. // Device-Pixel-Ratio of the given window.
@ -53,7 +64,7 @@ public:
#endif #endif
private: private:
void init(HWND handle); void init(LPWINDOW data);
void handleDwmCompositionChanged(LPWINDOW data); void handleDwmCompositionChanged(LPWINDOW data);
void handleThemeChanged(LPWINDOW data); void handleThemeChanged(LPWINDOW data);
void handleBlurForWindow(LPWINDOW data); void handleBlurForWindow(LPWINDOW data);