跳到正文

科技·工程

小程序 - 实时键速显示器

ExFish约 112 分钟
原文
文章信息与版本

文章信息

发布
2026年8月10日
收录
2026年8月11日
更新
2026年8月18日
篇幅
约 112 分钟

版本

  1. v1当前

使用 GPT5.6 制作的轻量级程序。使用 -std=c++17 -O2 -mwindows -lgdi32 -luser32 -lshell32 编译即可。

C++
#define WINVER 0x0600
#define _WIN32_WINNT 0x0600

#define UNICODE
#define _UNICODE
#define NOMINMAX

#include <windows.h>
// TDM-GCC / Dev-C++ 链接参数:-mwindows -lgdi32 -luser32 -lshell32
#include <windowsx.h>
#include <shellapi.h>

#ifndef GET_X_LPARAM
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#endif

#ifndef GET_Y_LPARAM
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
#endif

#include <vector>
#include <algorithm>
#include <cmath>
#include <cwchar>

using namespace std;

// ============================================================
// Timer
// ============================================================

ULONGLONG NowMs()
{
    static LARGE_INTEGER freq = {};
    static bool init = false;

    if(!init)
    {
        QueryPerformanceFrequency(&freq);
        init = true;
    }

    LARGE_INTEGER now;
    QueryPerformanceCounter(&now);

    return (ULONGLONG)(now.QuadPart * 1000LL / freq.QuadPart);
}

// ============================================================
// Base layout / IDs
// ============================================================

const int BASE_WINDOW_WIDTH  = 340;
const int BASE_WINDOW_HEIGHT = 136;
const int BASE_SHADOW_MARGIN = 18;
const int BASE_CORNER_RADIUS = 20;
const int WINDOW_MARGIN      = 18;

const UINT TIMER_REFRESH = 1;
const UINT WM_TRAYICON = WM_APP + 10;
const UINT TRAY_ICON_ID = 1;

const int MENU_RESET          = 1001;
const int MENU_BOTTOM_RIGHT   = 1002;
const int MENU_HIDE_TO_TRAY   = 1003;
const int MENU_SHOW           = 1004;
const int MENU_ABOUT          = 1005;

// 透明度:0% = 完全不透明,100% = 完全透明
const int MENU_TRANSPARENCY_0   = 1010;
const int MENU_TRANSPARENCY_10  = 1011;
const int MENU_TRANSPARENCY_20  = 1012;
const int MENU_TRANSPARENCY_40  = 1013;
const int MENU_TRANSPARENCY_60  = 1014;
const int MENU_TRANSPARENCY_80  = 1015;
const int MENU_TRANSPARENCY_90  = 1016;
const int MENU_TRANSPARENCY_100 = 1017;

const int MENU_THEME_DARK        = 1030;
const int MENU_THEME_LIGHT       = 1031;
const int MENU_THEME_BLUE_WHITE  = 1032;
const int MENU_THEME_GREEN_BLACK = 1033;
const int MENU_THEME_CUSTOM      = 1034;

const int MENU_CUSTOM_HUE_MINUS = 1040;
const int MENU_CUSTOM_HUE_PLUS  = 1041;
const int MENU_CUSTOM_SAT_MINUS = 1042;
const int MENU_CUSTOM_SAT_PLUS  = 1043;
const int MENU_CUSTOM_LIT_MINUS = 1044;
const int MENU_CUSTOM_LIT_PLUS  = 1045;
const int MENU_CUSTOM_RESET     = 1046;

const int MENU_SCALE_75  = 1050;
const int MENU_SCALE_90  = 1051;
const int MENU_SCALE_100 = 1052;
const int MENU_SCALE_110 = 1053;
const int MENU_SCALE_125 = 1054;
const int MENU_SCALE_150 = 1055;
const int MENU_SCALE_175 = 1056;

const int MENU_EXIT = 1099;

const int HOTKEY_EXIT              = 2001;
const int HOTKEY_RESET             = 2002;
const int HOTKEY_LEFT              = 2010;
const int HOTKEY_RIGHT             = 2011;
const int HOTKEY_UP                = 2012;
const int HOTKEY_DOWN              = 2013;
const int HOTKEY_TRANSPARENCY_UP   = 2020;
const int HOTKEY_TRANSPARENCY_DOWN = 2021;
const int HOTKEY_SCALE_UP          = 2030;
const int HOTKEY_SCALE_DOWN        = 2031;

// ============================================================
// Global state
// ============================================================

HWND  g_hwnd = NULL;
HHOOK g_keyboardHook = NULL;

vector<ULONGLONG> g_events;
bool g_keyDown[256] = {};

// 默认完全不透明,避免启动后“看起来仍透明”。
int g_transparencyPercent = 0;
int g_scalePercent = 100;

enum ThemeMode
{
    THEME_DARK,
    THEME_LIGHT,
    THEME_BLUE_WHITE,
    THEME_GREEN_BLACK,
    THEME_CUSTOM
};

ThemeMode g_theme = THEME_DARK;

// 自定义主题采用 HSL,避免依赖 comdlg32 / 新 SDK。
double g_customHue = 210.0;
double g_customSat = 72.0;
double g_customLit = 56.0;

HFONT g_titleFont = NULL;
HFONT g_speedFont = NULL;
HFONT g_unitFont  = NULL;
HFONT g_smallFont = NULL;
HFONT g_closeFont = NULL;

bool g_dragging = false;
bool g_closeHover = false;
bool g_closePressed = false;

POINT g_dragStartMouse = {};
POINT g_dragStartWindow = {};

NOTIFYICONDATAW g_tray = {};

// ============================================================
// Scale helpers
// ============================================================

int S(int value)
{
    return MulDiv(value, g_scalePercent, 100);
}

int GetShadowMargin()
{
    int v = S(BASE_SHADOW_MARGIN);
    return v < 8 ? 8 : v;
}

int GetContentWidth()
{
    return S(BASE_WINDOW_WIDTH);
}

int GetContentHeight()
{
    return S(BASE_WINDOW_HEIGHT);
}

int GetWindowWidth()
{
    return GetContentWidth() + GetShadowMargin() * 2;
}

int GetWindowHeight()
{
    return GetContentHeight() + GetShadowMargin() * 2;
}

int LX(int logicalX)
{
    return GetShadowMargin() + S(logicalX);
}

int LY(int logicalY)
{
    return GetShadowMargin() + S(logicalY);
}

// ============================================================
// Theme / color helpers
// ============================================================

struct Palette
{
    COLORREF bgTop;
    COLORREF bgBottom;
    COLORREF title;
    COLORREF primary;
    COLORREF secondary;
    COLORREF muted;
    COLORREF track;
    COLORREF accent;
    COLORREF border;
    COLORREF closeHover;
    COLORREF closeText;
    COLORREF shadow;
};

int ClampByteInt(int v)
{
    if(v < 0) return 0;
    if(v > 255) return 255;
    return v;
}

double ClampDouble(double v, double lo, double hi)
{
    if(v < lo) return lo;
    if(v > hi) return hi;
    return v;
}

double WrapHue(double h)
{
    while(h < 0.0) h += 360.0;
    while(h >= 360.0) h -= 360.0;
    return h;
}

double HueToRgb(double p, double q, double t)
{
    if(t < 0.0) t += 1.0;
    if(t > 1.0) t -= 1.0;

    if(t < 1.0 / 6.0)
        return p + (q - p) * 6.0 * t;

    if(t < 1.0 / 2.0)
        return q;

    if(t < 2.0 / 3.0)
        return p + (q - p) * (2.0 / 3.0 - t) * 6.0;

    return p;
}

