跳到正文

剪贴板

剪贴板 rxzgy6xr

Jxl_Lxh
原文
剪贴板信息

剪贴板信息

发布
收录
更新
C++
#define _WIN32_WINNT 0x0600
#define UNICODE
#define _UNICODE

#include <windows.h>
#include <windowsx.h>
#include <shellapi.h>
#include <shlobj.h>
#include <commctrl.h>
#include <map>
#include <vector>
#include <string>
#include <math.h>
#include <stdio.h>

#define WM_TRAYICON         (WM_USER + 1)
#define WM_APP_NEW_INSTANCE (WM_APP + 100)
#define WM_MENU_SELECTED    (WM_APP + 200)
#define TIMER_CLEANUP       1
#define TIMER_FADE          2

#define MIN_ALPHA 10
#define MAX_ALPHA 255
#define STEP_ALPHA 20

#define HK_DOWN 1
#define HK_UP 2
#define HK_RESET 3
#define HK_EXIT 4
#define HK_P1 5
#define HK_P2 6
#define HK_P3 7
#define HK_P4 8

#define WIN_W_BASE 760
#define WIN_H_BASE 500
#define HELP_W_BASE 660
#define HELP_H_BASE 620
#define TITLE_H 48
#define CORNER_R 8

#define CARD_Y 64
#define CARD_H 340
#define CARD_L_X 20
#define CARD_L_W 350
#define CARD_R_X 390
#define CARD_R_W 350

#define L_LABEL_Y (CARD_Y + 18)
#define L_TARGET_Y (CARD_Y + 42)
#define L_TARGET_H 42
#define L_SEARCH_Y (CARD_Y + 92)
#define L_SEARCH_H 34
#define L_BTNS_Y (CARD_Y + 136)
#define L_BTN_H 34
#define L_TOPCT_Y (CARD_Y + 180)
#define L_CHECK_Y (CARD_Y + 226)
#define L_HELP_Y (CARD_Y + 264)
#define L_HELP_H 42

#define R_LABEL_Y (CARD_Y + 22)
#define R_NUM_Y (CARD_Y + 50)
#define R_NUM_H 100
#define R_SLIDER_Y (CARD_Y + 210)
#define R_PRESET_Y (CARD_Y + 250)
#define R_PRESET_H 44

#define ID_MORE_TOP    2001
#define ID_MORE_EXCL   2002
#define ID_MORE_FADE5  2003
#define ID_MORE_FADE10 2004
#define ID_MORE_FADE30 2005
#define ID_REFRESH     1
#define ID_SEARCH_CLEAR 2
#define ID_SEARCH_EDIT 4001

#define MENU_ITEM_H 36
#define MENU_SEP_H 9
#define MENU_PAD 8
#define MENU_MAX_H 480
#ifndef ECM_FIRST
#define ECM_FIRST 0x1500
#endif
#ifndef EM_SETCUEBANNER
#define EM_SETCUEBANNER (ECM_FIRST + 1)
#endif

double g_dpiScale = 1.0;
int S(int v) { return (int)(v * g_dpiScale + 0.5); }

double mymax(double a, double b) { return a > b ? a : b; }

// ===== 主题 =====
struct Theme {
    COLORREF bg, bgTitle;
    COLORREF card, cardBorder;
    COLORREF accent, accentHover, accentDim;
    COLORREF text, text2, textDim, textFaint;
    COLORREF btn, btnHover, btnPress, btnBorder, btnText, btnTextHover;
    COLORREF checkOn, closeHover, sep;
    COLORREF editBg;
};

Theme g_themeDark = {
    RGB(32, 32, 32), RGB(39, 39, 39),
    RGB(43, 43, 43), RGB(58, 58, 58),
    RGB(167, 139, 250), RGB(192, 167, 252), RGB(100, 80, 160),
    RGB(255, 255, 255), RGB(200, 200, 200), RGB(155, 155, 155), RGB(100, 100, 100),
    RGB(50, 50, 50), RGB(62, 62, 62), RGB(41, 41, 41), RGB(70, 70, 70),
    RGB(255, 255, 255), RGB(255, 255, 255),
    RGB(167, 139, 250), RGB(196, 43, 28), RGB(58, 58, 58),
    RGB(38, 38, 38)
};

Theme g_themeLight = {
    RGB(243, 243, 243), RGB(243, 243, 243),
    RGB(255, 255, 255), RGB(229, 229, 229),
    RGB(124, 58, 237), RGB(109, 40, 217), RGB(200, 180, 240),
    RGB(28, 28, 28), RGB(68, 68, 68), RGB(118, 118, 118), RGB(170, 170, 170),
    RGB(251, 251, 251), RGB(240, 240, 240), RGB(232, 232, 232), RGB(218, 218, 218),
    RGB(28, 28, 28), RGB(28, 28, 28),
    RGB(124, 58, 237), RGB(196, 43, 28), RGB(229, 229, 229),
    RGB(248, 248, 248)
};

Theme g_theme;

#define C_BG         (g_theme.bg)
#define C_BG_TITLE   (g_theme.bgTitle)
#define C_CARD       (g_theme.card)
#define C_CARD_EDGE  (g_theme.cardBorder)
#define C_ACCENT     (g_theme.accent)
#define C_ACCENT_HOV (g_theme.accentHover)
#define C_ACCENT_DIM (g_theme.accentDim)
#define C_TEXT       (g_theme.text)
#define C_TEXT_2     (g_theme.text2)
#define C_TEXT_DIM   (g_theme.textDim)
#define C_TEXT_FAINT (g_theme.textFaint)
#define C_BTN        (g_theme.btn)
#define C_BTN_HOVER  (g_theme.btnHover)
#define C_BTN_PRESS  (g_theme.btnPress)
#define C_BTN_EDGE   (g_theme.btnBorder)
#define C_BTN_TEXT   (g_theme.btnText)
#define C_CHECK_ON   (g_theme.checkOn)
#define C_CLOSE_HOV  (g_theme.closeHover)
#define C_SEP        (g_theme.sep)
#define C_EDIT_BG    (g_theme.editBg)

// ===== 配置 =====
struct Config {
    int darkMode;
    int autoRestore;
    int firstRun;
    int saveProfiles;
    UINT hkModDown, hkModUp, hkModReset, hkModExit;
    UINT hkKeyDown, hkKeyUp, hkKeyReset, hkKeyExit;
    std::vector<std::wstring> exclude;
};
Config g_cfg;

struct WindowState {
    bool wasLayered;
    BYTE originalAlpha;
    bool wasTopmost;
    bool clickThrough;
};

HWND g_hwnd = NULL;
HWND g_hHelp = NULL;
HWND g_hSearchEdit = NULL;
HFONT g_fontTitle = NULL;
HFONT g_fontVersion = NULL;
HFONT g_fontBig = NULL;
HFONT g_fontPercent = NULL;
HFONT g_fontNormal = NULL;
HFONT g_fontSmall = NULL;
HFONT g_fontTiny = NULL;
HFONT g_fontBubble = NULL;
HFONT g_fontMenu = NULL;
HFONT g_fontHelpH1 = NULL;
HFONT g_fontHelpH2 = NULL;
HFONT g_fontHelpBody = NULL;

HBRUSH g_editBgBrush = NULL;

std::vector<HWND> g_wins;
std::vector<std::wstring> g_titles;
std::map<HWND, WindowState> g_modified;
std::map<std::wstring, int> g_profiles;

int g_selected = -1;
int g_alpha = MAX_ALPHA;
bool g_draggingSlider = false;
bool g_hoverSlider = false;

bool g_hoverTarget = false;
int g_hoverBtn = -1;
int g_pressBtn = -1;
bool g_hoverCheck = false;
bool g_checkOn = true;
bool g_hoverHelp = false;
bool g_hoverClose = false;
bool g_hoverMin = false;
bool g_hoverTheme = false;
bool g_hoverTopmost = false;
bool g_hoverClickThrough = false;
bool g_hoverMore = false;
int g_hoverPreset = -1;
int g_pressPreset = -1;
bool g_tracking = false;

bool g_fadeActive = false;
int g_fadeFrom = 255;
int g_fadeTo = 255;
int g_fadeSteps = 0;
int g_fadeTotalSteps = 0;
HWND g_fadeHwnd = NULL;

int g_helpScroll = 0;
bool g_helpHoverClose = false;
bool g_helpTracking = false;
bool g_helpDragging = false;
POINT g_helpDragOffset = {0, 0};

HICON g_appIcon = NULL;
HICON g_trayIcon = NULL;
int g_trayIconAlpha = -1;
NOTIFYICONDATAW g_nid;
bool g_trayAdded = false;
HANDLE g_hMutex = NULL;
std::wstring g_cfgPath;
std::wstring g_searchText;

// ===== 自定义菜单 =====
struct MenuItem {
    std::wstring text;
    int id;
    bool checked;
    bool disabled;
    bool isSeparator;
    MenuItem() : id(0), checked(false), disabled(false), isSeparator(false) {}
};

std::vector<MenuItem> g_menuItems;
HWND g_hMenuWnd = NULL;
HWND g_hMenuOwner = NULL;
int g_menuHover = -1;
bool g_menuTracking = false;

typedef BOOL (WINAPI *PFN_GetLayeredWindowAttributes)(HWND, COLORREF*, BYTE*, DWORD*);
typedef BOOL (WINAPI *PFN_SetProcessDPIAware)();
typedef BOOL (WINAPI *PFN_QueryFullProcessImageNameW)(HANDLE, DWORD, LPWSTR, PDWORD);

BOOL MyGetLWA(HWND hwnd, COLORREF* ck, BYTE* a, DWORD* fl) {
    static PFN_GetLayeredWindowAttributes fn = NULL;
    if (fn == NULL) {
        HMODULE h = GetModuleHandleW(L"user32.dll");
        if (h) {
            void* p = (void*)GetProcAddress(h, "GetLayeredWindowAttributes");
            fn = reinterpret_cast<PFN_GetLayeredWindowAttributes>(p);
        }
    }
    if (fn) return fn(hwnd, ck, a, fl);
    return FALSE;
}

void EnableDpiAware() {
    HMODULE h = GetModuleHandleW(L"user32.dll");
    if (h) {
        PFN_SetProcessDPIAware fn = (PFN_SetProcessDPIAware)
            GetProcAddress(h, "SetProcessDPIAware");
        if (fn) fn();
    }
}