COLORREF HslToRgb(double hDeg, double sPct, double lPct)
{
    double h = WrapHue(hDeg) / 360.0;
    double s = ClampDouble(sPct, 0.0, 100.0) / 100.0;
    double l = ClampDouble(lPct, 0.0, 100.0) / 100.0;

    double r, g, b;

    if(s <= 0.0001)
    {
        r = g = b = l;
    }
    else
    {
        double q = l < 0.5
            ? l * (1.0 + s)
            : l + s - l * s;

        double p = 2.0 * l - q;

        r = HueToRgb(p, q, h + 1.0 / 3.0);
        g = HueToRgb(p, q, h);
        b = HueToRgb(p, q, h - 1.0 / 3.0);
    }

    return RGB(
        ClampByteInt((int)(r * 255.0 + 0.5)),
        ClampByteInt((int)(g * 255.0 + 0.5)),
        ClampByteInt((int)(b * 255.0 + 0.5))
    );
}

Palette GetPalette()
{
    Palette p;

    if(g_theme == THEME_LIGHT)
    {
        p.bgTop      = RGB(250, 252, 255);
        p.bgBottom   = RGB(237, 243, 249);
        p.title      = RGB(52, 63, 79);
        p.primary    = RGB(31, 42, 57);
        p.secondary  = RGB(88, 103, 123);
        p.muted      = RGB(122, 135, 151);
        p.track      = RGB(212, 222, 233);
        p.accent     = RGB(69, 145, 244);
        p.border     = RGB(198, 211, 225);
        p.closeHover = RGB(226, 86, 103);
        p.closeText  = RGB(255, 255, 255);
        p.shadow     = RGB(45, 58, 76);
        return p;
    }

    if(g_theme == THEME_BLUE_WHITE)
    {
        p.bgTop      = RGB(241, 247, 255);
        p.bgBottom   = RGB(223, 237, 253);
        p.title      = RGB(39, 67, 104);
        p.primary    = RGB(27, 54, 88);
        p.secondary  = RGB(79, 111, 151);
        p.muted      = RGB(106, 133, 167);
        p.track      = RGB(197, 218, 242);
        p.accent     = RGB(52, 126, 238);
        p.border     = RGB(177, 205, 238);
        p.closeHover = RGB(225, 90, 105);
        p.closeText  = RGB(255, 255, 255);
        p.shadow     = RGB(42, 72, 111);
        return p;
    }

    if(g_theme == THEME_GREEN_BLACK)
    {
        p.bgTop      = RGB(20, 32, 28);
        p.bgBottom   = RGB(12, 22, 19);
        p.title      = RGB(218, 236, 227);
        p.primary    = RGB(244, 251, 247);
        p.secondary  = RGB(139, 171, 156);
        p.muted      = RGB(101, 134, 119);
        p.track      = RGB(38, 56, 48);
        p.accent     = RGB(77, 220, 149);
        p.border     = RGB(50, 72, 62);
        p.closeHover = RGB(179, 67, 80);
        p.closeText  = RGB(255, 255, 255);
        p.shadow     = RGB(0, 0, 0);
        return p;
    }

    if(g_theme == THEME_CUSTOM)
    {
        p.bgTop      = HslToRgb(g_customHue, 30.0, 17.0);
        p.bgBottom   = HslToRgb(g_customHue, 34.0, 11.0);
        p.title      = HslToRgb(g_customHue, 28.0, 90.0);
        p.primary    = HslToRgb(g_customHue, 18.0, 98.0);
        p.secondary  = HslToRgb(g_customHue, 26.0, 70.0);
        p.muted      = HslToRgb(g_customHue, 20.0, 54.0);
        p.track      = HslToRgb(g_customHue, 25.0, 24.0);
        p.accent     = HslToRgb(g_customHue, g_customSat, g_customLit);
        p.border     = HslToRgb(g_customHue, 24.0, 30.0);
        p.closeHover = HslToRgb(350.0, 62.0, 50.0);
        p.closeText  = RGB(255, 255, 255);
        p.shadow     = HslToRgb(g_customHue, 35.0, 5.0);
        return p;
    }

    // 深色:不是纯黑,而是偏蓝灰的夜间色。
    p.bgTop      = RGB(29, 33, 45);
    p.bgBottom   = RGB(20, 24, 34);
    p.title      = RGB(229, 233, 242);
    p.primary    = RGB(249, 251, 255);
    p.secondary  = RGB(154, 165, 184);
    p.muted      = RGB(111, 123, 143);
    p.track      = RGB(49, 56, 70);
    p.accent     = RGB(103, 218, 166);
    p.border     = RGB(61, 69, 86);
    p.closeHover = RGB(184, 67, 82);
    p.closeText  = RGB(255, 255, 255);
    p.shadow     = RGB(0, 0, 0);
    return p;
}

void SetTheme(ThemeMode theme)
{
    g_theme = theme;

    if(g_hwnd)
        InvalidateRect(g_hwnd, NULL, FALSE);
}

void AdjustCustomHue(double delta)
{
    g_customHue = WrapHue(g_customHue + delta);
    SetTheme(THEME_CUSTOM);
}

void AdjustCustomSaturation(double delta)
{
    g_customSat = ClampDouble(g_customSat + delta, 10.0, 100.0);
    SetTheme(THEME_CUSTOM);
}

void AdjustCustomLightness(double delta)
{
    g_customLit = ClampDouble(g_customLit + delta, 28.0, 76.0);
    SetTheme(THEME_CUSTOM);
}

void ResetCustomTheme()
{
    g_customHue = 210.0;
    g_customSat = 72.0;
    g_customLit = 56.0;
    SetTheme(THEME_CUSTOM);
}

// ============================================================
// Statistics
// ============================================================

void ResetStatistics()
{
    g_events.clear();

    if(g_hwnd)
        InvalidateRect(g_hwnd, NULL, FALSE);
}

void AddKey()
{
    g_events.push_back(NowMs());
}

void UndoKey()
{
    if(!g_events.empty())
        g_events.pop_back();
}

long long GetRecentCount(ULONGLONG now)
{
    if(g_events.empty())
        return 0;

    ULONGLONG cutoff = now >= 60000 ? now - 60000 : 0;

    vector<ULONGLONG>::iterator it = lower_bound(
        g_events.begin(),
        g_events.end(),
        cutoff
    );

    return (long long)(g_events.end() - it);
}

long long GetCurrentCPM()
{
    // 固定 60 秒滚动窗口。
    // 启动不足 60 秒时,不再把 1~几秒的数据外推到整分钟,
    // 因而不会出现刚打几下就显示数百 CPM 的“飙高”。
    return GetRecentCount(NowMs());
}

// ============================================================
// Window position
// ============================================================

void ClampWindowPosition(int &x, int &y)
{
    RECT workArea;
    SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0);

    int w = GetWindowWidth();
    int h = GetWindowHeight();

    if(x < workArea.left) x = workArea.left;
    if(y < workArea.top)  y = workArea.top;

    if(x + w > workArea.right)
        x = workArea.right - w;

    if(y + h > workArea.bottom)
        y = workArea.bottom - h;
}

void PutWindowAtBottomRight(HWND hwnd)
{
    RECT workArea;
    SystemParametersInfoW(SPI_GETWORKAREA, 0, &workArea, 0);

    int w = GetWindowWidth();
    int h = GetWindowHeight();

    int x = workArea.right - w - WINDOW_MARGIN;
    int y = workArea.bottom - h - WINDOW_MARGIN;

    SetWindowPos(
        hwnd,
        HWND_TOPMOST,
        x,
        y,
        w,
        h,
        SWP_NOACTIVATE
    );
}

void MoveWindowBy(int dx, int dy)
{
    if(!g_hwnd)
        return;

    RECT rc;
    GetWindowRect(g_hwnd, &rc);

    int x = rc.left + dx;
    int y = rc.top + dy;

    ClampWindowPosition(x, y);

    SetWindowPos(
        g_hwnd,
        HWND_TOPMOST,
        x,
        y,
        0,
        0,
        SWP_NOSIZE | SWP_NOACTIVATE
    );
}

// ============================================================
// Transparency
// ============================================================

void SetTransparencyPercent(int percent)
{
    if(percent < 0) percent = 0;
    if(percent > 100) percent = 100;

    g_transparencyPercent = percent;

    if(g_hwnd)
        InvalidateRect(g_hwnd, NULL, FALSE);
}

void ChangeTransparency(int delta)
{
    SetTransparencyPercent(g_transparencyPercent + delta);
}