// ===== 日志 =====
void Log(const wchar_t* fmt, ...) {
    if (g_cfgPath.empty()) return;
    std::wstring lp = g_cfgPath;
    size_t p = lp.find_last_of(L"\\");
    if (p != std::wstring::npos) lp = lp.substr(0, p + 1) + L"log.txt";
    else lp = L"log.txt";

    wchar_t msg[1024];
    va_list args;
    va_start(args, fmt);
    _vsnwprintf(msg, 1024, fmt, args);
    va_end(args);
    msg[1023] = 0;

    SYSTEMTIME st;
    GetLocalTime(&st);
    wchar_t full[1200];
    _snwprintf(full, 1200, L"[%04d-%02d-%02d %02d:%02d:%02d] %s\r\n",
             st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, msg);
    full[1199] = 0;

    HANDLE hFile = CreateFileW(lp.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ,
        NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return;

    int len = WideCharToMultiByte(CP_UTF8, 0, full, -1, NULL, 0, NULL, NULL);
    if (len > 0) {
        char* utf8 = new char[len];
        WideCharToMultiByte(CP_UTF8, 0, full, -1, utf8, len, NULL, NULL);
        DWORD written = 0;
        WriteFile(hFile, utf8, len - 1, &written, NULL);
        delete[] utf8;
    }
    CloseHandle(hFile);
}

// ===== 绘图工具 =====
void FillRectC(HDC hdc, RECT r, COLORREF c) {
    HBRUSH br = CreateSolidBrush(c);
    FillRect(hdc, &r, br);
    DeleteObject(br);
}

void FillRound(HDC hdc, RECT r, int radius, COLORREF c) {
    HBRUSH br = CreateSolidBrush(c);
    HPEN pen = CreatePen(PS_NULL, 0, 0);
    HBRUSH ob = (HBRUSH)SelectObject(hdc, br);
    HPEN op = (HPEN)SelectObject(hdc, pen);
    RoundRect(hdc, r.left, r.top, r.right, r.bottom, radius * 2, radius * 2);
    SelectObject(hdc, ob);
    SelectObject(hdc, op);
    DeleteObject(br);
    DeleteObject(pen);
}

void StrokeRoundW(HDC hdc, RECT r, int radius, int width, COLORREF c) {
    HBRUSH br = (HBRUSH)GetStockObject(NULL_BRUSH);
    HPEN pen = CreatePen(PS_SOLID, width, c);
    HBRUSH ob = (HBRUSH)SelectObject(hdc, br);
    HPEN op = (HPEN)SelectObject(hdc, pen);
    RoundRect(hdc, r.left, r.top, r.right, r.bottom, radius * 2, radius * 2);
    SelectObject(hdc, ob);
    SelectObject(hdc, op);
    DeleteObject(pen);
}

void FillCircle(HDC hdc, int cx, int cy, int r, COLORREF c) {
    HBRUSH br = CreateSolidBrush(c);
    HPEN pen = CreatePen(PS_NULL, 0, 0);
    HBRUSH ob = (HBRUSH)SelectObject(hdc, br);
    HPEN op = (HPEN)SelectObject(hdc, pen);
    Ellipse(hdc, cx - r, cy - r, cx + r + 1, cy + r + 1);
    SelectObject(hdc, ob);
    SelectObject(hdc, op);
    DeleteObject(br);
    DeleteObject(pen);
}

void DrawTextC(HDC hdc, const wchar_t* t, RECT r, HFONT f, COLORREF c, UINT fmt) {
    HFONT of = (HFONT)SelectObject(hdc, f);
    SetTextColor(hdc, c);
    SetBkMode(hdc, TRANSPARENT);
    DrawTextW(hdc, t, -1, &r, fmt);
    SelectObject(hdc, of);
}

// ===== 字体 =====
HFONT CreateUI(int size, int weight) {
    return CreateFontW(S(size), 0, 0, 0, weight, FALSE, FALSE, FALSE,
        DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
        CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Microsoft YaHei UI");
}

// ===== 图标 =====
HICON CreateAppIcon(int size) {
    HDC hdc = CreateCompatibleDC(NULL);
    BITMAPV5HEADER bi;
    ZeroMemory(&bi, sizeof(bi));
    bi.bV5Size = sizeof(bi);
    bi.bV5Width = size; bi.bV5Height = size;
    bi.bV5Planes = 1; bi.bV5BitCount = 32; bi.bV5Compression = BI_BITFIELDS;
    bi.bV5RedMask = 0x00FF0000; bi.bV5GreenMask = 0x0000FF00;
    bi.bV5BlueMask = 0x000000FF; bi.bV5AlphaMask = 0xFF000000;

    void* bits = NULL;
    HBITMAP hBmp = CreateDIBSection(hdc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, &bits, NULL, 0);
    if (!hBmp) { DeleteDC(hdc); return NULL; }

    DWORD* px = (DWORD*)bits;
    double cc = size / 2.0;
    double outerHW = size * 0.46;
    double outerR = size * 0.24;
    double innerHW = size * 0.20;
    double innerR = size * 0.05;

    for (int y = 0; y < size; y++) {
        for (int x = 0; x < size; x++) {
            double fx = x + 0.5, fy = y + 0.5;
            double ox = fabs(fx - cc) - (outerHW - outerR);
            double oy = fabs(fy - cc) - (outerHW - outerR);
            double dOuter;
            if (ox < 0 && oy < 0) dOuter = mymax(ox, oy) - outerR;
            else {
                double dx = mymax(ox, 0.0), dy = mymax(oy, 0.0);
                dOuter = sqrt(dx*dx + dy*dy) - outerR;
            }
            double aOuter = 1.0;
            if (dOuter > 0) aOuter = 0;
            else if (dOuter > -1) aOuter = -dOuter;
            if (aOuter <= 0) { px[y * size + x] = 0; continue; }

            double t = (fx + fy) / (double)(size * 2);
            int cr = (int)(167 - 25 * t);
            int cg = (int)(139 - 25 * t);
            int cb = (int)(250 - 15 * t);

            double ix = fabs(fx - cc) - (innerHW - innerR);
            double iy = fabs(fy - cc) - (innerHW - innerR);
            double dInner;
            if (ix < 0 && iy < 0) dInner = mymax(ix, iy) - innerR;
            else {
                double dx = mymax(ix, 0.0), dy = mymax(iy, 0.0);
                dInner = sqrt(dx*dx + dy*dy) - innerR;
            }
            double mix = 0;
            if (dInner < -1) mix = 1;
            else if (dInner < 0) mix = -dInner;

            cr = (int)(cr * (1 - mix) + 255 * mix);
            cg = (int)(cg * (1 - mix) + 255 * mix);
            cb = (int)(cb * (1 - mix) + 255 * mix);

            BYTE a = (BYTE)(aOuter * 255);
            px[y * size + x] = ((DWORD)a << 24) | ((DWORD)cr << 16) | ((DWORD)cg << 8) | cb;
        }
    }
    DeleteDC(hdc);

    HBITMAP hMask = CreateBitmap(size, size, 1, 1, NULL);
    ICONINFO ii;
    ZeroMemory(&ii, sizeof(ii));
    ii.fIcon = TRUE;
    ii.hbmColor = hBmp;
    ii.hbmMask = hMask;
    HICON icon = CreateIconIndirect(&ii);
    DeleteObject(hBmp);
    DeleteObject(hMask);
    return icon;
}

HICON CreateTrayIcon(int size, int alpha) {
    (void)alpha;
    return CreateAppIcon(size);
}

// ===== 配置 =====
std::wstring GetConfigPath() {
    wchar_t path[MAX_PATH];
    if (FAILED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, path))) return L"";
    std::wstring dir = path;
    dir += L"\\Window3Clear";
    CreateDirectoryW(dir.c_str(), NULL);
    return dir + L"\\config.ini";
}

void ParseHotkey(const std::wstring& s, UINT& mod, UINT& vk, UINT defMod, UINT defKey) {
    mod = 0; vk = 0;
    if (s.empty()) { mod = defMod; vk = defKey; return; }
    std::wstring cur;
    for (size_t i = 0; i <= s.size(); i++) {
        wchar_t c = (i < s.size()) ? s[i] : L'+';
        if (c == L'+') {
            if (cur == L"Ctrl" || cur == L"CTRL" || cur == L"ctrl") mod |= MOD_CONTROL;
            else if (cur == L"Alt" || cur == L"ALT") mod |= MOD_ALT;
            else if (cur == L"Shift" || cur == L"SHIFT") mod |= MOD_SHIFT;
            else if (cur == L"Win" || cur == L"WIN") mod |= MOD_WIN;
            else if (cur == L"Left") vk = VK_LEFT;
            else if (cur == L"Right") vk = VK_RIGHT;
            else if (cur == L"Up") vk = VK_UP;
            else if (cur == L"Down") vk = VK_DOWN;
            else if (cur == L"Space") vk = VK_SPACE;
            else if (cur.length() == 1) {
                wchar_t u = cur[0];
                if (u >= L'a' && u <= L'z') u = u - L'a' + L'A';
                vk = (UINT)u;
            } else if (cur.length() >= 2 && cur[0] == L'F') {
                int n = 0;
                swscanf(cur.c_str() + 1, L"%d", &n);
                if (n >= 1 && n <= 24) vk = VK_F1 + n - 1;
            }
            cur.clear();
        } else cur += c;
    }
    if (vk == 0) vk = defKey;
    if (mod == 0) mod = defMod;
}

void LoadProfiles(const std::wstring& p) {
    g_profiles.clear();
    wchar_t buf[4096];
    DWORD n = GetPrivateProfileSectionW(L"Profiles", buf, 4096, p.c_str());
    if (n > 0) {
        wchar_t* s = buf;
        while (*s) {
            std::wstring line = s;
            size_t eq = line.find(L'=');
            if (eq != std::wstring::npos) {
                std::wstring key = line.substr(0, eq);
                int val = (int)wcstol(line.c_str() + eq + 1, NULL, 10);
                if (val >= MIN_ALPHA && val <= MAX_ALPHA) g_profiles[key] = val;
            }
            s += wcslen(s) + 1;
        }
    }
}

void SaveProfiles(const std::wstring& p) {
    if (!g_cfg.saveProfiles) return;
    WritePrivateProfileStringW(L"Profiles", NULL, NULL, p.c_str());
    for (std::map<std::wstring, int>::iterator it = g_profiles.begin();
         it != g_profiles.end(); ++it) {
        wchar_t val[16];
        wsprintfW(val, L"%d", it->second);
        WritePrivateProfileStringW(L"Profiles", it->first.c_str(), val, p.c_str());
    }
}

void LoadConfig() {
    g_cfgPath = GetConfigPath();
    std::wstring p = g_cfgPath;
    if (p.empty()) {
        g_cfg.darkMode = 1;
        g_cfg.autoRestore = 1;
        g_cfg.firstRun = 1;
        g_cfg.saveProfiles = 1;
        g_cfg.hkModDown = MOD_CONTROL | MOD_ALT; g_cfg.hkKeyDown = VK_LEFT;
        g_cfg.hkModUp = MOD_CONTROL | MOD_ALT;   g_cfg.hkKeyUp = VK_RIGHT;
        g_cfg.hkModReset = MOD_CONTROL | MOD_ALT; g_cfg.hkKeyReset = '0';
        g_cfg.hkModExit = MOD_CONTROL | MOD_ALT; g_cfg.hkKeyExit = 'Q';
        return;
    }
    g_cfg.darkMode = GetPrivateProfileIntW(L"General", L"DarkMode", 1, p.c_str());
    g_cfg.autoRestore = GetPrivateProfileIntW(L"General", L"AutoRestore", 1, p.c_str());
    g_cfg.firstRun = GetPrivateProfileIntW(L"General", L"FirstRun", 1, p.c_str());
    g_cfg.saveProfiles = GetPrivateProfileIntW(L"General", L"SaveProfiles", 1, p.c_str());

    wchar_t buf[256];
    GetPrivateProfileStringW(L"Hotkeys", L"Down", L"Ctrl+Alt+Left", buf, 256, p.c_str());
    ParseHotkey(buf, g_cfg.hkModDown, g_cfg.hkKeyDown, MOD_CONTROL | MOD_ALT, VK_LEFT);
    GetPrivateProfileStringW(L"Hotkeys", L"Up", L"Ctrl+Alt+Right", buf, 256, p.c_str());
    ParseHotkey(buf, g_cfg.hkModUp, g_cfg.hkKeyUp, MOD_CONTROL | MOD_ALT, VK_RIGHT);
    GetPrivateProfileStringW(L"Hotkeys", L"Reset", L"Ctrl+Alt+0", buf, 256, p.c_str());
    ParseHotkey(buf, g_cfg.hkModReset, g_cfg.hkKeyReset, MOD_CONTROL | MOD_ALT, '0');
    GetPrivateProfileStringW(L"Hotkeys", L"Exit", L"Ctrl+Alt+Q", buf, 256, p.c_str());
    ParseHotkey(buf, g_cfg.hkModExit, g_cfg.hkKeyExit, MOD_CONTROL | MOD_ALT, 'Q');

    g_cfg.exclude.clear();
    int cnt = GetPrivateProfileIntW(L"Exclude", L"Count", 0, p.c_str());
    for (int i = 0; i < cnt; i++) {
        wchar_t key[32];
        wsprintfW(key, L"Name%d", i);
        GetPrivateProfileStringW(L"Exclude", key, L"", buf, 256, p.c_str());
        if (buf[0]) g_cfg.exclude.push_back(buf);
    }
    g_cfg.exclude.push_back(L"Program Manager");
    g_cfg.exclude.push_back(L"Windows 输入体验");
    g_cfg.exclude.push_back(L"Windows Input Experience");
    g_cfg.exclude.push_back(L"Microsoft Text Input Application");

    LoadProfiles(p);
}

void SaveConfig() {
    std::wstring p = g_cfgPath;
    if (p.empty()) return;
    WritePrivateProfileStringW(L"General", L"DarkMode", g_cfg.darkMode ? L"1" : L"0", p.c_str());
    WritePrivateProfileStringW(L"General", L"AutoRestore", g_cfg.autoRestore ? L"1" : L"0", p.c_str());
    WritePrivateProfileStringW(L"General", L"FirstRun", L"0", p.c_str());
    WritePrivateProfileStringW(L"General", L"SaveProfiles", g_cfg.saveProfiles ? L"1" : L"0", p.c_str());
    g_cfg.firstRun = 0;
    SaveProfiles(p);
}

void UpdateEditColors() {
    if (g_editBgBrush) {
        DeleteObject(g_editBgBrush);
        g_editBgBrush = NULL;
    }
    g_editBgBrush = CreateSolidBrush(C_EDIT_BG);
    if (g_hSearchEdit) InvalidateRect(g_hSearchEdit, NULL, TRUE);
}

void ApplyTheme() {
    g_theme = g_cfg.darkMode ? g_themeDark : g_themeLight;
    UpdateEditColors();
}

// ===== 进程/类名/Profile =====
std::wstring GetProcessName(HWND hwnd) {
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    if (!pid) return L"";
    HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
    if (!hProc) return L"";
    wchar_t buf[MAX_PATH] = {0};
    DWORD sz = MAX_PATH;
    static PFN_QueryFullProcessImageNameW fn = NULL;
    static bool tried = false;
    if (!tried) {
        tried = true;
        HMODULE hK = GetModuleHandleW(L"kernel32.dll");
        if (hK) {
            void* p = (void*)GetProcAddress(hK, "QueryFullProcessImageNameW");
            fn = reinterpret_cast<PFN_QueryFullProcessImageNameW>(p);
        }
    }
    if (fn) fn(hProc, 0, buf, &sz);
    CloseHandle(hProc);
    if (!buf[0]) return L"";
    std::wstring s = buf;
    size_t p = s.find_last_of(L"\\/");
    if (p != std::wstring::npos) s = s.substr(p + 1);
    return s;
}

std::wstring GetWindowClass(HWND hwnd) {
    wchar_t buf[256] = {0};
    GetClassNameW(hwnd, buf, 256);
    return buf;
}

std::wstring GetProfileKey(HWND hwnd) {
    std::wstring proc = GetProcessName(hwnd);
    std::wstring cls = GetWindowClass(hwnd);
    if (proc.empty()) return L"";
    return proc + L"|" + cls;
}

// ===== 透明度 =====
int GetCurrentAlpha(HWND hwnd) {
    if (!IsWindow(hwnd)) return 255;
    LONG_PTR ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
    if (!(ex & WS_EX_LAYERED)) return 255;
    COLORREF ck = 0;
    BYTE a = 255;
    DWORD fl = 0;
    if (MyGetLWA(hwnd, &ck, &a, &fl) && (fl & LWA_ALPHA)) return (int)a;
    return 255;
}