// ============================================================
// Fonts
// ============================================================

void DeleteFonts()
{
    if(g_titleFont) DeleteObject(g_titleFont);
    if(g_speedFont) DeleteObject(g_speedFont);
    if(g_unitFont)  DeleteObject(g_unitFont);
    if(g_smallFont) DeleteObject(g_smallFont);
    if(g_closeFont) DeleteObject(g_closeFont);

    g_titleFont = NULL;
    g_speedFont = NULL;
    g_unitFont  = NULL;
    g_smallFont = NULL;
    g_closeFont = NULL;
}

void CreateFonts()
{
    DeleteFonts();

    g_titleFont = CreateFontW(
        -S(16), 0, 0, 0, 600, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
        L"Microsoft YaHei UI"
    );

    g_speedFont = CreateFontW(
        -S(44), 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
        L"Segoe UI"
    );

    g_unitFont = CreateFontW(
        -S(14), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
        L"Microsoft YaHei UI"
    );

    g_smallFont = CreateFontW(
        -S(12), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
        L"Microsoft YaHei UI"
    );

    g_closeFont = CreateFontW(
        -S(20), 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
        L"Segoe UI Symbol"
    );
}

void SetScalePercent(int percent)
{
    if(percent < 60) percent = 60;
    if(percent > 200) percent = 200;

    if(percent == g_scalePercent)
        return;

    RECT oldRect = {};
    if(g_hwnd)
        GetWindowRect(g_hwnd, &oldRect);

    int oldCenterX = (oldRect.left + oldRect.right) / 2;
    int oldCenterY = (oldRect.top + oldRect.bottom) / 2;

    g_scalePercent = percent;
    CreateFonts();

    if(g_hwnd)
    {
        int w = GetWindowWidth();
        int h = GetWindowHeight();
        int x = oldCenterX - w / 2;
        int y = oldCenterY - h / 2;

        ClampWindowPosition(x, y);

        SetWindowPos(
            g_hwnd,
            HWND_TOPMOST,
            x,
            y,
            w,
            h,
            SWP_NOACTIVATE
        );

        InvalidateRect(g_hwnd, NULL, FALSE);
    }
}

void ChangeScale(int delta)
{
    SetScalePercent(g_scalePercent + delta);
}

// ============================================================
// Tray
// ============================================================

void AddTrayIcon(HWND hwnd)
{
    ZeroMemory(&g_tray, sizeof(g_tray));

    g_tray.cbSize = sizeof(g_tray);
    g_tray.hWnd = hwnd;
    g_tray.uID = TRAY_ICON_ID;
    g_tray.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
    g_tray.uCallbackMessage = WM_TRAYICON;
    g_tray.hIcon = LoadIconW(NULL, IDI_APPLICATION);

    lstrcpynW(g_tray.szTip, L"TYPEspeed - 实时键速", 128);
    Shell_NotifyIconW(NIM_ADD, &g_tray);
}

void RemoveTrayIcon()
{
    if(g_tray.hWnd)
    {
        Shell_NotifyIconW(NIM_DELETE, &g_tray);
        ZeroMemory(&g_tray, sizeof(g_tray));
    }
}

void HideToTray(HWND hwnd)
{
    ShowWindow(hwnd, SW_HIDE);
}

void ShowFromTray(HWND hwnd)
{
    ShowWindow(hwnd, SW_SHOWNOACTIVATE);
    SetWindowPos(
        hwnd,
        HWND_TOPMOST,
        0,
        0,
        0,
        0,
        SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW
    );
    InvalidateRect(hwnd, NULL, FALSE);
}

// ============================================================
// Geometry / hit test
// ============================================================

RECT GetCloseButtonRect(HWND hwnd)
{
    (void)hwnd;

    RECT r = {};
    r.left   = LX(BASE_WINDOW_WIDTH - 40);
    r.top    = LY(7);
    r.right  = LX(BASE_WINDOW_WIDTH - 8);
    r.bottom = LY(36);
    return r;
}

bool IsPointInCloseButton(HWND hwnd, POINT pt)
{
    RECT r = GetCloseButtonRect(hwnd);
    return PtInRect(&r, pt) != FALSE;
}

double RoundedRectDistance(double px, double py)
{
    double ox = (double)GetShadowMargin();
    double oy = (double)GetShadowMargin();
    double w  = (double)GetContentWidth();
    double h  = (double)GetContentHeight();
    double r  = (double)S(BASE_CORNER_RADIUS);

    if(r < 4.0) r = 4.0;

    double cx = ox + w * 0.5;
    double cy = oy + h * 0.5;
    double bx = w * 0.5;
    double by = h * 0.5;

    double qx = fabs(px - cx) - bx + r;
    double qy = fabs(py - cy) - by + r;

    double ax = qx > 0.0 ? qx : 0.0;
    double ay = qy > 0.0 ? qy : 0.0;

    double outside = sqrt(ax * ax + ay * ay);
    double inside = qx > qy ? qx : qy;
    if(inside > 0.0) inside = 0.0;

    return outside + inside - r;
}

bool IsPointInsideContentShape(POINT pt)
{
    return RoundedRectDistance((double)pt.x + 0.5, (double)pt.y + 0.5) <= 0.5;
}

// ============================================================
// Layered rendering
// ============================================================

void FillOpaqueGradient32(BYTE* bits, int width, int height, const Palette &p)
{
    int ox = GetShadowMargin();
    int oy = GetShadowMargin();
    int cw = GetContentWidth();
    int ch = GetContentHeight();

    int sr = GetRValue(p.shadow);
    int sg = GetGValue(p.shadow);
    int sb = GetBValue(p.shadow);

    for(int y = 0; y < height; ++y)
    {
        BYTE* row = bits + y * width * 4;

        for(int x = 0; x < width; ++x)
        {
            row[x * 4 + 0] = (BYTE)sb;
            row[x * 4 + 1] = (BYTE)sg;
            row[x * 4 + 2] = (BYTE)sr;
            row[x * 4 + 3] = 255;
        }
    }

    int tr = GetRValue(p.bgTop);
    int tg = GetGValue(p.bgTop);
    int tb = GetBValue(p.bgTop);

    int br = GetRValue(p.bgBottom);
    int bg = GetGValue(p.bgBottom);
    int bb = GetBValue(p.bgBottom);

    for(int y = 0; y < ch; ++y)
    {
        double t = ch > 1 ? (double)y / (double)(ch - 1) : 0.0;
        t = t * t * (3.0 - 2.0 * t);

        int rr = (int)(tr + (br - tr) * t + 0.5);
        int gg = (int)(tg + (bg - tg) * t + 0.5);
        int bl = (int)(tb + (bb - tb) * t + 0.5);

        BYTE* row = bits + (oy + y) * width * 4;

        for(int x = 0; x < cw; ++x)
        {
            int px = ox + x;
            row[px * 4 + 0] = (BYTE)bl;
            row[px * 4 + 1] = (BYTE)gg;
            row[px * 4 + 2] = (BYTE)rr;
            row[px * 4 + 3] = 255;
        }
    }
}