bool IsOwn(HWND hwnd) {
    if (!hwnd) return true;
    if (hwnd == g_hwnd || (g_hHelp && hwnd == g_hHelp)) return true;
    if (g_hSearchEdit && hwnd == g_hSearchEdit) return true;
    if (g_hMenuWnd && hwnd == g_hMenuWnd) return true;
    return false;
}

void ApplyOpacityRaw(HWND hwnd, int alpha) {
    if (!IsWindow(hwnd) || IsOwn(hwnd)) return;
    if (alpha < MIN_ALPHA) alpha = MIN_ALPHA;
    if (alpha > MAX_ALPHA) alpha = MAX_ALPHA;
    LONG_PTR ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
    bool wasLayered = (ex & WS_EX_LAYERED) != 0;
    if (g_modified.find(hwnd) == g_modified.end()) {
        WindowState st;
        st.wasLayered = wasLayered;
        st.originalAlpha = (BYTE)GetCurrentAlpha(hwnd);
        st.wasTopmost = (ex & WS_EX_TOPMOST) != 0;
        st.clickThrough = false;
        g_modified[hwnd] = st;
    }
    if (!wasLayered) {
        SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex | WS_EX_LAYERED);
        SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
            SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
    }
    SetLayeredWindowAttributes(hwnd, 0, (BYTE)alpha, LWA_ALPHA);
}

void ApplyOpacity(HWND hwnd, int alpha) {
    ApplyOpacityRaw(hwnd, alpha);
    if (g_cfg.saveProfiles && alpha < MAX_ALPHA) {
        std::wstring k = GetProfileKey(hwnd);
        if (!k.empty()) g_profiles[k] = alpha;
    } else if (g_cfg.saveProfiles && alpha == MAX_ALPHA) {
        std::wstring k = GetProfileKey(hwnd);
        if (!k.empty()) g_profiles.erase(k);
    }
}

void RestoreOne(HWND hwnd, const WindowState& st) {
    if (!IsWindow(hwnd)) return;
    if (st.wasLayered) {
        SetLayeredWindowAttributes(hwnd, 0, st.originalAlpha, LWA_ALPHA);
    } else {
        SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA);
        LONG_PTR ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
        if (ex & WS_EX_LAYERED) {
            SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex & ~WS_EX_LAYERED);
            SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
        }
    }
    RedrawWindow(hwnd, NULL, NULL,
        RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE | RDW_ALLCHILDREN);
}

void RestoreAll() {
    std::vector<HWND> keys;
    for (std::map<HWND, WindowState>::iterator it = g_modified.begin();
         it != g_modified.end(); ++it) keys.push_back(it->first);
    for (size_t i = 0; i < keys.size(); i++) {
        std::map<HWND, WindowState>::iterator it = g_modified.find(keys[i]);
        if (it != g_modified.end()) RestoreOne(it->first, it->second);
    }
    g_modified.clear();
}

bool IsExcluded(const std::wstring& title) {
    for (size_t i = 0; i < g_cfg.exclude.size(); i++) {
        if (title.find(g_cfg.exclude[i]) != std::wstring::npos) return true;
    }
    return false;
}

BOOL CALLBACK EnumProc(HWND hwnd, LPARAM lp) {
    if (IsOwn(hwnd)) return TRUE;
    if (!IsWindowVisible(hwnd)) return TRUE;
    if (GetWindow(hwnd, GW_OWNER) != NULL) return TRUE;
    LONG_PTR ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
    if (ex & WS_EX_TOOLWINDOW) return TRUE;
    if (GetWindowTextLengthW(hwnd) == 0) return TRUE;
    wchar_t buf[256];
    GetWindowTextW(hwnd, buf, 256);
    if (buf[0] == 0) return TRUE;
    std::wstring t = buf;
    if (IsExcluded(t)) return TRUE;
    std::vector<HWND>* v = (std::vector<HWND>*)lp;
    v->push_back(hwnd);
    return TRUE;
}

void ApplyProfilesToList() {
    if (!g_cfg.saveProfiles) return;
    for (size_t i = 0; i < g_wins.size(); i++) {
        std::wstring k = GetProfileKey(g_wins[i]);
        if (k.empty()) continue;
        std::map<std::wstring, int>::iterator it = g_profiles.find(k);
        if (it != g_profiles.end() && it->second < MAX_ALPHA) {
            ApplyOpacityRaw(g_wins[i], it->second);
        }
    }
}

void RefreshList() {
    g_wins.clear();
    g_titles.clear();
    EnumWindows(EnumProc, (LPARAM)&g_wins);
    for (size_t i = 0; i < g_wins.size(); i++) {
        wchar_t buf[256];
        GetWindowTextW(g_wins[i], buf, 256);
        g_titles.push_back(buf);
    }
    if (g_selected >= 0) {
        if (g_selected >= (int)g_wins.size()) g_selected = -1;
    }
    ApplyProfilesToList();
}

bool HasTarget() {
    return g_selected >= 0 && g_selected < (int)g_wins.size() && IsWindow(g_wins[g_selected]);
}

// ===== 布局 =====
const RECT& RcClose() {
    static RECT r;
    r.left = S(WIN_W_BASE - 44); r.top = S(14);
    r.right = S(WIN_W_BASE - 20); r.bottom = S(38);
    return r;
}
const RECT& RcMin() {
    static RECT r;
    r.left = S(WIN_W_BASE - 80); r.top = S(14);
    r.right = S(WIN_W_BASE - 56); r.bottom = S(38);
    return r;
}
const RECT& RcTheme() {
    static RECT r;
    r.left = S(WIN_W_BASE - 116); r.top = S(14);
    r.right = S(WIN_W_BASE - 92); r.bottom = S(38);
    return r;
}
const RECT& RcTargetBtn() {
    static RECT r;
    r.left = S(CARD_L_X + 20); r.top = S(L_TARGET_Y);
    r.right = S(CARD_L_X + CARD_L_W - 20); r.bottom = S(L_TARGET_Y + L_TARGET_H);
    return r;
}
const RECT& RcSearchEdit() {
    static RECT r;
    r.left = S(CARD_L_X + 20); r.top = S(L_SEARCH_Y);
    r.right = S(CARD_L_X + CARD_L_W - 20); r.bottom = S(L_SEARCH_Y + L_SEARCH_H);
    return r;
}
const RECT& RcSmallBtn(int i) {
    static RECT r;
    int x = CARD_L_X + 20 + i * (96 + 10);
    r.left = S(x); r.top = S(L_BTNS_Y);
    r.right = S(x + 96); r.bottom = S(L_BTNS_Y + L_BTN_H);
    return r;
}
const RECT& RcTopmostBtn() {
    static RECT r;
    r.left = S(CARD_L_X + 20); r.top = S(L_TOPCT_Y);
    r.right = S(CARD_L_X + 20 + 100); r.bottom = S(L_TOPCT_Y + L_BTN_H);
    return r;
}
const RECT& RcClickThroughBtn() {
    static RECT r;
    r.left = S(CARD_L_X + 20 + 110); r.top = S(L_TOPCT_Y);
    r.right = S(CARD_L_X + 20 + 210); r.bottom = S(L_TOPCT_Y + L_BTN_H);
    return r;
}
const RECT& RcMoreBtn() {
    static RECT r;
    r.left = S(CARD_L_X + 20 + 220); r.top = S(L_TOPCT_Y);
    r.right = S(CARD_L_X + CARD_L_W - 20); r.bottom = S(L_TOPCT_Y + L_BTN_H);
    return r;
}
const RECT& RcCheck() {
    static RECT r;
    r.left = S(CARD_L_X + 20); r.top = S(L_CHECK_Y);
    r.right = S(CARD_L_X + 20 + 300); r.bottom = S(L_CHECK_Y + 24);
    return r;
}
const RECT& RcHelpBtn() {
    static RECT r;
    r.left = S(CARD_L_X + 20); r.top = S(L_HELP_Y);
    r.right = S(CARD_L_X + CARD_L_W - 20); r.bottom = S(L_HELP_Y + L_HELP_H);
    return r;
}
const RECT& RcSlider() {
    static RECT r;
    r.left = S(CARD_R_X + 20); r.top = S(R_SLIDER_Y - 12);
    r.right = S(CARD_R_X + CARD_R_W - 20); r.bottom = S(R_SLIDER_Y + 12);
    return r;
}
const RECT& RcPreset(int i) {
    static RECT r;
    int x = CARD_R_X + 20 + i * (71 + 8);
    r.left = S(x); r.top = S(R_PRESET_Y);
    r.right = S(x + 71); r.bottom = S(R_PRESET_Y + R_PRESET_H);
    return r;
}

int HitTestSmallBtn(POINT pt) {
    for (int i = 0; i < 3; i++) {
        RECT r = RcSmallBtn(i);
        if (PtInRect(&r, pt)) return i;
    }
    return -1;
}

int HitTestPreset(POINT pt) {
    for (int i = 0; i < 4; i++) {
        RECT r = RcPreset(i);
        if (PtInRect(&r, pt)) return i;
    }
    return -1;
}

int SliderXFromValue(int v) {
    RECT sr = RcSlider();
    int r0 = sr.left + S(9);
    int r1 = sr.right - S(9);
    return r0 + (r1 - r0) * (v - MIN_ALPHA) / (MAX_ALPHA - MIN_ALPHA);
}

int ValueFromSliderX(int x) {
    RECT sr = RcSlider();
    int r0 = sr.left + S(9);
    int r1 = sr.right - S(9);
    if (x < r0) x = r0;
    if (x > r1) x = r1;
    int v = MIN_ALPHA + (x - r0) * (MAX_ALPHA - MIN_ALPHA) / (r1 - r0);
    if (v < MIN_ALPHA) v = MIN_ALPHA;
    if (v > MAX_ALPHA) v = MAX_ALPHA;
    return v;
}

// ===== 自定义菜单绘制 =====
void PaintCustomMenu(HWND hwnd) {
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);
    RECT rc;
    GetClientRect(hwnd, &rc);
    int W = rc.right;
    int H = rc.bottom;

    HDC mem = CreateCompatibleDC(hdc);
    HBITMAP bmp = CreateCompatibleBitmap(hdc, W, H);
    HBITMAP ob = (HBITMAP)SelectObject(mem, bmp);
    SetBkMode(mem, TRANSPARENT);

    RECT full = {0, 0, W, H};
    FillRound(mem, full, S(8), C_CARD);
    RECT borderRc = {0, 0, W - 1, H - 1};
    StrokeRoundW(mem, borderRc, S(8), 1, C_CARD_EDGE);

    int y = S(MENU_PAD);
    for (size_t i = 0; i < g_menuItems.size(); i++) {
        MenuItem& item = g_menuItems[i];
        int itemH = item.isSeparator ? S(MENU_SEP_H) : S(MENU_ITEM_H);
        if (y + itemH > H - S(MENU_PAD) + S(MENU_SEP_H)) break;

        if (item.isSeparator) {
            int lineY = y + itemH / 2;
            RECT lineRc = {S(12), lineY, W - S(12), lineY + 1};
            FillRectC(mem, lineRc, C_SEP);
        } else {
            RECT itemRc = {S(4), y, W - S(4), y + itemH};
            bool hover = ((int)i == g_menuHover) && !item.disabled;
            bool sel = item.checked;

            if (hover) {
                FillRound(mem, itemRc, S(6), C_BTN_HOVER);
            } else if (sel) {
                int ar = GetRValue(C_ACCENT);
                int ag = GetGValue(C_ACCENT);
                int ab = GetBValue(C_ACCENT);
                int br = GetRValue(C_CARD);
                int bg = GetGValue(C_CARD);
                int bb = GetBValue(C_CARD);
                COLORREF selBg = RGB((ar + br * 4) / 5, (ag + bg * 4) / 5, (ab + bb * 4) / 5);
                FillRound(mem, itemRc, S(6), selBg);
            }

            if (sel) {
                int cx = S(20);
                int cy = y + itemH / 2;
                HPEN pen = CreatePen(PS_SOLID, 2, C_ACCENT);
                HPEN op = (HPEN)SelectObject(mem, pen);
                MoveToEx(mem, cx - S(4), cy, NULL);
                LineTo(mem, cx - S(1), cy + S(3));
                LineTo(mem, cx + S(4), cy - S(3));
                SelectObject(mem, op);
                DeleteObject(pen);
            }

            COLORREF tc = item.disabled ? C_TEXT_FAINT : (hover ? C_ACCENT : C_TEXT);
            RECT textRc = {S(36), y, W - S(16), y + itemH};
            DrawTextC(mem, item.text.c_str(), textRc, g_fontMenu, tc,
                      DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
        }
        y += itemH;
    }

    BitBlt(hdc, 0, 0, W, H, mem, 0, 0, SRCCOPY);
    SelectObject(mem, ob);
    DeleteObject(bmp);
    DeleteDC(mem);
    EndPaint(hwnd, &ps);
}

int HitTestMenuY(int y) {
    int cur = S(MENU_PAD);
    for (size_t i = 0; i < g_menuItems.size(); i++) {
        int itemH = g_menuItems[i].isSeparator ? S(MENU_SEP_H) : S(MENU_ITEM_H);
        if (y >= cur && y < cur + itemH) return (int)i;
        cur += itemH;
    }
    return -1;
}