// 两次可分离盒式模糊。视觉上接近高斯模糊,但计算量远低于逐像素高斯卷积,
// 更适合 100ms 刷新的桌面悬浮窗。
void BoxBlur32(BYTE* bits, int width, int height, int radius)
{
    if(radius <= 0 || width <= 1 || height <= 1)
        return;

    if(radius > 24)
        radius = 24;

    vector<BYTE> temp((size_t)width * (size_t)height * 4);
    int window = radius * 2 + 1;

    // Horizontal pass
    for(int y = 0; y < height; ++y)
    {
        long sumB = 0;
        long sumG = 0;
        long sumR = 0;

        for(int k = -radius; k <= radius; ++k)
        {
            int sx = k;
            if(sx < 0) sx = 0;
            if(sx >= width) sx = width - 1;

            BYTE* px = bits + ((size_t)y * width + sx) * 4;
            sumB += px[0];
            sumG += px[1];
            sumR += px[2];
        }

        for(int x = 0; x < width; ++x)
        {
            BYTE* out = &temp[((size_t)y * width + x) * 4];
            out[0] = (BYTE)(sumB / window);
            out[1] = (BYTE)(sumG / window);
            out[2] = (BYTE)(sumR / window);
            out[3] = 255;

            int removeX = x - radius;
            int addX = x + radius + 1;

            if(removeX < 0) removeX = 0;
            if(removeX >= width) removeX = width - 1;
            if(addX < 0) addX = 0;
            if(addX >= width) addX = width - 1;

            BYTE* removePx = bits + ((size_t)y * width + removeX) * 4;
            BYTE* addPx = bits + ((size_t)y * width + addX) * 4;

            sumB += (long)addPx[0] - (long)removePx[0];
            sumG += (long)addPx[1] - (long)removePx[1];
            sumR += (long)addPx[2] - (long)removePx[2];
        }
    }

    // Vertical pass
    for(int x = 0; x < width; ++x)
    {
        long sumB = 0;
        long sumG = 0;
        long sumR = 0;

        for(int k = -radius; k <= radius; ++k)
        {
            int sy = k;
            if(sy < 0) sy = 0;
            if(sy >= height) sy = height - 1;

            BYTE* px = &temp[((size_t)sy * width + x) * 4];
            sumB += px[0];
            sumG += px[1];
            sumR += px[2];
        }

        for(int y = 0; y < height; ++y)
        {
            BYTE* out = bits + ((size_t)y * width + x) * 4;
            out[0] = (BYTE)(sumB / window);
            out[1] = (BYTE)(sumG / window);
            out[2] = (BYTE)(sumR / window);
            out[3] = 255;

            int removeY = y - radius;
            int addY = y + radius + 1;

            if(removeY < 0) removeY = 0;
            if(removeY >= height) removeY = height - 1;
            if(addY < 0) addY = 0;
            if(addY >= height) addY = height - 1;

            BYTE* removePx = &temp[((size_t)removeY * width + x) * 4];
            BYTE* addPx = &temp[((size_t)addY * width + x) * 4];

            sumB += (long)addPx[0] - (long)removePx[0];
            sumG += (long)addPx[1] - (long)removePx[1];
            sumR += (long)addPx[2] - (long)removePx[2];
        }
    }
}

void TintBackdrop32(BYTE* bits, int width, int height, const Palette &p)
{
    int ox = GetShadowMargin();
    int oy = GetShadowMargin();
    int cw = GetContentWidth();
    int ch = GetContentHeight();

    // 透明度越高,主题染色略微越强,避免文字区域显得脏乱。
    double baseTint =
        (g_theme == THEME_LIGHT || g_theme == THEME_BLUE_WHITE)
        ? 0.72
        : 0.78;

    baseTint += (double)g_transparencyPercent * 0.0010;
    if(baseTint > 0.88) baseTint = 0.88;

    int tr = GetRValue(p.bgTop);
    int tg = GetGValue(p.bgTop);
    int tb = GetBValue(p.bgTop);

    int br = GetRValue(p.bgBottom);
    int bg = GetGValue(p.bgBottom);
    int bb = GetBValue(p.bgBottom);

    for(int y = 0; y < ch; ++y)
    {
        double t = ch > 1 ? (double)y / (double)(ch - 1) : 0.0;
        t = t * t * (3.0 - 2.0 * t);

        int tintR = (int)(tr + (br - tr) * t + 0.5);
        int tintG = (int)(tg + (bg - tg) * t + 0.5);
        int tintB = (int)(tb + (bb - tb) * t + 0.5);

        BYTE* row = bits + (oy + y) * width * 4;

        for(int x = 0; x < cw; ++x)
        {
            int index = (ox + x) * 4;

            int srcB = row[index + 0];
            int srcG = row[index + 1];
            int srcR = row[index + 2];

            row[index + 0] = (BYTE)(srcB * (1.0 - baseTint) + tintB * baseTint + 0.5);
            row[index + 1] = (BYTE)(srcG * (1.0 - baseTint) + tintG * baseTint + 0.5);
            row[index + 2] = (BYTE)(srcR * (1.0 - baseTint) + tintR * baseTint + 0.5);
            row[index + 3] = 255;
        }
    }
}

bool PrepareBlurredBackdrop32(
    HDC memDC,
    HDC screenDC,
    BYTE* bits,
    int width,
    int height,
    const RECT &windowRect,
    const Palette &p
)
{
    // 0% 透明必须是真正不透明,因此此时完全关闭背景采样/玻璃效果。
    if(g_transparencyPercent <= 0)
    {
        FillOpaqueGradient32(bits, width, height, p);
        return true;
    }

    BOOL copied = BitBlt(
        memDC,
        0,
        0,
        width,
        height,
        screenDC,
        windowRect.left,
        windowRect.top,
        SRCCOPY
    );

    if(!copied)
    {
        FillOpaqueGradient32(bits, width, height, p);
        return false;
    }

    int blurRadius = S(6);
    if(blurRadius < 3) blurRadius = 3;
    if(blurRadius > 18) blurRadius = 18;

    // 两次调用(每次内部横+纵)进一步接近高斯柔化。
    BoxBlur32(bits, width, height, blurRadius);
    BoxBlur32(bits, width, height, blurRadius / 2 + 1);
    TintBackdrop32(bits, width, height, p);
    return true;
}

void DrawRoundedBar(HDC hdc, const RECT &r, COLORREF color, int radius)
{
    HBRUSH brush = CreateSolidBrush(color);
    HPEN pen = CreatePen(PS_NULL, 0, color);

    HBRUSH oldBrush = (HBRUSH)SelectObject(hdc, brush);
    HPEN oldPen = (HPEN)SelectObject(hdc, pen);

    RoundRect(
        hdc,
        r.left,
        r.top,
        r.right,
        r.bottom,
        radius,
        radius
    );

    SelectObject(hdc, oldBrush);
    SelectObject(hdc, oldPen);
    DeleteObject(brush);
    DeleteObject(pen);
}