LRESULT CALLBACK MenuWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_ERASEBKGND: return 1;
    case WM_PAINT: PaintCustomMenu(hwnd); return 0;

    case WM_MOUSEMOVE: {
        if (!g_menuTracking) {
            TRACKMOUSEEVENT tme;
            tme.cbSize = sizeof(tme); tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd; tme.dwHoverTime = 0;
            TrackMouseEvent(&tme); g_menuTracking = true;
        }
        POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
        int idx = HitTestMenuY(pt.y);
        if (idx >= 0 && (g_menuItems[idx].isSeparator || g_menuItems[idx].disabled)) idx = -1;
        if (idx != g_menuHover) {
            g_menuHover = idx;
            InvalidateRect(hwnd, NULL, FALSE);
        }
        return 0;
    }

    case WM_MOUSELEAVE:
        g_menuTracking = false;
        if (g_menuHover != -1) {
            g_menuHover = -1;
            InvalidateRect(hwnd, NULL, FALSE);
        }
        return 0;

    case WM_LBUTTONDOWN: {
        POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
        int idx = HitTestMenuY(pt.y);
        if (idx >= 0 && !g_menuItems[idx].isSeparator && !g_menuItems[idx].disabled) {
            int id = g_menuItems[idx].id;
            HWND owner = g_hMenuOwner;
            DestroyWindow(hwnd);
            if (owner && IsWindow(owner)) PostMessageW(owner, WM_MENU_SELECTED, (WPARAM)id, 0);
        }
        return 0;
    }

    case WM_RBUTTONDOWN:
    case WM_MBUTTONDOWN:
        DestroyWindow(hwnd);
        return 0;

    case WM_ACTIVATE:
        if (LOWORD(wParam) == WA_INACTIVE) DestroyWindow(hwnd);
        return 0;

    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE) { DestroyWindow(hwnd); return 0; }
        return 0;

    case WM_DESTROY:
        g_hMenuWnd = NULL;
        g_menuHover = -1;
        g_menuTracking = false;
        return 0;
    }
    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void ShowCustomMenu(HWND owner, int screenX, int screenY, int width) {
    if (g_hMenuWnd && IsWindow(g_hMenuWnd)) {
        DestroyWindow(g_hMenuWnd);
        g_hMenuWnd = NULL;
    }
    if (g_menuItems.empty()) return;

    static bool registered = false;
    if (!registered) {
        registered = true;
        WNDCLASSEXW wc;
        ZeroMemory(&wc, sizeof(wc));
        wc.cbSize = sizeof(wc);
        wc.lpfnWndProc = MenuWndProc;
        wc.hInstance = GetModuleHandleW(NULL);
        wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
        wc.hbrBackground = NULL;
        wc.lpszClassName = L"Window3ClearMenuClass";
        RegisterClassExW(&wc);
    }

    int h = S(MENU_PAD) * 2;
    int itemCount = 0, sepCount = 0;
    for (size_t i = 0; i < g_menuItems.size(); i++) {
        if (g_menuItems[i].isSeparator) { h += S(MENU_SEP_H); sepCount++; }
        else { h += S(MENU_ITEM_H); itemCount++; }
    }
    if (h > S(MENU_MAX_H)) h = S(MENU_MAX_H);
    if (itemCount == 0 && sepCount == 0) return;

    int screenW = GetSystemMetrics(SM_CXSCREEN);
    int screenH = GetSystemMetrics(SM_CYSCREEN);
    if (screenX + width > screenW) screenX = screenW - width - 4;
    if (screenX < 0) screenX = 4;
    if (screenY + h > screenH) screenY = screenY - h - S(L_TARGET_H) - 8;
    if (screenY < 0) screenY = 4;

    g_hMenuOwner = owner;
    g_menuHover = -1;

    g_hMenuWnd = CreateWindowExW(
        WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
        L"Window3ClearMenuClass", L"",
        WS_POPUP,
        screenX, screenY, width, h,
        owner, NULL, GetModuleHandleW(NULL), NULL);

    if (g_hMenuWnd) {
        HRGN rgn = CreateRoundRectRgn(0, 0, width + 1, h + 1, S(8) * 2, S(8) * 2);
        SetWindowRgn(g_hMenuWnd, rgn, TRUE);
        ShowWindow(g_hMenuWnd, SW_SHOWNOACTIVATE);
        SetForegroundWindow(g_hMenuWnd);
        UpdateWindow(g_hMenuWnd);
    }
}

// ===== 构建菜单项 =====
void BuildWindowPickerMenu() {
    g_menuItems.clear();

    int matchCount = 0;
    for (size_t i = 0; i < g_wins.size(); i++) {
        // 搜索过滤:匹配窗口标题或进程名
        if (!g_searchText.empty()) {
            std::wstring proc = GetProcessName(g_wins[i]);
            bool match = (g_titles[i].find(g_searchText) != std::wstring::npos) ||
                         (proc.find(g_searchText) != std::wstring::npos);
            if (!match) continue;
        }
        std::wstring t = g_titles[i];
        if (t.length() > 50) t = t.substr(0, 47) + L"...";
        MenuItem it;
        it.text = t;
        it.id = 1000 + (int)i;
        it.checked = ((int)i == g_selected);
        g_menuItems.push_back(it);
        matchCount++;
    }

    if (matchCount == 0) {
        MenuItem it;
        if (!g_searchText.empty()) {
            it.text = L"(没有匹配的窗口)";
        } else {
            it.text = L"(没有可用窗口)";
        }
        it.disabled = true;
        g_menuItems.push_back(it);
    }

    MenuItem sep; sep.isSeparator = true;
    g_menuItems.push_back(sep);

    if (!g_searchText.empty()) {
        MenuItem cl;
        cl.text = L"清除搜索过滤";
        cl.id = ID_SEARCH_CLEAR;
        g_menuItems.push_back(cl);
    }

    MenuItem rf;
    rf.text = L"刷新窗口列表";
    rf.id = ID_REFRESH;
    g_menuItems.push_back(rf);
}

void BuildMoreMenu() {
    g_menuItems.clear();

    MenuItem a;
    a.text = L"应用到同进程所有窗口";
    a.id = ID_MORE_TOP;
    g_menuItems.push_back(a);

    MenuItem b;
    b.text = L"排除此窗口(从列表中隐藏)";
    b.id = ID_MORE_EXCL;
    g_menuItems.push_back(b);

    MenuItem sep1; sep1.isSeparator = true;
    g_menuItems.push_back(sep1);

    MenuItem c;
    c.text = L"5 秒渐隐至 50%";
    c.id = ID_MORE_FADE5;
    g_menuItems.push_back(c);

    MenuItem d;
    d.text = L"10 秒渐隐至 50%";
    d.id = ID_MORE_FADE10;
    g_menuItems.push_back(d);

    MenuItem e;
    e.text = L"30 秒渐隐至 50%";
    e.id = ID_MORE_FADE30;
    g_menuItems.push_back(e);
}

void OpenWindowPickerMenu(HWND hwnd) {
    // 打开菜单前,从编辑框同步一次搜索文字
    if (g_hSearchEdit) {
        wchar_t buf[256] = {0};
        GetWindowTextW(g_hSearchEdit, buf, 256);
        g_searchText = buf;
    }
    BuildWindowPickerMenu();
    RECT rc;
    GetWindowRect(hwnd, &rc);
    int x = rc.left + S(CARD_L_X + 20);
    int y = rc.top + S(L_TARGET_Y + L_TARGET_H + 4);
    int w = S(CARD_L_W - 40);
    ShowCustomMenu(hwnd, x, y, w);
}

void OpenMoreMenu(HWND hwnd) {
    if (!HasTarget()) return;
    BuildMoreMenu();
    RECT rc;
    GetWindowRect(hwnd, &rc);
    int x = rc.left + S(CARD_L_X + 20 + 220);
    int y = rc.top + S(L_TOPCT_Y + L_BTN_H + 4);
    int w = S(CARD_L_W - 40 - 220);
    if (w < S(240)) w = S(240);
    ShowCustomMenu(hwnd, x, y, w);
}

// ===== 卡片与按钮 =====
void DrawCard(HDC mem, RECT r, int radius) {
    FillRound(mem, r, radius, C_CARD);
    StrokeRoundW(mem, r, radius, 1, C_CARD_EDGE);
}

void DrawButton(HDC mem, RECT r, int radius, const wchar_t* label, HFONT font,
                bool hover, bool press, COLORREF textNormal, COLORREF textHover) {
    COLORREF bg;
    if (press) bg = C_BTN_PRESS;
    else if (hover) bg = C_BTN_HOVER;
    else bg = C_BTN;
    FillRound(mem, r, radius, bg);
    StrokeRoundW(mem, r, radius, 1, C_BTN_EDGE);
    COLORREF tc = hover ? textHover : textNormal;
    RECT tr = r;
    DrawTextC(mem, label, tr, font, tc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}

// ===== 主窗口绘制 =====
void PaintMain(HWND hwnd) {
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);

    int WIN_W = S(WIN_W_BASE);
    int WIN_H = S(WIN_H_BASE);
    int TH = S(TITLE_H);

    HDC mem = CreateCompatibleDC(hdc);
    HBITMAP bmp = CreateCompatibleBitmap(hdc, WIN_W, WIN_H);
    HBITMAP ob = (HBITMAP)SelectObject(mem, bmp);
    SetBkMode(mem, TRANSPARENT);

    RECT full = {0, 0, WIN_W, WIN_H};
    FillRectC(mem, full, C_BG);
    FillRectC(mem, (RECT){0, 0, WIN_W, TH}, C_BG_TITLE);

    if (g_appIcon) DrawIconEx(mem, S(20), TH / 2 - S(8), g_appIcon, S(16), S(16), 0, NULL, DI_NORMAL);

    RECT titleText = {S(44), 0, WIN_W - S(140), TH};
    DrawTextC(mem, L"Window3Clear", titleText, g_fontTitle, C_TEXT,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    SIZE szTitle = {S(120), 0};
    {
        HFONT of = (HFONT)SelectObject(mem, g_fontTitle);
        GetTextExtentPoint32W(mem, L"Window3Clear", 12, &szTitle);
        SelectObject(mem, of);
    }
    RECT verRc = {S(44) + szTitle.cx + S(8), 0, WIN_W - S(140), TH};
    DrawTextC(mem, L"V18", verRc, g_fontVersion, C_TEXT_FAINT,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    // 主题按钮
    RECT rTheme = RcTheme();
    int tcx = (rTheme.left + rTheme.right) / 2;
    int tcy = (rTheme.top + rTheme.bottom) / 2;
    if (g_hoverTheme) FillCircle(mem, tcx, tcy, S(12), C_BTN_HOVER);
    {
        COLORREF ic = g_hoverTheme ? C_TEXT : C_TEXT_DIM;
        if (g_cfg.darkMode) {
            int r = S(6);
            HRGN outer = CreateEllipticRgn(tcx - r, tcy - r, tcx + r + 1, tcy + r + 1);
            HRGN inner = CreateEllipticRgn(tcx - r + S(4), tcy - r - S(2),
                                           tcx + r + S(4) + 1, tcy + r - S(2) + 1);
            CombineRgn(outer, outer, inner, RGN_DIFF);
            HBRUSH br = CreateSolidBrush(ic);
            FillRgn(mem, outer, br);
            DeleteObject(br); DeleteObject(inner); DeleteObject(outer);
        } else {
            FillCircle(mem, tcx, tcy, S(4), ic);
            HPEN pen = CreatePen(PS_SOLID, 2, ic);
            HPEN op = (HPEN)SelectObject(mem, pen);
            for (int k = 0; k < 8; k++) {
                double ang = k * 3.14159 / 4;
                MoveToEx(mem, tcx + (int)(cos(ang) * S(6)), tcy + (int)(sin(ang) * S(6)), NULL);
                LineTo(mem, tcx + (int)(cos(ang) * S(8)), tcy + (int)(sin(ang) * S(8)));
            }
            SelectObject(mem, op); DeleteObject(pen);
        }
    }

    // 最小化
    RECT rMin = RcMin();
    if (g_hoverMin) FillCircle(mem, (rMin.left + rMin.right) / 2,
                               (rMin.top + rMin.bottom) / 2, S(12), C_BTN_HOVER);
    {
        int mx = (rMin.left + rMin.right) / 2, my = (rMin.top + rMin.bottom) / 2;
        HPEN pen = CreatePen(PS_SOLID, 1, g_hoverMin ? C_TEXT : C_TEXT_DIM);
        HPEN op = (HPEN)SelectObject(mem, pen);
        MoveToEx(mem, mx - S(5), my, NULL); LineTo(mem, mx + S(6), my);
        SelectObject(mem, op); DeleteObject(pen);
    }
    // 关闭
    RECT rClose = RcClose();
    if (g_hoverClose) FillCircle(mem, (rClose.left + rClose.right) / 2,
                                 (rClose.top + rClose.bottom) / 2, S(12), C_CLOSE_HOV);
    {
        int cx = (rClose.left + rClose.right) / 2, cy = (rClose.top + rClose.bottom) / 2;
        HPEN pen = CreatePen(PS_SOLID, 1, g_hoverClose ? RGB(255,255,255) : C_TEXT_DIM);
        HPEN op = (HPEN)SelectObject(mem, pen);
        MoveToEx(mem, cx - S(4), cy - S(4), NULL); LineTo(mem, cx + S(5), cy + S(5));
        MoveToEx(mem, cx - S(4), cy + S(5), NULL); LineTo(mem, cx + S(5), cy - S(4));
        SelectObject(mem, op); DeleteObject(pen);
    }

    // ===== 左卡片 =====
    RECT lcard = {S(CARD_L_X), S(CARD_Y), S(CARD_L_X + CARD_L_W), S(CARD_Y + CARD_H)};
    DrawCard(mem, lcard, S(8));

    RECT lLabel = {S(CARD_L_X + 20), S(L_LABEL_Y), S(CARD_L_X + CARD_L_W - 20), S(L_LABEL_Y + 18)};
    DrawTextC(mem, L"当前目标窗口", lLabel, g_fontSmall, C_TEXT_DIM,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    // 目标按钮
    RECT tb = RcTargetBtn();
    bool hasTarget = HasTarget();
    {
        COLORREF bg = g_hoverTarget ? C_BTN_HOVER : C_BTN;
        FillRound(mem, tb, S(6), bg);
        StrokeRoundW(mem, tb, S(6), 1, g_hoverTarget ? C_ACCENT : C_BTN_EDGE);
    }
    RECT tbText = {tb.left + S(14), tb.top, tb.right - S(30), tb.bottom};
    if (hasTarget) {
        DrawTextC(mem, g_titles[g_selected].c_str(), tbText, g_fontNormal, C_TEXT,
                  DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
    } else {
        DrawTextC(mem, L"点击选择目标窗口", tbText, g_fontNormal, C_TEXT_DIM,
                  DT_LEFT | DT_VCENTER | DT_SINGLELINE);
    }
    {
        int cx = tb.right - S(16), cy = (tb.top + tb.bottom) / 2;
        COLORREF c = g_hoverTarget ? C_ACCENT : C_TEXT_DIM;
        HBRUSH br = CreateSolidBrush(c);
        HPEN pen = CreatePen(PS_NULL, 0, 0);
        HBRUSH ob2 = (HBRUSH)SelectObject(mem, br);
        HPEN op2 = (HPEN)SelectObject(mem, pen);
        POINT pts[3] = {{cx - S(4), cy - S(2)}, {cx + S(4), cy - S(2)}, {cx, cy + S(3)}};
        Polygon(mem, pts, 3);
        SelectObject(mem, ob2); SelectObject(mem, op2);
        DeleteObject(br); DeleteObject(pen);
    }

    // 搜索框背景(EDIT 覆盖在上面,这里只画一个位置留白,防抖)
    // 不画,让 EDIT 自绘

    // 三个小按钮
    const wchar_t* labels[3] = {L"刷新", L"恢复", L"全恢复"};
    for (int i = 0; i < 3; i++) {
        RECT r = RcSmallBtn(i);
        DrawButton(mem, r, S(6), labels[i], g_fontNormal,
                   g_hoverBtn == i, g_pressBtn == i, C_BTN_TEXT, C_ACCENT);
    }

    bool topOn = hasTarget && ((GetWindowLongPtrW(g_wins[g_selected], GWL_EXSTYLE) & WS_EX_TOPMOST) != 0);
    bool ctOn  = hasTarget && ((GetWindowLongPtrW(g_wins[g_selected], GWL_EXSTYLE) & WS_EX_TRANSPARENT) != 0);

    {
        RECT r = RcTopmostBtn();
        COLORREF bg = topOn ? C_ACCENT : (g_hoverTopmost ? C_BTN_HOVER : C_BTN);
        FillRound(mem, r, S(6), bg);
        StrokeRoundW(mem, r, S(6), 1, topOn ? C_ACCENT : (g_hoverTopmost ? C_ACCENT : C_BTN_EDGE));
        COLORREF tc = topOn ? RGB(255,255,255) : (g_hoverTopmost ? C_TEXT : C_TEXT_2);
        RECT tr = r;
        DrawTextC(mem, L"置顶", tr, g_fontNormal, tc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
    }
    {
        RECT r = RcClickThroughBtn();
        COLORREF bg = ctOn ? C_ACCENT : (g_hoverClickThrough ? C_BTN_HOVER : C_BTN);
        FillRound(mem, r, S(6), bg);
        StrokeRoundW(mem, r, S(6), 1, ctOn ? C_ACCENT : (g_hoverClickThrough ? C_ACCENT : C_BTN_EDGE));
        COLORREF tc = ctOn ? RGB(255,255,255) : (g_hoverClickThrough ? C_TEXT : C_TEXT_2);
        RECT tr = r;
        DrawTextC(mem, L"穿透", tr, g_fontNormal, tc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
    }
    {
        RECT r = RcMoreBtn();
        DrawButton(mem, r, S(6), L"更多...", g_fontNormal,
                   g_hoverMore, false, C_BTN_TEXT, C_ACCENT);
    }

    RECT chk = RcCheck();
    RECT box = {chk.left, chk.top + S(2), chk.left + S(18), chk.top + S(20)};
    if (g_checkOn) {
        FillRound(mem, box, S(4), C_CHECK_ON);
        HPEN pen = CreatePen(PS_SOLID, 2, RGB(255, 255, 255));
        HPEN op2 = (HPEN)SelectObject(mem, pen);
        int bx = box.left + S(4), by = box.top + S(10);
        MoveToEx(mem, bx, by, NULL);
        LineTo(mem, bx + S(3), by + S(4));
        LineTo(mem, bx + S(10), by - S(4));
        SelectObject(mem, op2); DeleteObject(pen);
    } else {
        FillRound(mem, box, S(4), g_hoverCheck ? C_BTN_HOVER : C_BTN);
        StrokeRoundW(mem, box, S(4), 1, C_BTN_EDGE);
    }
    RECT chkText = {box.right + S(10), chk.top, chk.right, chk.bottom};
    DrawTextC(mem, L"退出时自动恢复所有窗口", chkText, g_fontNormal, C_TEXT_2,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    RECT hb = RcHelpBtn();
    DrawButton(mem, hb, S(6), L"查看使用说明", g_fontNormal,
               g_hoverHelp, false, C_BTN_TEXT, C_ACCENT);

    // ===== 右卡片 =====
    RECT rcard = {S(CARD_R_X), S(CARD_Y), S(CARD_R_X + CARD_R_W), S(CARD_Y + CARD_H)};
    DrawCard(mem, rcard, S(8));

    RECT rLabel = {S(CARD_R_X + 20), S(R_LABEL_Y), S(CARD_R_X + CARD_R_W - 20), S(R_LABEL_Y + 18)};
    DrawTextC(mem, L"透明度", rLabel, g_fontSmall, C_TEXT_DIM,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    wchar_t numStr[16];
    int pct = (g_alpha * 100 + 127) / 255;
    wsprintfW(numStr, L"%d", pct);
    RECT numRc = {S(CARD_R_X + 20), S(R_NUM_Y), S(CARD_R_X + CARD_R_W - 40), S(R_NUM_Y + R_NUM_H)};
    {
        HFONT of = (HFONT)SelectObject(mem, g_fontBig);
        SetTextColor(mem, hasTarget ? C_ACCENT : C_TEXT_FAINT);
        SetBkMode(mem, TRANSPARENT);
        DrawTextW(mem, numStr, -1, &numRc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE);
        SelectObject(mem, of);
    }
    {
        RECT pctRc = {S(CARD_R_X + CARD_R_W - 40), S(R_NUM_Y + 50), S(CARD_R_X + CARD_R_W - 20), S(R_NUM_Y + R_NUM_H)};
        DrawTextC(mem, L"%", pctRc, g_fontPercent, hasTarget ? C_ACCENT : C_TEXT_FAINT,
                  DT_LEFT | DT_BOTTOM | DT_SINGLELINE);
    }

    RECT sr = RcSlider();
    int knobX = SliderXFromValue(g_alpha);
    int cy = (sr.top + sr.bottom) / 2;
    int sh = S(4);
    int trackL = sr.left + S(8);
    int trackR = sr.right - S(8);

    for (int i = 1; i <= 3; i++) {
        int v = MIN_ALPHA + (MAX_ALPHA - MIN_ALPHA) * i / 4;
        int x = SliderXFromValue(v);
        FillCircle(mem, x, cy, S(2), C_BTN_EDGE);
    }

    RECT trackBg = {trackL, cy - sh/2, trackR, cy + sh/2};
    FillRound(mem, trackBg, sh/2, C_BTN_PRESS);

    COLORREF accentC = hasTarget ? C_ACCENT : C_ACCENT_DIM;
    RECT trackFg = {trackL, cy - sh/2, knobX, cy + sh/2};
    if (trackFg.right > trackFg.left && hasTarget) {
        FillRound(mem, trackFg, sh/2, accentC);
    }

    for (int i = 1; i <= 3; i++) {
        int v = MIN_ALPHA + (MAX_ALPHA - MIN_ALPHA) * i / 4;
        int x = SliderXFromValue(v);
        FillCircle(mem, x, cy, S(2), hasTarget ? RGB(255,255,255) : C_TEXT_FAINT);
    }

    int kr = (g_draggingSlider || g_hoverSlider) ? S(9) : S(8);
    FillCircle(mem, knobX, cy, kr, hasTarget ? RGB(255,255,255) : RGB(150,150,150));
    if (hasTarget) {
        HBRUSH br = (HBRUSH)GetStockObject(NULL_BRUSH);
        HPEN pen = CreatePen(PS_SOLID, 2, C_ACCENT);
        HBRUSH ob2 = (HBRUSH)SelectObject(mem, br);
        HPEN op2 = (HPEN)SelectObject(mem, pen);
        Ellipse(mem, knobX - kr, cy - kr, knobX + kr + 1, cy + kr + 1);
        SelectObject(mem, ob2); SelectObject(mem, op2);
        DeleteObject(pen);
    }

    if (g_draggingSlider) {
        wchar_t buf[32];
        wsprintfW(buf, L"%d%%", pct);
        SIZE sz;
        {
            HFONT of = (HFONT)SelectObject(mem, g_fontBubble);
            GetTextExtentPoint32W(mem, buf, (int)wcslen(buf), &sz);
            SelectObject(mem, of);
        }
        int bw = sz.cx + S(24);
        int bh = S(32);
        int bx = knobX - bw / 2;
        int by = cy - S(50);
        RECT bubble = {bx, by, bx + bw, by + bh};
        FillRound(mem, bubble, S(6), C_ACCENT);
        DrawTextC(mem, buf, bubble, g_fontBubble, RGB(255,255,255),
                  DT_CENTER | DT_VCENTER | DT_SINGLELINE);
    }

    const wchar_t* presets[4] = {L"25%", L"50%", L"75%", L"100%"};
    for (int i = 0; i < 4; i++) {
        RECT r = RcPreset(i);
        DrawButton(mem, r, S(6), presets[i], g_fontNormal,
                   g_hoverPreset == i, g_pressPreset == i, C_BTN_TEXT, C_ACCENT);
    }

    RECT hint = {S(24), S(WIN_H_BASE - 32), S(WIN_W_BASE - 24), S(WIN_H_BASE - 8)};
    DrawTextC(mem,
        L"提示:点右上角 X 只是缩到托盘。想真正退出并恢复所有窗口,请用托盘右键菜单里的“退出”。",
        hint, g_fontSmall, C_TEXT_FAINT,
        DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);

    BitBlt(hdc, 0, 0, WIN_W, WIN_H, mem, 0, 0, SRCCOPY);

    SelectObject(mem, ob);
    DeleteObject(bmp);
    DeleteDC(mem);
    EndPaint(hwnd, &ps);
}

// ===== 使用说明 =====
const wchar_t* g_helpLines[] = {
    L"# Window3Clear - V18 使用说明",
    L"",
    L"## 一、快速上手",
    L"",
    L"1. 点击「当前目标窗口」按钮,弹出下拉菜单选择",
    L"2. 拖动滑块调整透明度,或点 25% / 50% / 75% / 100% 预设",
    L"3. 想恢复原样,点「恢复」或「全恢复」",
    L"",
    L"## 二、快捷键",
    L"",
    L"- Ctrl + Alt + 左方向键    让前台窗口更透明",
    L"- Ctrl + Alt + 右方向键    让前台窗口更不透明",
    L"- Ctrl + Alt + 数字 0      恢复所有窗口",
    L"- Ctrl + Alt + Q           退出程序",
    L"- Ctrl + Shift + 1/2/3/4   快速应用 25/50/75/100%",
    L"",
    L"## 三、更多功能",
    L"",
    L"- 搜索进程              在左卡片搜索框里输入,实时过滤窗口菜单",
    L"- 应用到同进程所有窗口    对同一程序的所有窗口统一应用透明度",
    L"- 排除此窗口              从列表中隐藏,可在 config.ini 恢复",
    L"- 定时渐隐                在指定时间内平滑过渡到 50%",
    L"",
    L"## 四、记忆功能",
    L"",
    L"程序会自动按「进程名+窗口类名」记住每个窗口的透明度,重启后自动恢复。",
    L"配置文件在 %APPDATA%\\Window3Clear\\config.ini,日志在同目录 log.txt。",
    L"",
    L"## 五、注意事项",
    L"",
    L"- 部分 UWP 应用、全屏游戏、任务管理器无法调整透明度",
    L"- 想调整管理员权限的窗口,本程序也需以管理员身份运行",
    NULL
};

void PaintHelp(HWND hwnd) {
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);

    int HW = S(HELP_W_BASE);
    int HH = S(HELP_H_BASE);
    int TH = S(TITLE_H);

    HDC mem = CreateCompatibleDC(hdc);
    HBITMAP bmp = CreateCompatibleBitmap(hdc, HW, HH);
    HBITMAP ob = (HBITMAP)SelectObject(mem, bmp);
    SetBkMode(mem, TRANSPARENT);

    RECT full = {0, 0, HW, HH};
    FillRectC(mem, full, C_BG);
    FillRectC(mem, (RECT){0, 0, HW, TH}, C_BG_TITLE);
    RECT sep = {0, TH - 1, HW, TH};
    FillRectC(mem, sep, C_SEP);

    RECT ht = {S(24), 0, HW - S(60), TH};
    DrawTextC(mem, L"使用说明", ht, g_fontTitle, C_TEXT,
              DT_LEFT | DT_VCENTER | DT_SINGLELINE);

    RECT rClose = {HW - S(44), S(14), HW - S(20), S(38)};
    if (g_helpHoverClose) FillCircle(mem, (rClose.left + rClose.right) / 2,
                                     (rClose.top + rClose.bottom) / 2, S(12), C_CLOSE_HOV);
    {
        int cx = (rClose.left + rClose.right) / 2, cy = (rClose.top + rClose.bottom) / 2;
        HPEN pen = CreatePen(PS_SOLID, 1, g_helpHoverClose ? RGB(255,255,255) : C_TEXT_DIM);
        HPEN op = (HPEN)SelectObject(mem, pen);
        MoveToEx(mem, cx - S(4), cy - S(4), NULL); LineTo(mem, cx + S(5), cy + S(5));
        MoveToEx(mem, cx - S(4), cy + S(5), NULL); LineTo(mem, cx + S(5), cy - S(4));
        SelectObject(mem, op); DeleteObject(pen);
    }

    HRGN rgn = CreateRectRgn(0, TH, HW, HH);
    SelectClipRgn(mem, rgn);

    int y = TH + S(20) - g_helpScroll;
    int contentX = S(32);

    for (int i = 0; g_helpLines[i]; i++) {
        const wchar_t* line = g_helpLines[i];
        int lineH = S(24);
        HFONT f = g_fontHelpBody;
        COLORREF c = C_TEXT_2;
        const wchar_t* drawText = line;
        int textX = contentX;

        if (line[0] == L'#' && line[1] == L' ') {
            drawText = line + 2; lineH = S(44); f = g_fontHelpH1; c = C_TEXT;
        } else if (line[0] == L'#' && line[1] == L'#' && line[2] == L' ') {
            drawText = line + 3; lineH = S(36); f = g_fontHelpH2; c = C_ACCENT;
        } else if (line[0] == L'-' && line[1] == L' ') {
            drawText = line + 2; lineH = S(30);
            FillCircle(mem, contentX + S(4), y + lineH / 2, S(3), C_ACCENT);
            textX = contentX + S(20);
        } else if (line[0] == 0) {
            lineH = S(12);
        }

        RECT r = {textX, y, HW - S(32), y + lineH};
        DrawTextC(mem, drawText, r, f, c, DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS);
        y += lineH;
    }

    SelectClipRgn(mem, NULL);
    DeleteObject(rgn);

    BitBlt(hdc, 0, 0, HW, HH, mem, 0, 0, SRCCOPY);
    SelectObject(mem, ob);
    DeleteObject(bmp);
    DeleteDC(mem);
    EndPaint(hwnd, &ps);
}

LRESULT CALLBACK HelpWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_CREATE:
        SetWindowRgn(hwnd, CreateRoundRectRgn(0, 0, S(HELP_W_BASE) + 1, S(HELP_H_BASE) + 1,
            S(CORNER_R) * 2, S(CORNER_R) * 2), TRUE);
        return 0;
    case WM_PAINT: PaintHelp(hwnd); return 0;
    case WM_ERASEBKGND: return 1;

    case WM_MOUSEMOVE: {
        if (!g_helpTracking) {
            TRACKMOUSEEVENT tme;
            tme.cbSize = sizeof(tme); tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd; tme.dwHoverTime = 0;
            TrackMouseEvent(&tme); g_helpTracking = true;
        }
        POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
        if (g_helpDragging) {
            POINT c; GetCursorPos(&c);
            SetWindowPos(hwnd, NULL, c.x - g_helpDragOffset.x, c.y - g_helpDragOffset.y,
                0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
            return 0;
        }
        RECT rc = {S(HELP_W_BASE) - S(44), S(14), S(HELP_W_BASE) - S(20), S(38)};
        bool h = PtInRect(&rc, pt) != 0;
        if (h != g_helpHoverClose) { g_helpHoverClose = h; InvalidateRect(hwnd, NULL, FALSE); }
        return 0;
    }
    case WM_MOUSELEAVE:
        g_helpTracking = false;
        if (g_helpHoverClose) { g_helpHoverClose = false; InvalidateRect(hwnd, NULL, FALSE); }
        return 0;

    case WM_LBUTTONDOWN: {
        POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
        RECT rc = {S(HELP_W_BASE) - S(44), S(14), S(HELP_W_BASE) - S(20), S(38)};
        if (PtInRect(&rc, pt)) { DestroyWindow(hwnd); return 0; }
        if (pt.y < S(TITLE_H)) {
            g_helpDragging = true;
            SetCapture(hwnd);
            POINT c; GetCursorPos(&c);
            RECT wr; GetWindowRect(hwnd, &wr);
            g_helpDragOffset.x = c.x - wr.left;
            g_helpDragOffset.y = c.y - wr.top;
            return 0;
        }
        return 0;
    }
    case WM_LBUTTONUP:
        if (g_helpDragging) { g_helpDragging = false; ReleaseCapture(); }
        return 0;

    case WM_MOUSEWHEEL: {
        int delta = GET_WHEEL_DELTA_WPARAM(wParam);
        int totalH = 0;
        for (int i = 0; g_helpLines[i]; i++) {
            const wchar_t* line = g_helpLines[i];
            if (line[0] == L'#' && line[1] == L' ') totalH += S(44);
            else if (line[0] == L'#' && line[1] == L'#' && line[2] == L' ') totalH += S(36);
            else if (line[0] == L'-' && line[1] == L' ') totalH += S(30);
            else if (line[0] == 0) totalH += S(12);
            else totalH += S(24);
        }
        totalH += S(40);
        int maxScroll = totalH - (S(HELP_H_BASE) - S(TITLE_H));
        if (maxScroll < 0) maxScroll = 0;
        if (delta > 0) g_helpScroll -= S(40); else g_helpScroll += S(40);
        if (g_helpScroll < 0) g_helpScroll = 0;
        if (g_helpScroll > maxScroll) g_helpScroll = maxScroll;
        InvalidateRect(hwnd, NULL, FALSE);
        return 0;
    }
    case WM_DESTROY:
        g_hHelp = NULL; g_helpScroll = 0;
        return 0;
    }
    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void OpenHelpWindow() {
    if (g_hHelp && IsWindow(g_hHelp)) {
        ShowWindow(g_hHelp, SW_SHOW);
        SetForegroundWindow(g_hHelp);
        return;
    }
    int sx = (GetSystemMetrics(SM_CXSCREEN) - S(HELP_W_BASE)) / 2;
    int sy = (GetSystemMetrics(SM_CYSCREEN) - S(HELP_H_BASE)) / 2;
    g_hHelp = CreateWindowExW(WS_EX_TOOLWINDOW,
        L"Window3ClearHelpClass", L"使用说明", WS_POPUP,
        sx, sy, S(HELP_W_BASE), S(HELP_H_BASE),
        g_hwnd, NULL, GetModuleHandleW(NULL), NULL);
    if (g_hHelp) {
        ShowWindow(g_hHelp, SW_SHOW);
        UpdateWindow(g_hHelp);
        SetForegroundWindow(g_hHelp);
    }
}

// ===== 托盘 =====
void AddTray(HWND hwnd) {
    ZeroMemory(&g_nid, sizeof(g_nid));
    g_nid.cbSize = sizeof(g_nid);
    g_nid.hWnd = hwnd;
    g_nid.uID = 1;
    g_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
    g_nid.uCallbackMessage = WM_TRAYICON;
    g_nid.hIcon = g_appIcon ? g_appIcon : LoadIconW(NULL, IDI_APPLICATION);
    lstrcpyW(g_nid.szTip, L"Window3Clear - V18");
    if (Shell_NotifyIconW(NIM_ADD, &g_nid)) g_trayAdded = true;
}

void RemoveTray() {
    if (g_trayAdded) { Shell_NotifyIconW(NIM_DELETE, &g_nid); g_trayAdded = false; }
}

void UpdateTrayIcon(HWND hwnd, int alpha) {
    (void)hwnd;
    if (!g_trayAdded) return;
    if (alpha == g_trayIconAlpha) return;
    g_trayIconAlpha = alpha;
    if (g_trayIcon) DestroyIcon(g_trayIcon);
    g_trayIcon = CreateTrayIcon(GetSystemMetrics(SM_CXSMICON), alpha);
    if (g_trayIcon) {
        g_nid.uFlags = NIF_ICON | NIF_TIP;
        g_nid.hIcon = g_trayIcon;
        wchar_t tip[128];
        int pct = (alpha * 100 + 127) / 255;
        wsprintfW(tip, L"Window3Clear - V18\n当前透明度 %d%%", pct);
        lstrcpyW(g_nid.szTip, tip);
        Shell_NotifyIconW(NIM_MODIFY, &g_nid);
    }
}

// ===== 目标窗口操作 =====
void ToggleTopmost() {
    if (!HasTarget()) return;
    HWND t = g_wins[g_selected];
    LONG_PTR ex = GetWindowLongPtrW(t, GWL_EXSTYLE);
    bool isTop = (ex & WS_EX_TOPMOST) != 0;
    SetWindowPos(t, isTop ? HWND_NOTOPMOST : HWND_TOPMOST,
                 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
    Log(L"置顶 %s:%s", isTop ? L"关闭" : L"开启", g_titles[g_selected].c_str());
}

void ToggleClickThrough() {
    if (!HasTarget()) return;
    HWND t = g_wins[g_selected];
    LONG_PTR ex = GetWindowLongPtrW(t, GWL_EXSTYLE);
    bool ct = (ex & WS_EX_TRANSPARENT) != 0;
    if (ct) ex &= ~WS_EX_TRANSPARENT;
    else     ex |= WS_EX_TRANSPARENT;
    SetWindowLongPtrW(t, GWL_EXSTYLE, ex | WS_EX_LAYERED);
    SetWindowPos(t, NULL, 0, 0, 0, 0,
        SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
    Log(L"穿透 %s:%s", ct ? L"关闭" : L"开启", g_titles[g_selected].c_str());
}

void NudgeAlpha(int delta) {
    if (!HasTarget()) return;
    g_alpha += delta;
    if (g_alpha < MIN_ALPHA) g_alpha = MIN_ALPHA;
    if (g_alpha > MAX_ALPHA) g_alpha = MAX_ALPHA;
    ApplyOpacity(g_wins[g_selected], g_alpha);
    UpdateTrayIcon(g_hwnd, g_alpha);
    InvalidateRect(g_hwnd, NULL, FALSE);
}

void ApplyPreset(int idx) {
    if (!HasTarget()) return;
    int vals[4] = {64, 128, 191, 255};
    if (idx < 0 || idx > 3) return;
    g_alpha = vals[idx];
    ApplyOpacity(g_wins[g_selected], g_alpha);
    UpdateTrayIcon(g_hwnd, g_alpha);
    InvalidateRect(g_hwnd, NULL, FALSE);
    Log(L"预设 %d%% → %s", (g_alpha * 100 + 127) / 255, g_titles[g_selected].c_str());
}

// ===== 处理菜单选中 =====
void OnMenuSelected(HWND hwnd, int id) {
    if (id >= 1000) {
        int idx = id - 1000;
        if (idx >= 0 && idx < (int)g_wins.size()) {
            g_selected = idx;
            g_alpha = GetCurrentAlpha(g_wins[idx]);
            if (g_alpha < MIN_ALPHA) g_alpha = MIN_ALPHA;
            if (g_alpha > MAX_ALPHA) g_alpha = MAX_ALPHA;
            InvalidateRect(hwnd, NULL, FALSE);
        }
        return;
    }
    switch (id) {
    case ID_REFRESH:
        RefreshList();
        InvalidateRect(hwnd, NULL, FALSE);
        Log(L"刷新列表");
        break;

    case ID_SEARCH_CLEAR:
        if (g_hSearchEdit) SetWindowTextW(g_hSearchEdit, L"");
        g_searchText.clear();
        InvalidateRect(hwnd, NULL, FALSE);
        break;

    case ID_MORE_TOP: {
        if (!HasTarget()) break;
        std::wstring key = GetProfileKey(g_wins[g_selected]);
        int applied = 0;
        for (size_t i = 0; i < g_wins.size(); i++) {
            if (GetProfileKey(g_wins[i]) == key) {
                ApplyOpacityRaw(g_wins[i], g_alpha);
                applied++;
            }
        }
        wchar_t msg[64];
        wsprintfW(msg, L"已应用到 %d 个同类窗口", applied);
        MessageBoxW(hwnd, msg, L"提示", MB_OK | MB_ICONINFORMATION);
        break;
    }

    case ID_MORE_EXCL: {
        if (!HasTarget()) break;
        std::wstring title = g_titles[g_selected];
        g_cfg.exclude.push_back(title);
        std::wstring p = g_cfgPath;
        int cnt = GetPrivateProfileIntW(L"Exclude", L"Count", 0, p.c_str());
        wchar_t key[32], val[256];
        wsprintfW(key, L"Name%d", cnt);
        lstrcpynW(val, title.c_str(), 256);
        WritePrivateProfileStringW(L"Exclude", key, val, p.c_str());
        wsprintfW(val, L"%d", cnt + 1);
        WritePrivateProfileStringW(L"Exclude", L"Count", val, p.c_str());
        g_selected = -1; g_alpha = MAX_ALPHA;
        RefreshList();
        InvalidateRect(hwnd, NULL, FALSE);
        break;
    }

    case ID_MORE_FADE5:
    case ID_MORE_FADE10:
    case ID_MORE_FADE30: {
        if (!HasTarget()) break;
        int secs = (id == ID_MORE_FADE5) ? 5 : (id == ID_MORE_FADE10 ? 10 : 30);
        g_fadeHwnd = g_wins[g_selected];
        g_fadeFrom = GetCurrentAlpha(g_fadeHwnd);
        g_fadeTo = 128;
        g_fadeTotalSteps = secs * 10;
        g_fadeSteps = 0;
        g_fadeActive = true;
        SetTimer(hwnd, TIMER_FADE, 100, NULL);
        break;
    }
    }
}

// ===== 主窗口过程 =====
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {

    case WM_CREATE:
        g_hwnd = hwnd;
        g_fontTitle     = CreateUI(-16, FW_SEMIBOLD);
        g_fontVersion   = CreateUI(-12, FW_NORMAL);
        g_fontBig       = CreateUI(-72, FW_SEMIBOLD);
        g_fontPercent   = CreateUI(-20, FW_SEMIBOLD);
        g_fontNormal    = CreateUI(-14, FW_NORMAL);
        g_fontSmall     = CreateUI(-12, FW_NORMAL);
        g_fontTiny      = CreateUI(-11, FW_NORMAL);
        g_fontBubble    = CreateUI(-16, FW_SEMIBOLD);
        g_fontMenu      = CreateUI(-14, FW_NORMAL);
        g_fontHelpH1    = CreateUI(-22, FW_SEMIBOLD);
        g_fontHelpH2    = CreateUI(-16, FW_SEMIBOLD);
        g_fontHelpBody  = CreateUI(-14, FW_NORMAL);

        g_editBgBrush = CreateSolidBrush(C_EDIT_BG);

        // 创建搜索框
        {
            RECT er = RcSearchEdit();
            g_hSearchEdit = CreateWindowExW(
                0, L"EDIT", L"",
                WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL,
                er.left, er.top, er.right - er.left, er.bottom - er.top,
                hwnd, (HMENU)ID_SEARCH_EDIT, NULL, NULL);
            if (g_hSearchEdit) {
                SendMessageW(g_hSearchEdit, WM_SETFONT, (WPARAM)g_fontNormal, TRUE);
                SendMessageW(g_hSearchEdit, EM_SETCUEBANNER, TRUE, (LPARAM)L"搜索进程...");
                // 圆角
                HRGN hr = CreateRoundRectRgn(0, 0,
                    (er.right - er.left) + 1, (er.bottom - er.top) + 1,
                    S(6) * 2, S(6) * 2);
                SetWindowRgn(g_hSearchEdit, hr, TRUE);
            }
        }

        SetTimer(hwnd, TIMER_CLEANUP, 2000, NULL);
        return 0;

    case WM_PAINT: PaintMain(hwnd); return 0;
    case WM_ERASEBKGND: return 1;

    case WM_CTLCOLOREDIT: {
        HDC hdcEdit = (HDC)wParam;
        SetTextColor(hdcEdit, C_TEXT);
        SetBkColor(hdcEdit, C_EDIT_BG);
        if (!g_editBgBrush) g_editBgBrush = CreateSolidBrush(C_EDIT_BG);
        return (LRESULT)g_editBgBrush;
    }

    case WM_COMMAND: {
        int id = LOWORD(wParam);
        int code = HIWORD(wParam);
        if (id == ID_SEARCH_EDIT) {
            if (code == EN_CHANGE) {
                wchar_t buf[256] = {0};
                GetWindowTextW(g_hSearchEdit, buf, 256);
                g_searchText = buf;
            }
            return 0;
        }
        if (id == ID_SEARCH_CLEAR) {
            if (g_hSearchEdit) SetWindowTextW(g_hSearchEdit, L"");
            g_searchText.clear();
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }
        return 0;
    }

    case WM_MENU_SELECTED:
        OnMenuSelected(hwnd, (int)wParam);
        return 0;

    case WM_TIMER:
        if (wParam == TIMER_CLEANUP) {
            std::vector<HWND> dead;
            for (std::map<HWND, WindowState>::iterator it = g_modified.begin();
                 it != g_modified.end(); ++it) {
                if (!IsWindow(it->first)) dead.push_back(it->first);
            }
            for (size_t i = 0; i < dead.size(); i++) g_modified.erase(dead[i]);
            if (HasTarget() && !IsWindow(g_wins[g_selected])) {
                g_selected = -1; g_alpha = MAX_ALPHA;
                InvalidateRect(hwnd, NULL, FALSE);
            }
        } else if (wParam == TIMER_FADE) {
            if (!g_fadeActive || !IsWindow(g_fadeHwnd)) {
                g_fadeActive = false;
                KillTimer(hwnd, TIMER_FADE);
                return 0;
            }
            g_fadeSteps++;
            double t = (double)g_fadeSteps / g_fadeTotalSteps;
            if (t >= 1.0) t = 1.0;
            int a = (int)(g_fadeFrom + (g_fadeTo - g_fadeFrom) * t);
            ApplyOpacityRaw(g_fadeHwnd, a);
            if (HasTarget() && g_wins[g_selected] == g_fadeHwnd) {
                g_alpha = a;
                InvalidateRect(hwnd, NULL, FALSE);
            }
            if (g_fadeSteps >= g_fadeTotalSteps) {
                g_fadeActive = false;
                KillTimer(hwnd, TIMER_FADE);
            }
        }
        return 0;

    case WM_APP_NEW_INSTANCE:
        DestroyWindow(hwnd);
        return 0;

    case WM_NCHITTEST: {
        POINT cp = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
        ScreenToClient(hwnd, &cp);
        if (cp.y < S(TITLE_H)) {
            RECT rc = RcClose(); if (PtInRect(&rc, cp)) return HTCLIENT;
            rc = RcMin(); if (PtInRect(&rc, cp)) return HTCLIENT;
            rc = RcTheme(); if (PtInRect(&rc, cp)) return HTCLIENT;
            return HTCAPTION;
        }
        return HTCLIENT;
    }

    case WM_MOUSEMOVE: {
        if (!g_tracking) {
            TRACKMOUSEEVENT tme;
            tme.cbSize = sizeof(tme); tme.dwFlags = TME_LEAVE;
            tme.hwndTrack = hwnd; tme.dwHoverTime = 0;
            TrackMouseEvent(&tme); g_tracking = true;
        }
        POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};

        if (g_draggingSlider) {
            if (HasTarget()) {
                int v = ValueFromSliderX(pt.x);
                if (v != g_alpha) {
                    g_alpha = v;
                    ApplyOpacity(g_wins[g_selected], g_alpha);
                    UpdateTrayIcon(hwnd, g_alpha);
                    InvalidateRect(hwnd, NULL, FALSE);
                }
            }
            return 0;
        }

        RECT rc;
        rc = RcTargetBtn();       bool nT = PtInRect(&rc, pt) != 0;
        int nB = HitTestSmallBtn(pt);
        rc = RcSlider();          bool nS = PtInRect(&rc, pt) != 0;
        rc = RcClose();           bool nC = PtInRect(&rc, pt) != 0;
        rc = RcMin();             bool nM = PtInRect(&rc, pt) != 0;
        rc = RcCheck();           bool nK = PtInRect(&rc, pt) != 0;
        rc = RcHelpBtn();         bool nH = PtInRect(&rc, pt) != 0;
        rc = RcTheme();           bool nTh = PtInRect(&rc, pt) != 0;
        rc = RcTopmostBtn();      bool nTop = PtInRect(&rc, pt) != 0;
        rc = RcClickThroughBtn(); bool nCT = PtInRect(&rc, pt) != 0;
        rc = RcMoreBtn();         bool nMore = PtInRect(&rc, pt) != 0;
        int nP = HitTestPreset(pt);

        bool changed = nT != g_hoverTarget || nB != g_hoverBtn || nS != g_hoverSlider ||
            nC != g_hoverClose || nM != g_hoverMin || nK != g_hoverCheck ||
            nH != g_hoverHelp || nTh != g_hoverTheme || nTop != g_hoverTopmost ||
            nCT != g_hoverClickThrough || nP != g_hoverPreset || nMore != g_hoverMore;

        g_hoverTarget = nT; g_hoverBtn = nB; g_hoverSlider = nS;
        g_hoverClose = nC; g_hoverMin = nM; g_hoverCheck = nK;
        g_hoverHelp = nH; g_hoverTheme = nTh; g_hoverTopmost = nTop;
        g_hoverClickThrough = nCT; g_hoverPreset = nP; g_hoverMore = nMore;

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

    case WM_MOUSELEAVE:
        g_tracking = false;
        g_hoverTarget = false; g_hoverBtn = -1; g_hoverSlider = false;
        g_hoverClose = false; g_hoverMin = false; g_hoverCheck = false;
        g_hoverHelp = false; g_hoverTheme = false; g_hoverTopmost = false;
        g_hoverClickThrough = false; g_hoverPreset = -1; g_hoverMore = false;
        InvalidateRect(hwnd, NULL, FALSE);
        return 0;

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

        rc = RcClose(); if (PtInRect(&rc, pt)) { PostMessageW(hwnd, WM_CLOSE, 0, 0); return 0; }
        rc = RcMin();   if (PtInRect(&rc, pt)) { ShowWindow(hwnd, SW_MINIMIZE); return 0; }
        rc = RcTheme();
        if (PtInRect(&rc, pt)) {
            g_cfg.darkMode = !g_cfg.darkMode;
            ApplyTheme(); SaveConfig();
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }
        rc = RcTargetBtn();
        if (PtInRect(&rc, pt)) { OpenWindowPickerMenu(hwnd); return 0; }

        rc = RcSlider();
        if (PtInRect(&rc, pt) && HasTarget()) {
            g_draggingSlider = true; SetCapture(hwnd);
            g_alpha = ValueFromSliderX(pt.x);
            ApplyOpacity(g_wins[g_selected], g_alpha);
            UpdateTrayIcon(hwnd, g_alpha);
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        int btn = HitTestSmallBtn(pt);
        if (btn >= 0) { g_pressBtn = btn; InvalidateRect(hwnd, NULL, FALSE); return 0; }

        rc = RcTopmostBtn();
        if (PtInRect(&rc, pt)) { ToggleTopmost(); InvalidateRect(hwnd, NULL, FALSE); return 0; }
        rc = RcClickThroughBtn();
        if (PtInRect(&rc, pt)) { ToggleClickThrough(); InvalidateRect(hwnd, NULL, FALSE); return 0; }
        rc = RcMoreBtn();
        if (PtInRect(&rc, pt)) { OpenMoreMenu(hwnd); return 0; }

        rc = RcCheck();
        if (PtInRect(&rc, pt)) {
            g_checkOn = !g_checkOn;
            g_cfg.autoRestore = g_checkOn ? 1 : 0;
            SaveConfig();
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }
        rc = RcHelpBtn();
        if (PtInRect(&rc, pt)) { OpenHelpWindow(); return 0; }

        int pre = HitTestPreset(pt);
        if (pre >= 0) { g_pressPreset = pre; InvalidateRect(hwnd, NULL, FALSE); return 0; }
        return 0;
    }

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

        if (g_draggingSlider) {
            g_draggingSlider = false; ReleaseCapture();
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        if (g_pressBtn >= 0) {
            int btn = g_pressBtn; g_pressBtn = -1;
            int hit = HitTestSmallBtn(pt);
            if (hit == btn) {
                if (btn == 0) {
                    RefreshList();
                    Log(L"刷新列表");
                } else if (btn == 1) {
                    if (HasTarget()) {
                        HWND t = g_wins[g_selected];
                        std::map<HWND, WindowState>::iterator it = g_modified.find(t);
                        if (it != g_modified.end()) {
                            RestoreOne(it->first, it->second);
                            g_modified.erase(it);
                        }
                        std::wstring k = GetProfileKey(t);
                        if (!k.empty()) g_profiles.erase(k);
                        g_alpha = GetCurrentAlpha(t);
                        if (g_alpha < MIN_ALPHA) g_alpha = MIN_ALPHA;
                        Log(L"恢复:%s", g_titles[g_selected].c_str());
                    }
                } else if (btn == 2) {
                    RestoreAll();
                    g_profiles.clear();
                    g_alpha = MAX_ALPHA;
                    Log(L"全部恢复");
                }
            }
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }

        if (g_pressPreset >= 0) {
            int pre = g_pressPreset; g_pressPreset = -1;
            int hit = HitTestPreset(pt);
            if (hit == pre) ApplyPreset(pre);
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }
        return 0;
    }

    case WM_KEYDOWN: {
        if (wParam == VK_UP)   { NudgeAlpha(+5); return 0; }
        if (wParam == VK_DOWN) { NudgeAlpha(-5); return 0; }
        if (wParam == VK_ESCAPE) {
            if (g_hHelp) { DestroyWindow(g_hHelp); return 0; }
        }
        return 0;
    }

    case WM_MOUSEWHEEL: {
        if (HasTarget()) {
            int delta = GET_WHEEL_DELTA_WPARAM(wParam);
            NudgeAlpha(delta > 0 ? +5 : -5);
        }
        return 0;
    }

    case WM_HOTKEY: {
        if (wParam == HK_EXIT) { DestroyWindow(hwnd); return 0; }

        if (wParam >= HK_P1 && wParam <= HK_P4) {
            int idx = (int)wParam - HK_P1;
            ApplyPreset(idx);
            return 0;
        }

        HWND fg = GetForegroundWindow();
        if (IsOwn(fg)) return 0;

        int cur = GetCurrentAlpha(fg);
        if (wParam == HK_DOWN) ApplyOpacity(fg, cur - STEP_ALPHA);
        else if (wParam == HK_UP) ApplyOpacity(fg, cur + STEP_ALPHA);
        else if (wParam == HK_RESET) {
            RestoreAll();
            g_profiles.clear();
            if (HasTarget()) {
                g_alpha = GetCurrentAlpha(g_wins[g_selected]);
                if (g_alpha < MIN_ALPHA) g_alpha = MIN_ALPHA;
                if (g_alpha > MAX_ALPHA) g_alpha = MAX_ALPHA;
            } else g_alpha = MAX_ALPHA;
            InvalidateRect(hwnd, NULL, FALSE);
            return 0;
        }
        if (HasTarget() && g_wins[g_selected] == fg) {
            g_alpha = GetCurrentAlpha(fg);
            if (g_alpha < MIN_ALPHA) g_alpha = MIN_ALPHA;
            if (g_alpha > MAX_ALPHA) g_alpha = MAX_ALPHA;
            UpdateTrayIcon(hwnd, g_alpha);
            InvalidateRect(hwnd, NULL, FALSE);
        } else {
            UpdateTrayIcon(hwnd, GetCurrentAlpha(fg));
        }
        return 0;
    }

    case WM_TRAYICON: {
        if (lParam == WM_LBUTTONDBLCLK) {
            ShowWindow(hwnd, SW_SHOW);
            ShowWindow(hwnd, SW_RESTORE);
            SetForegroundWindow(hwnd);
        } else if (lParam == WM_RBUTTONUP) {
            POINT pt; GetCursorPos(&pt);
            HMENU menu = CreatePopupMenu();
            AppendMenuW(menu, MF_STRING, 1, L"显示主窗口");
            AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
            AppendMenuW(menu, MF_STRING, 2, L"退出");
            SetForegroundWindow(hwnd);
            int cmd = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON,
                                     pt.x, pt.y, 0, hwnd, NULL);
            DestroyMenu(menu);
            if (cmd == 1) {
                ShowWindow(hwnd, SW_SHOW);
                ShowWindow(hwnd, SW_RESTORE);
                SetForegroundWindow(hwnd);
            } else if (cmd == 2) DestroyWindow(hwnd);
        }
        return 0;
    }

    case WM_CLOSE:
        ShowWindow(hwnd, SW_HIDE);
        return 0;

    case WM_DESTROY:
        KillTimer(hwnd, TIMER_CLEANUP);
        KillTimer(hwnd, TIMER_FADE);
        if (g_hMenuWnd && IsWindow(g_hMenuWnd)) DestroyWindow(g_hMenuWnd);
        if (g_checkOn) {
            RestoreAll();
            g_profiles.clear();
        }
        SaveConfig();
        RemoveTray();
        UnregisterHotKey(hwnd, HK_DOWN);
        UnregisterHotKey(hwnd, HK_UP);
        UnregisterHotKey(hwnd, HK_RESET);
        UnregisterHotKey(hwnd, HK_EXIT);
        UnregisterHotKey(hwnd, HK_P1);
        UnregisterHotKey(hwnd, HK_P2);
        UnregisterHotKey(hwnd, HK_P3);
        UnregisterHotKey(hwnd, HK_P4);
        if (g_fontTitle)      DeleteObject(g_fontTitle);
        if (g_fontVersion)    DeleteObject(g_fontVersion);
        if (g_fontBig)        DeleteObject(g_fontBig);
        if (g_fontPercent)    DeleteObject(g_fontPercent);
        if (g_fontNormal)     DeleteObject(g_fontNormal);
        if (g_fontSmall)      DeleteObject(g_fontSmall);
        if (g_fontTiny)       DeleteObject(g_fontTiny);
        if (g_fontBubble)     DeleteObject(g_fontBubble);
        if (g_fontMenu)       DeleteObject(g_fontMenu);
        if (g_fontHelpH1)     DeleteObject(g_fontHelpH1);
        if (g_fontHelpH2)     DeleteObject(g_fontHelpH2);
        if (g_fontHelpBody)   DeleteObject(g_fontHelpBody);
        if (g_editBgBrush)    DeleteObject(g_editBgBrush);
        if (g_appIcon)        DestroyIcon(g_appIcon);
        if (g_trayIcon)       DestroyIcon(g_trayIcon);
        Log(L"程序退出");
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

// ===== 启动参数解析 =====
struct StartupArgs {
    int initAlpha;
    std::wstring targetTitle;
    StartupArgs() : initAlpha(-1) {}
};

StartupArgs ParseCmdLine(const wchar_t* cmd) {
    StartupArgs a;
    if (!cmd) return a;
    std::wstring s = cmd;
    std::vector<std::wstring> tokens;
    std::wstring cur;
    bool inQuote = false;
    for (size_t i = 0; i <= s.size(); i++) {
        wchar_t c = (i < s.size()) ? s[i] : L' ';
        if (c == L'"') { inQuote = !inQuote; continue; }
        if (!inQuote && (c == L' ' || c == L'\t')) {
            if (!cur.empty()) { tokens.push_back(cur); cur.clear(); }
        } else cur += c;
    }
    for (size_t i = 0; i < tokens.size(); i++) {
        if (tokens[i] == L"-a" && i + 1 < tokens.size()) {
            a.initAlpha = (int)wcstol(tokens[i + 1].c_str(), NULL, 10);
            if (a.initAlpha < MIN_ALPHA) a.initAlpha = MIN_ALPHA;
            if (a.initAlpha > MAX_ALPHA) a.initAlpha = MAX_ALPHA;
            i++;
        } else if (tokens[i] == L"-t" && i + 1 < tokens.size()) {
            a.targetTitle = tokens[i + 1];
            i++;
        }
    }
    return a;
}

// ===== 入口 =====
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow) {
    (void)hPrev; (void)lpCmd; (void)nShow;

    LPWSTR wcmd = GetCommandLineW();
    StartupArgs args = ParseCmdLine(wcmd);

    EnableDpiAware();
    HDC screen = GetDC(NULL);
    g_dpiScale = GetDeviceCaps(screen, LOGPIXELSX) / 96.0;
    ReleaseDC(NULL, screen);
    if (g_dpiScale < 1.0) g_dpiScale = 1.0;

    LoadConfig();
    ApplyTheme();
    g_checkOn = g_cfg.autoRestore != 0;

    Log(L"===== 程序启动 (V18) =====");

    g_hMutex = CreateMutexW(NULL, FALSE, L"Local\\Window3ClearV18_Mutex");
    if (g_hMutex && GetLastError() == ERROR_ALREADY_EXISTS) {
        HWND existing = FindWindowW(L"Window3ClearV18Class", NULL);
        if (existing) {
            DWORD_PTR result = 0;
            SendMessageTimeoutW(existing, WM_APP_NEW_INSTANCE, 0, 0,
                                SMTO_ABORTIFHUNG, 3000, &result);
            for (int i = 0; i < 60; i++) {
                if (!IsWindow(existing)) break;
                Sleep(50);
            }
        }
    }

    if (g_cfg.firstRun) {
        MessageBoxW(NULL,
            L"欢迎使用 Window3Clear - V18!\n\n"
            L"1. 点击「当前目标窗口」选择要调整的窗口\n"
            L"2. 左卡片有搜索框,可以过滤窗口列表\n"
            L"3. 拖动滑块或点预设百分比调整透明度\n"
            L"4. 程序会自动记住每个窗口的透明度\n"
            L"5. 点右上角 X 只是隐藏到托盘,托盘右键 - 退出才真正退出",
            L"欢迎", MB_OK | MB_ICONINFORMATION);
    }

    g_appIcon = CreateAppIcon(S(32));

    WNDCLASSEXW wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.cbSize = sizeof(wc);
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInst;
    wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
    wc.hbrBackground = NULL;
    wc.lpszClassName = L"Window3ClearV18Class";
    wc.hIcon = g_appIcon;
    wc.hIconSm = g_appIcon;
    if (!RegisterClassExW(&wc)) {
        MessageBoxW(NULL, L"主窗口类注册失败", L"错误", MB_ICONERROR);
        return 1;
    }

    WNDCLASSEXW wc2;
    ZeroMemory(&wc2, sizeof(wc2));
    wc2.cbSize = sizeof(wc2);
    wc2.lpfnWndProc = HelpWndProc;
    wc2.hInstance = hInst;
    wc2.hCursor = LoadCursorW(NULL, IDC_ARROW);
    wc2.hbrBackground = NULL;
    wc2.lpszClassName = L"Window3ClearHelpClass";
    if (!RegisterClassExW(&wc2)) {
        MessageBoxW(NULL, L"说明窗口类注册失败", L"错误", MB_ICONERROR);
        return 1;
    }

    int W = S(WIN_W_BASE), H = S(WIN_H_BASE);
    int sx = (GetSystemMetrics(SM_CXSCREEN) - W) / 2;
    int sy = (GetSystemMetrics(SM_CYSCREEN) - H) / 2;

    HWND hwnd = CreateWindowExW(
        WS_EX_APPWINDOW,
        L"Window3ClearV18Class", L"Window3Clear - V18",
        WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX,
        sx, sy, W, H,
        NULL, NULL, hInst, NULL);

    if (!hwnd) {
        wchar_t err[128];
        wsprintfW(err, L"主窗口创建失败,错误码 %lu", GetLastError());
        MessageBoxW(NULL, err, L"错误", MB_ICONERROR);
        return 1;
    }

    HRGN hRgn = CreateRoundRectRgn(0, 0, W + 1, H + 1, S(CORNER_R) * 2, S(CORNER_R) * 2);
    SetWindowRgn(hwnd, hRgn, TRUE);

    // 热键注册 + 诊断
    struct HotkeyReg { int id; UINT mod; UINT key; const wchar_t* name; };
    HotkeyReg regs[] = {
        {HK_DOWN,  g_cfg.hkModDown,  g_cfg.hkKeyDown,  L"Ctrl+Alt+← 更透明"},
        {HK_UP,    g_cfg.hkModUp,    g_cfg.hkKeyUp,    L"Ctrl+Alt+→ 更不透明"},
        {HK_RESET, g_cfg.hkModReset, g_cfg.hkKeyReset, L"Ctrl+Alt+0 全部恢复"},
        {HK_EXIT,  g_cfg.hkModExit,  g_cfg.hkKeyExit,  L"Ctrl+Alt+Q 退出"},
        {HK_P1, MOD_CONTROL | MOD_SHIFT, '1', L"Ctrl+Shift+1 预设 25%"},
        {HK_P2, MOD_CONTROL | MOD_SHIFT, '2', L"Ctrl+Shift+2 预设 50%"},
        {HK_P3, MOD_CONTROL | MOD_SHIFT, '3', L"Ctrl+Shift+3 预设 75%"},
        {HK_P4, MOD_CONTROL | MOD_SHIFT, '4', L"Ctrl+Shift+4 预设 100%"},
    };
    std::wstring failNames;
    for (int i = 0; i < 8; i++) {
        if (regs[i].mod == 0 || regs[i].key == 0) continue;
        if (!RegisterHotKey(hwnd, regs[i].id, regs[i].mod, regs[i].key)) {
            if (!failNames.empty()) failNames += L"\n";
            failNames += regs[i].name;
        }
    }
    if (!failNames.empty()) {
        std::wstring msg = L"以下热键被其他程序占用,无法注册:\n\n" + failNames +
                          L"\n\n其他热键仍可正常使用。";
        MessageBoxW(hwnd, msg.c_str(), L"热键冲突", MB_OK | MB_ICONWARNING);
    }

    AddTray(hwnd);
    g_trayIconAlpha = -1;
    UpdateTrayIcon(hwnd, MAX_ALPHA);

    RefreshList();

    if (args.initAlpha > 0) {
        HWND target = NULL;
        if (!args.targetTitle.empty()) {
            for (size_t i = 0; i < g_wins.size(); i++) {
                if (g_titles[i].find(args.targetTitle) != std::wstring::npos) {
                    target = g_wins[i];
                    g_selected = (int)i;
                    g_alpha = args.initAlpha;
                    break;
                }
            }
        } else {
            target = GetForegroundWindow();
        }
        if (target) {
            ApplyOpacity(target, args.initAlpha);
            UpdateTrayIcon(hwnd, args.initAlpha);
        }
    }

    ShowWindow(hwnd, SW_SHOWNORMAL);
    UpdateWindow(hwnd);
    SetForegroundWindow(hwnd);

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

    if (g_hMutex) {
        ReleaseMutex(g_hMutex);
        CloseHandle(g_hMutex);
    }
    return (int)msg.wParam;
}

编译前加参数:
参数1 · 加在编译器参数里面

C++
-std=c++14 -O2 -Wall -Wextra -static -finput-charset=GBK -fexec-charset=GBK

参数2 · 加在链接器命令行里面

C++
-lshell32 -mwindows -lgdi32 -lshlwapi -lcomctl32