void DrawWindowContent(HWND hwnd, HDC hdc, const Palette &p)
{
    SetBkMode(hdc, TRANSPARENT);

    // 柔和边框
    HPEN borderPen = CreatePen(PS_SOLID, S(1) < 1 ? 1 : S(1), p.border);
    HBRUSH hollow = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
    HPEN oldPen = (HPEN)SelectObject(hdc, borderPen);
    HBRUSH oldBrush = (HBRUSH)SelectObject(hdc, hollow);

    RoundRect(
        hdc,
        GetShadowMargin(),
        GetShadowMargin(),
        GetShadowMargin() + GetContentWidth(),
        GetShadowMargin() + GetContentHeight(),
        S(BASE_CORNER_RADIUS) * 2,
        S(BASE_CORNER_RADIUS) * 2
    );

    SelectObject(hdc, oldBrush);
    SelectObject(hdc, oldPen);
    DeleteObject(borderPen);

    // Status dot
    HBRUSH statusBrush = CreateSolidBrush(p.accent);
    HPEN statusPen = CreatePen(PS_NULL, 0, p.accent);
    oldBrush = (HBRUSH)SelectObject(hdc, statusBrush);
    oldPen = (HPEN)SelectObject(hdc, statusPen);

    Ellipse(hdc, LX(18), LY(19), LX(27), LY(28));

    SelectObject(hdc, oldBrush);
    SelectObject(hdc, oldPen);
    DeleteObject(statusBrush);
    DeleteObject(statusPen);

    // Title
    SelectObject(hdc, g_titleFont);
    SetTextColor(hdc, p.title);

    const wchar_t* title = L"实时键速";
    TextOutW(hdc, LX(36), LY(14), title, (int)wcslen(title));

    // Close button
    RECT closeRect = GetCloseButtonRect(hwnd);

    if(g_closeHover || g_closePressed)
    {
        int radius = S(8);
        if(radius < 4) radius = 4;
        DrawRoundedBar(hdc, closeRect, p.closeHover, radius);
    }

    SelectObject(hdc, g_closeFont);
    SetTextColor(hdc, g_closeHover || g_closePressed ? p.closeText : p.secondary);

    const wchar_t* closeText = L"×";
    SIZE closeSize = {};
    GetTextExtentPoint32W(hdc, closeText, 1, &closeSize);

    int closeX = closeRect.left + (closeRect.right - closeRect.left - closeSize.cx) / 2;
    int closeY = closeRect.top + (closeRect.bottom - closeRect.top - closeSize.cy) / 2 - S(1);

    TextOutW(hdc, closeX, closeY, closeText, 1);

    // Session total at top right
    wchar_t countText[64];
    swprintf(countText, 64, L"总计 %llu 次", (unsigned long long)g_events.size());

    SelectObject(hdc, g_smallFont);
    SetTextColor(hdc, p.secondary);

    SIZE countSize = {};
    GetTextExtentPoint32W(hdc, countText, (int)wcslen(countText), &countSize);

    TextOutW(
        hdc,
        closeRect.left - countSize.cx - S(10),
        LY(17),
        countText,
        (int)wcslen(countText)
    );

    // CPM: 固定最近 60 秒滚动次数
    long long cpm = GetCurrentCPM();
    wchar_t speedText[64];
    swprintf(speedText, 64, L"%lld", cpm);

    SelectObject(hdc, g_speedFont);
    SetTextColor(hdc, p.primary);

    int speedX = LX(18);
    int speedY = LY(38);

    TextOutW(hdc, speedX, speedY, speedText, (int)wcslen(speedText));

    SIZE speedSize = {};
    GetTextExtentPoint32W(hdc, speedText, (int)wcslen(speedText), &speedSize);

    SelectObject(hdc, g_unitFont);
    SetTextColor(hdc, p.secondary);

    const wchar_t* unit = L"CPM · 最近 60 秒";
    TextOutW(
        hdc,
        speedX + speedSize.cx + S(9),
        LY(63),
        unit,
        (int)wcslen(unit)
    );

    wchar_t hint[192];
    swprintf(
        hint,
        192,
        L"物理按键去重 · Backspace 撤销 · 透明 %d%% · 缩放 %d%%",
        g_transparencyPercent,
        g_scalePercent
    );

    SelectObject(hdc, g_smallFont);
    SetTextColor(hdc, p.muted);

    TextOutW(hdc, LX(18), LY(100), hint, (int)wcslen(hint));

    // Progress bar, 600 CPM = full
    int barLeft   = LX(18);
    int barRight  = LX(BASE_WINDOW_WIDTH - 18);
    int barTop    = LY(BASE_WINDOW_HEIGHT - 11);
    int barBottom = LY(BASE_WINDOW_HEIGHT - 7);

    RECT barRect = { barLeft, barTop, barRight, barBottom };
    int barRadius = S(4);
    if(barRadius < 2) barRadius = 2;

    DrawRoundedBar(hdc, barRect, p.track, barRadius);

    double ratio = (double)cpm / 600.0;
    if(ratio > 1.0) ratio = 1.0;
    if(ratio < 0.0) ratio = 0.0;

    int fillWidth = (int)((barRight - barLeft) * ratio + 0.5);

    if(fillWidth > 0)
    {
        RECT fill = {
            barLeft,
            barTop,
            barLeft + fillWidth,
            barBottom
        };

        DrawRoundedBar(hdc, fill, p.accent, barRadius);
    }
}

void ApplyAlphaMaskAndGaussianShadow(
    BYTE* bits,
    int width,
    int height,
    const Palette &p
)
{
    double opacity = (100.0 - (double)g_transparencyPercent) / 100.0;
    opacity = ClampDouble(opacity, 0.0, 1.0);

    double edgeWidth = (double)S(1);
    if(edgeWidth < 1.0) edgeWidth = 1.0;
    edgeWidth *= 1.25;

    double sigma = (double)S(7);
    if(sigma < 4.0) sigma = 4.0;

    const double shadowStrength = 0.34;

    int shadowR = GetRValue(p.shadow);
    int shadowG = GetGValue(p.shadow);
    int shadowB = GetBValue(p.shadow);

    for(int y = 0; y < height; ++y)
    {
        BYTE* row = bits + y * width * 4;

        for(int x = 0; x < width; ++x)
        {
            double d = RoundedRectDistance((double)x + 0.5, (double)y + 0.5);

            double coverage;

            if(d <= -edgeWidth)
            {
                coverage = 1.0;
            }
            else if(d >= edgeWidth)
            {
                coverage = 0.0;
            }
            else
            {
                double t = 0.5 - d / (2.0 * edgeWidth);
                t = ClampDouble(t, 0.0, 1.0);
                coverage = t * t * (3.0 - 2.0 * t);
            }

            double outside = d > 0.0 ? d : 0.0;
            double shadow = exp(-(outside * outside) / (2.0 * sigma * sigma));
            shadow *= shadowStrength;

            double localAlpha = coverage;
            if(shadow > localAlpha)
                localAlpha = shadow;

            int index = x * 4;

            int b = row[index + 0];
            int g = row[index + 1];
            int r = row[index + 2];

            // 圆角外部使用阴影颜色;边缘做颜色过渡,避免锯齿/硬边。
            if(coverage < 1.0)
            {
                r = (int)(shadowR + (r - shadowR) * coverage + 0.5);
                g = (int)(shadowG + (g - shadowG) * coverage + 0.5);
                b = (int)(shadowB + (b - shadowB) * coverage + 0.5);
            }

            int a = (int)(255.0 * opacity * localAlpha + 0.5);
            a = ClampByteInt(a);

            // UpdateLayeredWindow 需要预乘 alpha。
            row[index + 0] = (BYTE)((b * a + 127) / 255);
            row[index + 1] = (BYTE)((g * a + 127) / 255);
            row[index + 2] = (BYTE)((r * a + 127) / 255);
            row[index + 3] = (BYTE)a;
        }
    }
}

void RenderLayeredWindow(HWND hwnd)
{
    if(!hwnd)
        return;

    RECT wr;
    GetWindowRect(hwnd, &wr);

    int width = GetWindowWidth();
    int height = GetWindowHeight();

    HDC screenDC = GetDC(NULL);
    if(!screenDC)
        return;

    HDC memDC = CreateCompatibleDC(screenDC);
    if(!memDC)
    {
        ReleaseDC(NULL, screenDC);
        return;
    }

    BITMAPINFO bmi;
    ZeroMemory(&bmi, sizeof(bmi));

    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = -height; // top-down DIB
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biCompression = BI_RGB;

    BYTE* bits = NULL;

    HBITMAP bitmap = CreateDIBSection(
        screenDC,
        &bmi,
        DIB_RGB_COLORS,
        (void**)&bits,
        NULL,
        0
    );

    if(!bitmap || !bits)
    {
        if(bitmap) DeleteObject(bitmap);
        DeleteDC(memDC);
        ReleaseDC(NULL, screenDC);
        return;
    }

    HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, bitmap);

    Palette p = GetPalette();
    PrepareBlurredBackdrop32(memDC, screenDC, bits, width, height, wr, p);
    DrawWindowContent(hwnd, memDC, p);
    ApplyAlphaMaskAndGaussianShadow(bits, width, height, p);

    POINT dst = { wr.left, wr.top };
    POINT src = { 0, 0 };
    SIZE size = { width, height };

    BLENDFUNCTION blend;
    blend.BlendOp = AC_SRC_OVER;
    blend.BlendFlags = 0;
    blend.SourceConstantAlpha = 255;
    blend.AlphaFormat = AC_SRC_ALPHA;

    UpdateLayeredWindow(
        hwnd,
        screenDC,
        &dst,
        &size,
        memDC,
        &src,
        0,
        &blend,
        ULW_ALPHA
    );

    SelectObject(memDC, oldBitmap);
    DeleteObject(bitmap);
    DeleteDC(memDC);
    ReleaseDC(NULL, screenDC);
}

// ============================================================
// Keyboard filtering
// ============================================================

bool IsCommandModifierDown()
{
    bool ctrl = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
    bool alt  = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;
    bool win  =
        (GetAsyncKeyState(VK_LWIN) & 0x8000) != 0 ||
        (GetAsyncKeyState(VK_RWIN) & 0x8000) != 0;

    return ctrl || alt || win;
}

bool IsToolControlKey(DWORD vk)
{
    bool ctrl = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
    bool alt  = (GetAsyncKeyState(VK_MENU) & 0x8000) != 0;

    if(!ctrl || !alt)
        return false;

    return
        vk == 'Q' ||
        vk == 'R' ||
        vk == VK_LEFT ||
        vk == VK_RIGHT ||
        vk == VK_UP ||
        vk == VK_DOWN ||
        vk == VK_PRIOR ||
        vk == VK_NEXT ||
        vk == VK_OEM_PLUS ||
        vk == VK_OEM_MINUS;
}

bool IsInputKey(DWORD vk)
{
    // Ctrl+C / Alt+Tab / Win+... 等命令组合不计数。
    if(IsCommandModifierDown())
        return false;

    if(vk >= 'A' && vk <= 'Z')
        return true;

    if(vk >= '0' && vk <= '9')
        return true;

    if(vk >= VK_NUMPAD0 && vk <= VK_NUMPAD9)
        return true;

    switch(vk)
    {
        case VK_SPACE:
        case VK_RETURN:

        case VK_MULTIPLY:
        case VK_ADD:
        case VK_SEPARATOR:
        case VK_SUBTRACT:
        case VK_DECIMAL:
        case VK_DIVIDE:

        case VK_OEM_1:
        case VK_OEM_PLUS:
        case VK_OEM_COMMA:
        case VK_OEM_MINUS:
        case VK_OEM_PERIOD:
        case VK_OEM_2:
        case VK_OEM_3:
        case VK_OEM_4:
        case VK_OEM_5:
        case VK_OEM_6:
        case VK_OEM_7:
        case VK_OEM_8:
        case VK_OEM_102:
            return true;
    }

    // Shift/Ctrl/Alt/Win/CapsLock/Tab/Esc/F1~F24/方向键/Home/End/
    // PageUp/PageDown/Insert/Delete/PrintScreen/媒体键等均不统计。
    return false;
}

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if(nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* info = (KBDLLHOOKSTRUCT*)lParam;
        DWORD vk = info->vkCode;

        if(vk < 256)
        {
            if(wParam == WM_KEYUP || wParam == WM_SYSKEYUP)
            {
                g_keyDown[vk] = false;
            }
            else if(wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
            {
                // 忽略程序模拟输入。
                if(info->flags & LLKHF_INJECTED)
                {
                    return CallNextHookEx(g_keyboardHook, nCode, wParam, lParam);
                }

                // 关键修复:屏蔽 Windows 键盘自动重复。
                // 一个物理按下动作只计一次,长按不会把 CPM 冲高。
                if(g_keyDown[vk])
                {
                    return CallNextHookEx(g_keyboardHook, nCode, wParam, lParam);
                }

                g_keyDown[vk] = true;

                if(IsToolControlKey(vk))
                {
                    return CallNextHookEx(g_keyboardHook, nCode, wParam, lParam);
                }

                if(vk == VK_BACK)
                {
                    if(!IsCommandModifierDown())
                        UndoKey();
                }
                else if(IsInputKey(vk))
                {
                    AddKey();
                }

                if(g_hwnd)
                    InvalidateRect(g_hwnd, NULL, FALSE);
            }
        }
    }

    return CallNextHookEx(g_keyboardHook, nCode, wParam, lParam);
}

// ============================================================
// About
// ============================================================

void ShowFeatureIntro(HWND hwnd)
{
    MessageBoxW(
        hwnd,
        L"TYPEspeed 功能简介\n\n"
        L"• CPM 使用最近 60 秒固定滚动窗口,不再用启动几秒数据外推\n"
        L"• 每次物理按键只计一次,长按产生的自动重复不计\n"
        L"• 字母、数字、标点、空格、Enter、小键盘输入参与统计\n"
        L"• Shift / Ctrl / Alt / Win / F 键 / 方向键等功能键不计\n"
        L"• Ctrl+C、Alt+Tab 等命令组合不计\n"
        L"• Backspace:撤销最近一次计数\n"
        L"• 双击窗口:隐藏到托盘;双击托盘:恢复\n"
        L"• 右上角 ×:退出程序\n"
        L"• 鼠标滚轮:调整透明度\n"
        L"• Ctrl + 鼠标滚轮:缩放窗口\n"
        L"• Ctrl+Alt+PageUp/PageDown:调整透明度\n"
        L"• Ctrl+Alt++ / -:缩放\n"
        L"• 主题:深色、浅色、蓝白、绿黑、自定义 HSL 色调\n\n"
        L"透明度定义:0% = 完全不透明,100% = 完全透明。\n"
        L"透明度大于 0% 时会采样窗口后方画面并做近似高斯模糊;\n"
        L"圆角采用逐像素抗锯齿,并带软件高斯柔光阴影。",
        L"TYPEspeed - 功能简介",
        MB_OK | MB_ICONINFORMATION
    );
}

// ============================================================
// Context menu
// ============================================================

UINT CheckedIf(bool yes)
{
    return yes ? MF_CHECKED : MF_UNCHECKED;
}

void AppendTransparencyItem(HMENU menu, int id, int value, const wchar_t* text)
{
    AppendMenuW(
        menu,
        MF_STRING | CheckedIf(g_transparencyPercent == value),
        id,
        text
    );
}

void AppendScaleItem(HMENU menu, int id, int value, const wchar_t* text)
{
    AppendMenuW(
        menu,
        MF_STRING | CheckedIf(g_scalePercent == value),
        id,
        text
    );
}

void ShowContextMenu(HWND hwnd, bool fromTray)
{
    HMENU menu = CreatePopupMenu();

    if(fromTray || !IsWindowVisible(hwnd))
    {
        AppendMenuW(menu, MF_STRING, MENU_SHOW, L"显示窗口");
        AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
    }
    else
    {
        AppendMenuW(menu, MF_STRING, MENU_HIDE_TO_TRAY, L"隐藏到托盘\t双击窗口");
        AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
    }

    AppendMenuW(menu, MF_STRING, MENU_RESET, L"重置统计\tCtrl+Alt+R");
    AppendMenuW(menu, MF_STRING, MENU_BOTTOM_RIGHT, L"回到右下角");

    AppendMenuW(menu, MF_SEPARATOR, 0, NULL);

    HMENU opacityMenu = CreatePopupMenu();
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_0,   0,   L"0%(完全不透明)");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_10,  10,  L"10%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_20,  20,  L"20%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_40,  40,  L"40%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_60,  60,  L"60%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_80,  80,  L"80%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_90,  90,  L"90%");
    AppendTransparencyItem(opacityMenu, MENU_TRANSPARENCY_100, 100, L"100%(完全透明)");
    AppendMenuW(menu, MF_POPUP, (UINT_PTR)opacityMenu, L"透明度");

    HMENU scaleMenu = CreatePopupMenu();
    AppendScaleItem(scaleMenu, MENU_SCALE_75,  75,  L"75%");
    AppendScaleItem(scaleMenu, MENU_SCALE_90,  90,  L"90%");
    AppendScaleItem(scaleMenu, MENU_SCALE_100, 100, L"100%");
    AppendScaleItem(scaleMenu, MENU_SCALE_110, 110, L"110%");
    AppendScaleItem(scaleMenu, MENU_SCALE_125, 125, L"125%");
    AppendScaleItem(scaleMenu, MENU_SCALE_150, 150, L"150%");
    AppendScaleItem(scaleMenu, MENU_SCALE_175, 175, L"175%");
    AppendMenuW(menu, MF_POPUP, (UINT_PTR)scaleMenu, L"缩放");

    HMENU themeMenu = CreatePopupMenu();

    AppendMenuW(themeMenu, MF_STRING | CheckedIf(g_theme == THEME_DARK),
        MENU_THEME_DARK, L"深色 · 夜蓝灰");
    AppendMenuW(themeMenu, MF_STRING | CheckedIf(g_theme == THEME_LIGHT),
        MENU_THEME_LIGHT, L"浅色 · 雾白");
    AppendMenuW(themeMenu, MF_STRING | CheckedIf(g_theme == THEME_BLUE_WHITE),
        MENU_THEME_BLUE_WHITE, L"蓝白");
    AppendMenuW(themeMenu, MF_STRING | CheckedIf(g_theme == THEME_GREEN_BLACK),
        MENU_THEME_GREEN_BLACK, L"绿黑");
    AppendMenuW(themeMenu, MF_STRING | CheckedIf(g_theme == THEME_CUSTOM),
        MENU_THEME_CUSTOM, L"自定义");

    AppendMenuW(themeMenu, MF_SEPARATOR, 0, NULL);

    HMENU customMenu = CreatePopupMenu();

    wchar_t customInfo[96];
    swprintf(
        customInfo,
        96,
        L"当前 H %.0f° · S %.0f%% · L %.0f%%",
        g_customHue,
        g_customSat,
        g_customLit
    );

    AppendMenuW(customMenu, MF_STRING | MF_GRAYED, 0, customInfo);
    AppendMenuW(customMenu, MF_SEPARATOR, 0, NULL);
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_HUE_MINUS, L"色相 -15°");
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_HUE_PLUS,  L"色相 +15°");
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_SAT_MINUS, L"饱和度 -10%");
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_SAT_PLUS,  L"饱和度 +10%");
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_LIT_MINUS, L"亮度 -6%");
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_LIT_PLUS,  L"亮度 +6%");
    AppendMenuW(customMenu, MF_SEPARATOR, 0, NULL);
    AppendMenuW(customMenu, MF_STRING, MENU_CUSTOM_RESET, L"恢复自定义默认值");

    AppendMenuW(themeMenu, MF_POPUP, (UINT_PTR)customMenu, L"自定义色调调节");
    AppendMenuW(menu, MF_POPUP, (UINT_PTR)themeMenu, L"主题");

    AppendMenuW(menu, MF_STRING, MENU_ABOUT, L"功能简介");

    AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
    AppendMenuW(menu, MF_STRING, MENU_EXIT, L"退出\tCtrl+Alt+Q");

    POINT pt;
    GetCursorPos(&pt);

    SetForegroundWindow(hwnd);

    int command = TrackPopupMenu(
        menu,
        TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_NONOTIFY,
        pt.x,
        pt.y,
        0,
        hwnd,
        NULL
    );

    DestroyMenu(menu);

    switch(command)
    {
        case MENU_SHOW:
            ShowFromTray(hwnd);
            break;

        case MENU_HIDE_TO_TRAY:
            HideToTray(hwnd);
            break;

        case MENU_RESET:
            ResetStatistics();
            break;

        case MENU_BOTTOM_RIGHT:
            PutWindowAtBottomRight(hwnd);
            ShowFromTray(hwnd);
            break;

        case MENU_TRANSPARENCY_0:   SetTransparencyPercent(0);   break;
        case MENU_TRANSPARENCY_10:  SetTransparencyPercent(10);  break;
        case MENU_TRANSPARENCY_20:  SetTransparencyPercent(20);  break;
        case MENU_TRANSPARENCY_40:  SetTransparencyPercent(40);  break;
        case MENU_TRANSPARENCY_60:  SetTransparencyPercent(60);  break;
        case MENU_TRANSPARENCY_80:  SetTransparencyPercent(80);  break;
        case MENU_TRANSPARENCY_90:  SetTransparencyPercent(90);  break;
        case MENU_TRANSPARENCY_100: SetTransparencyPercent(100); break;

        case MENU_SCALE_75:  SetScalePercent(75);  break;
        case MENU_SCALE_90:  SetScalePercent(90);  break;
        case MENU_SCALE_100: SetScalePercent(100); break;
        case MENU_SCALE_110: SetScalePercent(110); break;
        case MENU_SCALE_125: SetScalePercent(125); break;
        case MENU_SCALE_150: SetScalePercent(150); break;
        case MENU_SCALE_175: SetScalePercent(175); break;

        case MENU_THEME_DARK:        SetTheme(THEME_DARK);        break;
        case MENU_THEME_LIGHT:       SetTheme(THEME_LIGHT);       break;
        case MENU_THEME_BLUE_WHITE:  SetTheme(THEME_BLUE_WHITE);  break;
        case MENU_THEME_GREEN_BLACK: SetTheme(THEME_GREEN_BLACK); break;
        case MENU_THEME_CUSTOM:      SetTheme(THEME_CUSTOM);      break;

        case MENU_CUSTOM_HUE_MINUS: AdjustCustomHue(-15.0);       break;
        case MENU_CUSTOM_HUE_PLUS:  AdjustCustomHue(+15.0);       break;
        case MENU_CUSTOM_SAT_MINUS: AdjustCustomSaturation(-10.0); break;
        case MENU_CUSTOM_SAT_PLUS:  AdjustCustomSaturation(+10.0); break;
        case MENU_CUSTOM_LIT_MINUS: AdjustCustomLightness(-6.0);   break;
        case MENU_CUSTOM_LIT_PLUS:  AdjustCustomLightness(+6.0);   break;
        case MENU_CUSTOM_RESET:     ResetCustomTheme();            break;

        case MENU_ABOUT:
            ShowFeatureIntro(hwnd);
            break;

        case MENU_EXIT:
            DestroyWindow(hwnd);
            break;
    }
}

// ============================================================
// Hotkeys
// ============================================================

void RegisterProgramHotkeys(HWND hwnd)
{
    RegisterHotKey(hwnd, HOTKEY_EXIT,  MOD_CONTROL | MOD_ALT, 'Q');
    RegisterHotKey(hwnd, HOTKEY_RESET, MOD_CONTROL | MOD_ALT, 'R');

    RegisterHotKey(hwnd, HOTKEY_LEFT,  MOD_CONTROL | MOD_ALT, VK_LEFT);
    RegisterHotKey(hwnd, HOTKEY_RIGHT, MOD_CONTROL | MOD_ALT, VK_RIGHT);
    RegisterHotKey(hwnd, HOTKEY_UP,    MOD_CONTROL | MOD_ALT, VK_UP);
    RegisterHotKey(hwnd, HOTKEY_DOWN,  MOD_CONTROL | MOD_ALT, VK_DOWN);

    RegisterHotKey(hwnd, HOTKEY_TRANSPARENCY_UP,
        MOD_CONTROL | MOD_ALT, VK_PRIOR);
    RegisterHotKey(hwnd, HOTKEY_TRANSPARENCY_DOWN,
        MOD_CONTROL | MOD_ALT, VK_NEXT);

    RegisterHotKey(hwnd, HOTKEY_SCALE_UP,
        MOD_CONTROL | MOD_ALT, VK_OEM_PLUS);
    RegisterHotKey(hwnd, HOTKEY_SCALE_DOWN,
        MOD_CONTROL | MOD_ALT, VK_OEM_MINUS);
}

void UnregisterProgramHotkeys(HWND hwnd)
{
    UnregisterHotKey(hwnd, HOTKEY_EXIT);
    UnregisterHotKey(hwnd, HOTKEY_RESET);
    UnregisterHotKey(hwnd, HOTKEY_LEFT);
    UnregisterHotKey(hwnd, HOTKEY_RIGHT);
    UnregisterHotKey(hwnd, HOTKEY_UP);
    UnregisterHotKey(hwnd, HOTKEY_DOWN);
    UnregisterHotKey(hwnd, HOTKEY_TRANSPARENCY_UP);
    UnregisterHotKey(hwnd, HOTKEY_TRANSPARENCY_DOWN);
    UnregisterHotKey(hwnd, HOTKEY_SCALE_UP);
    UnregisterHotKey(hwnd, HOTKEY_SCALE_DOWN);
}

// ============================================================
// Window procedure
// ============================================================

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_CREATE:
        {
            g_hwnd = hwnd;
            CreateFonts();
            AddTrayIcon(hwnd);
            RegisterProgramHotkeys(hwnd);
            SetTimer(hwnd, TIMER_REFRESH, 100, NULL);
            return 0;
        }

        case WM_HOTKEY:
        {
            switch((int)wParam)
            {
                case HOTKEY_EXIT:
                    DestroyWindow(hwnd);
                    break;

                case HOTKEY_RESET:
                    ResetStatistics();
                    break;

                case HOTKEY_LEFT:
                    MoveWindowBy(-S(20), 0);
                    break;

                case HOTKEY_RIGHT:
                    MoveWindowBy(S(20), 0);
                    break;

                case HOTKEY_UP:
                    MoveWindowBy(0, -S(20));
                    break;

                case HOTKEY_DOWN:
                    MoveWindowBy(0, S(20));
                    break;

                case HOTKEY_TRANSPARENCY_UP:
                    ChangeTransparency(+5);
                    break;

                case HOTKEY_TRANSPARENCY_DOWN:
                    ChangeTransparency(-5);
                    break;

                case HOTKEY_SCALE_UP:
                    ChangeScale(+10);
                    break;

                case HOTKEY_SCALE_DOWN:
                    ChangeScale(-10);
                    break;
            }

            return 0;
        }

        case WM_TRAYICON:
        {
            if(lParam == WM_LBUTTONDBLCLK)
            {
                ShowFromTray(hwnd);
                return 0;
            }

            if(lParam == WM_RBUTTONUP || lParam == WM_CONTEXTMENU)
            {
                ShowContextMenu(hwnd, true);
                return 0;
            }

            return 0;
        }

        case WM_NCHITTEST:
        {
            if(g_transparencyPercent >= 100)
                return HTTRANSPARENT;

            POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
            ScreenToClient(hwnd, &pt);

            if(!IsPointInsideContentShape(pt))
                return HTTRANSPARENT;

            return HTCLIENT;
        }

        case WM_LBUTTONDOWN:
        {
            POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };

            if(IsPointInCloseButton(hwnd, pt))
            {
                g_closePressed = true;
                SetCapture(hwnd);
                InvalidateRect(hwnd, NULL, FALSE);
                return 0;
            }

            if(!IsPointInsideContentShape(pt))
                return 0;

            g_dragging = true;
            SetCapture(hwnd);

            POINT mouse;
            GetCursorPos(&mouse);

            RECT windowRect;
            GetWindowRect(hwnd, &windowRect);

            g_dragStartMouse = mouse;
            g_dragStartWindow.x = windowRect.left;
            g_dragStartWindow.y = windowRect.top;

            return 0;
        }

        case WM_MOUSEMOVE:
        {
            POINT clientPt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
            bool hover = IsPointInCloseButton(hwnd, clientPt);

            if(hover != g_closeHover)
            {
                g_closeHover = hover;
                InvalidateRect(hwnd, NULL, FALSE);
            }

            TRACKMOUSEEVENT tme = {};
            tme.cbSize = sizeof(tme);
            tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd;
            TrackMouseEvent(&tme);

            if(g_dragging)
            {
                POINT mouse;
                GetCursorPos(&mouse);

                int dx = mouse.x - g_dragStartMouse.x;
                int dy = mouse.y - g_dragStartMouse.y;

                int x = g_dragStartWindow.x + dx;
                int y = g_dragStartWindow.y + dy;

                ClampWindowPosition(x, y);

                SetWindowPos(
                    hwnd,
                    HWND_TOPMOST,
                    x,
                    y,
                    0,
                    0,
                    SWP_NOSIZE | SWP_NOACTIVATE
                );
            }

            return 0;
        }

        case WM_MOUSELEAVE:
        {
            g_closeHover = false;
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        case WM_LBUTTONUP:
        {
            POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };

            if(g_closePressed)
            {
                bool shouldClose = IsPointInCloseButton(hwnd, pt);
                g_closePressed = false;
                ReleaseCapture();
                InvalidateRect(hwnd, NULL, FALSE);

                if(shouldClose)
                    DestroyWindow(hwnd);

                return 0;
            }

            if(g_dragging)
            {
                g_dragging = false;
                ReleaseCapture();
            }

            return 0;
        }

        case WM_LBUTTONDBLCLK:
        {
            POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };

            if(!IsPointInCloseButton(hwnd, pt) && IsPointInsideContentShape(pt))
                HideToTray(hwnd);

            return 0;
        }

        case WM_MOUSEWHEEL:
        {
            short delta = GET_WHEEL_DELTA_WPARAM(wParam);
            bool ctrl = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;

            if(ctrl)
            {
                if(delta > 0)
                    ChangeScale(+10);
                else
                    ChangeScale(-10);
            }
            else
            {
                // 上滚更不透明,下滚更透明。
                if(delta > 0)
                    ChangeTransparency(-5);
                else
                    ChangeTransparency(+5);
            }

            return 0;
        }

        case WM_RBUTTONUP:
        case WM_NCRBUTTONUP:
        {
            ShowContextMenu(hwnd, false);
            return 0;
        }

        case WM_TIMER:
        {
            if(wParam == TIMER_REFRESH)
                InvalidateRect(hwnd, NULL, FALSE);

            return 0;
        }

        case WM_PAINT:
        {
            PAINTSTRUCT ps;
            BeginPaint(hwnd, &ps);
            EndPaint(hwnd, &ps);

            RenderLayeredWindow(hwnd);
            return 0;
        }

        case WM_ERASEBKGND:
            return 1;

        case WM_DISPLAYCHANGE:
        case WM_SETTINGCHANGE:
        {
            RECT rc;
            GetWindowRect(hwnd, &rc);

            int x = rc.left;
            int y = rc.top;
            ClampWindowPosition(x, y);

            SetWindowPos(
                hwnd,
                HWND_TOPMOST,
                x,
                y,
                GetWindowWidth(),
                GetWindowHeight(),
                SWP_NOACTIVATE
            );

            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        case WM_SIZE:
        {
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        case WM_DESTROY:
        {
            KillTimer(hwnd, TIMER_REFRESH);
            UnregisterProgramHotkeys(hwnd);
            RemoveTrayIcon();

            if(g_keyboardHook)
            {
                UnhookWindowsHookEx(g_keyboardHook);
                g_keyboardHook = NULL;
            }

            DeleteFonts();
            g_hwnd = NULL;

            PostQuitMessage(0);
            return 0;
        }
    }

    return DefWindowProcW(hwnd, message, wParam, lParam);
}

// ============================================================
// Main
// ============================================================

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
    const wchar_t CLASS_NAME[] = L"TypeSpeedOverlayWindow";

    WNDCLASSEXW wc;
    ZeroMemory(&wc, sizeof(wc));

    wc.cbSize = sizeof(wc);
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
    wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
    wc.hIconSm = LoadIconW(NULL, IDI_APPLICATION);
    wc.hbrBackground = NULL;
    wc.lpszClassName = CLASS_NAME;

    if(!RegisterClassExW(&wc))
        return 1;

    DWORD exStyle =
        WS_EX_TOOLWINDOW |
        WS_EX_TOPMOST |
        WS_EX_LAYERED |
        WS_EX_NOACTIVATE;

    HWND hwnd = CreateWindowExW(
        exStyle,
        CLASS_NAME,
        L"TYPEspeed",
        WS_POPUP,
        0,
        0,
        GetWindowWidth(),
        GetWindowHeight(),
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if(!hwnd)
        return 1;

    g_hwnd = hwnd;
    PutWindowAtBottomRight(hwnd);

    g_keyboardHook = SetWindowsHookExW(
        WH_KEYBOARD_LL,
        KeyboardProc,
        hInstance,
        0
    );

    if(!g_keyboardHook)
    {
        MessageBoxW(
            NULL,
            L"无法安装键盘监听 Hook。",
            L"TYPEspeed",
            MB_ICONERROR
        );

        DestroyWindow(hwnd);
        return 1;
    }

    ShowWindow(hwnd, SW_SHOWNOACTIVATE);
    UpdateWindow(hwnd);
    RenderLayeredWindow(hwnd);

    MSG msg;

    while(GetMessageW(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    }

    return (int)msg.wParam;
}
原文