1
0

mousealert_windows.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. //go:build windows
  2. // ============================================================================
  3. // 系统级鼠标提醒(Windows 原生实现)—— 可靠方案 v2
  4. //
  5. // 需求:平时鼠标是正常样式;有消息来(通过 API 触发)时,鼠标旁边浮出
  6. // 半透明气泡提示文字,跟随鼠标移动、闪烁,可覆盖任意窗口(系统级),
  7. // 默认 8 秒自动消退。
  8. //
  9. // v1 的失败原因:全局低层鼠标钩子 WH_MOUSE_LL 的回调由系统在非 Go 线程
  10. // 上调用,经 syscall.NewCallback 进入 Go runtime 时会导致进程静默退出;
  11. // 且 DIB 自绘 + UpdateLayeredWindow 尺寸不匹配时绘制失效。v2 全部移除:
  12. //
  13. // 1. 不装任何钩子(去掉唯一危险源),位置跟随改为窗口线程定时器轮询
  14. // GetCursorPos(GetMessage 消息循环所在线程,安全)。
  15. // 2. 用 SetLayeredWindowAttributes(LWA_COLORKEY) 把背景色抠成透明(背景透明,
  16. // 只留白色文字),WM_PAINT 用普通 GDI(FillRect + TextOutW)绘制气泡,
  17. // 不再用 DIB/UpdateLayeredWindow。
  18. // 3. 窗口过程 WndProc 的 syscall.NewCallback 由 DispatchMessageW 在同线程
  19. // 同步调用,Go runtime 完全支持(安全)。
  20. // 4. 超长文字:TextOutW 单行绘制 + 定时器推进 scrollX 偏移,实现水平循环滚动。
  21. //
  22. // 说明:本文件仅在 Windows 编译。其他平台见 mousealert_other.go 空实现。
  23. // ============================================================================
  24. package main
  25. import (
  26. "fmt"
  27. "os"
  28. "runtime"
  29. "strings"
  30. "sync"
  31. "syscall"
  32. "time"
  33. "unsafe"
  34. )
  35. // Windows API 常量
  36. const (
  37. wmTimer = 0x0113
  38. wmDestroy = 0x0002
  39. wmNcDestroy = 0x0082
  40. wmPaint = 0x000F
  41. wmRefresh = 0x8001 // 自定义:立即刷新(trigger 唤醒窗口线程)
  42. wndExLayered = 0x00080000 // WS_EX_LAYERED 分层窗口(支持透明)
  43. wndExTool = 0x00000080 // WS_EX_TOOLWINDOW 不占任务栏
  44. wndExTopMost = 0x00000008 // WS_EX_TOPMOST 置顶
  45. wndExNoActivate = 0x08000000 // WS_EX_NOACTIVATE 不抢焦点
  46. swpNoActivate = 0x0010 // SWP_NOACTIVATE
  47. swpShowWindow = 0x0040 // SWP_SHOWWINDOW
  48. lwaAlpha = 0x2 // LWA_ALPHA:SetLayeredWindowAttributes 设置整体 alpha
  49. lwaColorKey = 0x1 // LWA_COLORKEY:把指定颜色像素抠成透明(背景透明)
  50. timerFollow = 1 // 位置跟随 + 闪烁定时器 ID
  51. overlayWidth = 200
  52. overlayHeight = 54
  53. alertDuration = 8 * time.Second
  54. followIntervalMs = 60 // 跟随/闪烁轮询间隔 60ms
  55. // tagAlertDuration 资源管理器「标签」气泡的显示时长(固定,不取用户「鼠标提醒」
  56. // 时长,也不做超长文字延长)。标签提示是顺带一瞥的信息,停得太久会一直挂在
  57. // 鼠标旁很干扰;鼠标离开悬停项时还会被立即隐藏(见 stopTagAlert)。
  58. tagAlertDuration = 2 * time.Second
  59. )
  60. // hwndTopMost HWND_TOPMOST = (HWND)-1
  61. const hwndTopMost uintptr = ^uintptr(0)
  62. // 气泡背景色(深蓝黑):COLORREF = 0x00BBGGRR(LWA_COLORKEY 抠成透明,只留文字)
  63. const bgColorRef = 0x001E1E3C
  64. // cfgDurationOrDefault 返回配置的显示时长(秒),非法时用默认 8 秒
  65. func cfgDurationOrDefault(sec int) time.Duration {
  66. if sec < 2 || sec > 60 {
  67. sec = 8
  68. }
  69. return time.Duration(sec) * time.Second
  70. }
  71. // mouseAlertScrollDefault 判断是否滚动显示超长文字:
  72. // - cfg.Scroll 非 nil → 用显式配置(true=滚动,false=裁剪不滚动);
  73. // - cfg.Scroll 为 nil(旧配置无该字段)→ 用 Speed>0 判断(旧行为:速度为 0 不滚动)。
  74. func mouseAlertScrollDefault(cfg MouseAlertConfig) bool {
  75. if cfg.Scroll != nil {
  76. return *cfg.Scroll
  77. }
  78. return cfg.Speed > 0
  79. }
  80. // estimateTextWidth 估算文字像素宽度(微软雅黑:全角/中文≈字号,半角/ASCII≈0.55*字号)。
  81. // 用于在触发时预判文字是否超长,从而智能延长显示时长。
  82. func estimateTextWidth(text string, fontSize int32) int32 {
  83. if text == "" || fontSize <= 0 {
  84. return 0
  85. }
  86. var w float32
  87. for _, r := range text {
  88. if r < 0x2E80 { // 半角 / ASCII / 拉丁
  89. w += 0.55 * float32(fontSize)
  90. } else { // 全角 / 中日韩
  91. w += float32(fontSize)
  92. }
  93. }
  94. return int32(w)
  95. }
  96. // hexColorToRef 把 #RRGGBB 或 #RGB 颜色字符串转 COLORREF(0x00BBGGRR)。
  97. // 解析失败时回退 fallback。
  98. func hexColorToRef(s string, fallback uintptr) uintptr {
  99. s = strings.TrimSpace(s)
  100. if len(s) == 7 && s[0] == '#' {
  101. var r, g, b uint32
  102. if _, err := fmt.Sscanf(s, "#%02x%02x%02x", &r, &g, &b); err == nil {
  103. return uintptr(r | g<<8 | b<<16)
  104. }
  105. }
  106. if len(s) == 4 && s[0] == '#' {
  107. var r, g, b uint32
  108. if _, err := fmt.Sscanf(s, "#%1x%1x%1x", &r, &g, &b); err == nil {
  109. return uintptr(r*17 | g*17<<8 | b*17<<16)
  110. }
  111. }
  112. return fallback
  113. }
  114. // ------------------------------------------------------------------------
  115. // Windows 结构体与函数指针声明(用 syscall 直接调用,避免引入额外依赖)
  116. // ------------------------------------------------------------------------
  117. type point struct {
  118. X int32
  119. Y int32
  120. }
  121. // rect Windows RECT 结构(GetWindowRect / FillRect 输出)
  122. type rect struct {
  123. Left int32
  124. Top int32
  125. Right int32
  126. Bottom int32
  127. }
  128. type msg struct {
  129. HWND uintptr
  130. Message uint32
  131. WParam uintptr
  132. LParam uintptr
  133. Time uint32
  134. Pt point
  135. LPrivate uint32
  136. }
  137. type wndclassex struct {
  138. CbSize uint32
  139. Style uint32
  140. LpfnWndProc uintptr
  141. CbClsExtra int32
  142. CbWndExtra int32
  143. HInstance uintptr
  144. HIcon uintptr
  145. HCursor uintptr
  146. HbrBackground uintptr
  147. LpszMenuName *uint16
  148. LpszClassName *uint16
  149. HIconSm uintptr
  150. }
  151. // paintstruct PAINTSTRUCT(BeginPaint / EndPaint 输出)
  152. type paintstruct struct {
  153. Hdc uintptr
  154. FErase int32
  155. RcPaint rect
  156. FRestore int32
  157. FIncUpdate int32
  158. RGBReserved [32]byte
  159. }
  160. // size SIZE 结构(GetTextExtentPoint32W 输出:文字像素尺寸)
  161. type size struct {
  162. Cx int32
  163. Cy int32
  164. }
  165. // 延迟加载的 user32.dll / gdi32.dll / kernel32.dll 函数
  166. var (
  167. user32 = syscall.NewLazyDLL("user32.dll")
  168. gdi32 = syscall.NewLazyDLL("gdi32.dll")
  169. kernel32 = syscall.NewLazyDLL("kernel32.dll")
  170. procGetMessage = user32.NewProc("GetMessageW")
  171. procTranslateMessage = user32.NewProc("TranslateMessage")
  172. procDispatchMessage = user32.NewProc("DispatchMessageW")
  173. procRegisterClassEx = user32.NewProc("RegisterClassExW")
  174. procCreateWindowEx = user32.NewProc("CreateWindowExW")
  175. procDefWindowProc = user32.NewProc("DefWindowProcW")
  176. procDestroyWindow = user32.NewProc("DestroyWindow")
  177. procSetTimer = user32.NewProc("SetTimer")
  178. procKillTimer = user32.NewProc("KillTimer")
  179. procShowWindow = user32.NewProc("ShowWindow")
  180. procSetWindowPos = user32.NewProc("SetWindowPos")
  181. procGetCursorPos = user32.NewProc("GetCursorPos")
  182. procPostMessage = user32.NewProc("PostMessageW")
  183. procSetLayeredWindowAttr = user32.NewProc("SetLayeredWindowAttributes")
  184. procBeginPaint = user32.NewProc("BeginPaint")
  185. procEndPaint = user32.NewProc("EndPaint")
  186. procInvalidateRect = user32.NewProc("InvalidateRect")
  187. procFillRect = user32.NewProc("FillRect") // 注意:FillRect 在 user32.dll,不在 gdi32.dll
  188. procDrawTextW = user32.NewProc("DrawTextW")
  189. procCreateSolidBrush = gdi32.NewProc("CreateSolidBrush")
  190. procDeleteObject = gdi32.NewProc("DeleteObject")
  191. procSetBkMode = gdi32.NewProc("SetBkMode")
  192. procSetTextColor = gdi32.NewProc("SetTextColor")
  193. procGetStockObject = gdi32.NewProc("GetStockObject")
  194. procSelectObject = gdi32.NewProc("SelectObject")
  195. procCreateFontW = gdi32.NewProc("CreateFontW")
  196. procTextOutW = gdi32.NewProc("TextOutW") // 单行文字输出(超长滚动用)
  197. procGetTextExtentPoint32W = gdi32.NewProc("GetTextExtentPoint32W") // 测量文字宽度(判断是否超长)
  198. procCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC") // 双缓冲:创建内存 DC
  199. procCreateCompatibleBitmap = gdi32.NewProc("CreateCompatibleBitmap") // 双缓冲:创建兼容位图
  200. procBitBlt = gdi32.NewProc("BitBlt") // 双缓冲:整块拷贝上屏
  201. procDeleteDC = gdi32.NewProc("DeleteDC") // 双缓冲:删除内存 DC
  202. procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW")
  203. procGetDpiForWindow = user32.NewProc("GetDpiForWindow") // Win10 1607+,返回窗口 DPI
  204. procGetDpiForSystem = user32.NewProc("GetDpiForSystem") // Win10 1607+,返回系统 DPI
  205. procGetDC = user32.NewProc("GetDC")
  206. procReleaseDC = user32.NewProc("ReleaseDC")
  207. procGetDeviceCaps = gdi32.NewProc("GetDeviceCaps")
  208. )
  209. // ------------------------------------------------------------------------
  210. // DPI 缩放辅助:高 DPI 屏幕(125%/150%/200%)下窗口与控件按物理像素创建会显得
  211. // 过小。manifest 声明 permonitorv2 只让进程「感知」DPI,不会自动放大窗口尺寸,
  212. // 必须手动把逻辑尺寸乘上缩放系数。scaleForDpi 返回 1.0~2.0 的缩放因子。
  213. // ------------------------------------------------------------------------
  214. // dpiScale 返回当前 DPI 缩放因子(96 基准)。失败/非 Windows 返回 1.0。
  215. func dpiScale() float64 {
  216. dpi := systemDpi()
  217. if dpi <= 0 {
  218. return 1.0
  219. }
  220. return float64(dpi) / 96.0
  221. }
  222. // scaleInt 按 DPI 缩放整数尺寸(最小保留 1)。
  223. func scaleInt(v int, scale float64) int {
  224. if scale <= 0 {
  225. scale = 1
  226. }
  227. r := int(float64(v) * scale)
  228. if r < 1 {
  229. r = 1
  230. }
  231. return r
  232. }
  233. // systemDpi 返回系统 DPI(96 基准)。GetDpiForSystem 可能受 OS 版本限制,
  234. // 失败时用 GetDeviceCaps(LOGPIXELSX) 兜底。
  235. func systemDpi() uint32 {
  236. // GetDpiForSystem(Win10 1607+)
  237. if procGetDpiForSystem.Find() == nil {
  238. r, _, _ := procGetDpiForSystem.Call()
  239. if r != 0 {
  240. return uint32(r)
  241. }
  242. }
  243. // 兜底:GetDeviceCaps(LOGPIXELSX=88)
  244. if procGetDeviceCaps.Find() == nil {
  245. hdc, _, _ := procGetDC.Call(0)
  246. if hdc != 0 {
  247. r, _, _ := procGetDeviceCaps.Call(hdc, 88)
  248. procReleaseDC.Call(0, hdc)
  249. if r != 0 {
  250. return uint32(r)
  251. }
  252. }
  253. }
  254. return 96
  255. }
  256. // ------------------------------------------------------------------------
  257. // 鼠标提醒运行时状态
  258. // ------------------------------------------------------------------------
  259. // mouseAlertState 鼠标提醒的运行时状态(单实例)
  260. type mouseAlertState struct {
  261. mu sync.Mutex
  262. started bool // 工作线程是否已启动(持久化,仅启动一次)
  263. overlayWnd uintptr
  264. active bool
  265. text string
  266. flashOn bool
  267. lastX, lastY int32
  268. stopTime time.Time
  269. wndProc uintptr
  270. classOK bool
  271. bgBrush uintptr
  272. scrollX int32 // 超长文字水平滚动偏移(px),定时器推进
  273. textWidth int32 // 当前文字像素宽度(>可用宽度时滚动)
  274. textGap int32 // 头尾相联间隔(两个空格宽度 px),滚动周期 = 文字宽 + 间隔
  275. // 运行时配置(triggerMouseAlert 时从设置加载)
  276. cfgWidth int32 // 气泡窗口宽度(px)
  277. cfgHeight int32 // 气泡窗口高度(px,按字号自适应)
  278. cfgFontSize int32 // 字号(px)
  279. cfgSpeed int // 超长文字滚动速度(px/s)
  280. cfgScroll bool // 是否滚动显示超长文字(false=超出部分右侧裁剪,不滚动)
  281. cfgDuration time.Duration // 显示时长
  282. cfgTextColor uintptr // 文字颜色(COLORREF)
  283. cfgBgColor uintptr // 气泡背景色(COLORKEY 抠透明)
  284. cfgOutlineColor uintptr // 文字描边颜色(COLORREF),形成反差
  285. cfgOutlineWidth int32 // 文字描边宽度(px),0 关闭
  286. // aboveMode 提示定位模式:true 时气泡显示在鼠标正上方(用于资源管理器
  287. // 悬停标签提示,避免遮挡光标且不与系统原有的右下信息提示重叠);
  288. // false 时气泡显示在鼠标右下偏移(默认,见 positionAndDraw)。
  289. aboveMode bool
  290. }
  291. var mouseAlert = &mouseAlertState{}
  292. // triggerMouseAlert 触发鼠标提醒:鼠标旁浮出半透明气泡提示,跟随鼠标闪烁。
  293. // 文字为空时用默认提示。重复触发会刷新提醒计时并立即显示。
  294. //
  295. // 定位策略:窗口线程的定时器主动用 GetCursorPos 读取当前鼠标位置并跟随,
  296. // 不依赖任何全局钩子回调(钩子回调在系统线程执行,曾导致进程退出)。
  297. func triggerMouseAlert(text string) {
  298. triggerMouseAlertEx(text, 0, nil, false)
  299. }
  300. // triggerMouseAlertWithOptions 触发鼠标提醒,并允许通过参数覆盖气泡宽度与滚动行为。
  301. // 用于 API 触发场景:调用方可指定 width(px,>0 生效)与 scroll(是否滚动显示超长文字)。
  302. // 传入 nil scroll 时使用设置默认(Speed>0 则滚动)。
  303. func triggerMouseAlertWithOptions(text string, width int, scroll *bool) {
  304. triggerMouseAlertEx(text, width, scroll, false)
  305. }
  306. // triggerMouseAlertAbove 触发鼠标提醒,并强制把气泡定位到鼠标正上方。
  307. // 用于资源管理器悬停文件/文件夹显示「标签」提示:与默认的右下偏移不同,
  308. // 正上方模式能避开光标本身,也不会与资源管理器原有的信息提示(多位于
  309. // 光标右下方)重叠,满足用户「提示注意显示位置」的要求。
  310. // 除定位模式外,其余行为与 triggerMouseAlert 完全一致。
  311. func triggerMouseAlertAbove(text string) {
  312. triggerMouseAlertEx(text, 0, nil, true)
  313. }
  314. // triggerMouseAlertEx 鼠标提醒核心:按参数触发气泡显示。
  315. // - widthOverride > 0 时覆盖气泡宽度(px),否则用设置配置;
  316. // - scrollOverride 非 nil 时覆盖「是否滚动显示超长文字」,否则用设置默认
  317. // (Speed>0 即滚动);
  318. // - above 为 true 时气泡定位到鼠标正上方(标签提示),否则右下偏移。
  319. func triggerMouseAlertEx(text string, widthOverride int, scrollOverride *bool, above bool) {
  320. if text == "" {
  321. text = "有新消息提醒"
  322. }
  323. // 从设置加载鼠标提醒配置(字号/宽度/速度/颜色/时长)
  324. cfg := loadSettings().MouseAlert
  325. var pt point
  326. curRet, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
  327. hasCursor := curRet != 0
  328. // 宽度:参数覆盖 > 设置值 > 默认
  329. cfgWidth := int32(cfg.Width)
  330. if widthOverride > 0 {
  331. cfgWidth = int32(widthOverride)
  332. }
  333. if cfgWidth <= 0 {
  334. cfgWidth = overlayWidth
  335. }
  336. cfgFontSize := int32(cfg.FontSize)
  337. if cfgFontSize <= 0 {
  338. cfgFontSize = DefaultMouseAlertFontSize
  339. }
  340. // 滚动开关:参数覆盖 > 设置配置(cfg.Scroll 非 nil)> 设置默认(Speed>0 即滚动)
  341. scroll := mouseAlertScrollDefault(cfg)
  342. if scrollOverride != nil {
  343. scroll = *scrollOverride
  344. }
  345. // 智能延长显示时长:仅当「会滚动」且文字超长(需滚动)时,追加滚动一圈所需
  346. // 时间,保证能看完。不滚动时超长部分右侧裁剪,不延长。
  347. // 标签提示(above=true)固定 tagAlertDuration(2 秒):只在鼠标停留该文件期间
  348. // 显示,鼠标移开即被 stopTagAlert 隐藏,不取用户「鼠标提醒」时长、也不因超长延长。
  349. estW := estimateTextWidth(text, cfgFontSize)
  350. var totalDur time.Duration
  351. if above {
  352. totalDur = tagAlertDuration
  353. } else {
  354. baseDur := cfgDurationOrDefault(cfg.Duration)
  355. totalDur = baseDur
  356. if scroll && estW > cfgWidth-24 && cfg.Speed > 0 {
  357. // 超出可用宽度的部分需滚动,所需时间 = 超出像素 / 速度
  358. extra := estW - (cfgWidth - 24)
  359. need := time.Duration(float64(extra) / float64(cfg.Speed) * float64(time.Second))
  360. totalDur = baseDur + need
  361. }
  362. }
  363. mouseAlert.mu.Lock()
  364. mouseAlert.text = text
  365. mouseAlert.active = true
  366. mouseAlert.flashOn = true
  367. mouseAlert.aboveMode = above // 定位模式:true=鼠标正上方(标签提示),false=右下偏移
  368. mouseAlert.stopTime = time.Now().Add(totalDur)
  369. mouseAlert.scrollX = 0 // 新消息从头开始滚动
  370. mouseAlert.textWidth = 0 // 强制重新测量
  371. // 缓存本次提醒的显示配置
  372. mouseAlert.cfgWidth = cfgWidth
  373. mouseAlert.cfgFontSize = cfgFontSize
  374. mouseAlert.cfgSpeed = cfg.Speed
  375. mouseAlert.cfgScroll = scroll
  376. mouseAlert.cfgDuration = totalDur
  377. mouseAlert.cfgTextColor = hexColorToRef(cfg.Color, 0x00FFFFFF) // 默认白字
  378. mouseAlert.cfgBgColor = bgColorRef
  379. mouseAlert.cfgOutlineColor = hexColorToRef(cfg.OutlineColor, 0x00000000) // 默认黑边
  380. mouseAlert.cfgOutlineWidth = int32(cfg.OutlineWidth)
  381. // 头尾相联间隔 = 两个空格宽度(约 0.3*字号 每个),提前缓存供滚动周期使用
  382. mouseAlert.textGap = int32(float32(cfgFontSize) * 0.3 * 2)
  383. if mouseAlert.textGap < 4 {
  384. mouseAlert.textGap = 4
  385. }
  386. // 气泡高度按字号自适应:字号 + 上下留白 + 内边距
  387. mouseAlert.cfgHeight = mouseAlert.cfgFontSize + 34
  388. if hasCursor {
  389. mouseAlert.lastX, mouseAlert.lastY = pt.X, pt.Y
  390. }
  391. started := mouseAlert.started
  392. mouseAlert.started = true
  393. overlay := mouseAlert.overlayWnd
  394. mouseAlert.mu.Unlock()
  395. // 首次触发:启动常驻工作线程(幂等),建窗后由线程主动定位并重绘
  396. if !started {
  397. go mouseAlertLoop()
  398. return
  399. }
  400. // 已启动:唤醒窗口线程立即刷新(窗口线程负责 SetWindowPos/绘制)
  401. if overlay != 0 {
  402. procPostMessage.Call(overlay, wmRefresh, 0, 0)
  403. }
  404. }
  405. // stopMouseAlert 立即停止鼠标提醒(隐藏气泡;线程保持常驻)
  406. func stopMouseAlert() {
  407. mouseAlert.mu.Lock()
  408. mouseAlert.active = false
  409. overlay := mouseAlert.overlayWnd
  410. mouseAlert.mu.Unlock()
  411. if overlay != 0 {
  412. procShowWindow.Call(overlay, 0) // SW_HIDE
  413. }
  414. }
  415. // stopTagAlert 立即隐藏资源管理器「标签」气泡(鼠标离开悬停项时调用)。
  416. // 与 stopMouseAlert 的区别:只在当前处于标签提示模式(aboveMode)时才停止,
  417. // 避免误关掉用户主动触发的普通鼠标提醒。
  418. func stopTagAlert() {
  419. mouseAlert.mu.Lock()
  420. if !mouseAlert.aboveMode {
  421. mouseAlert.mu.Unlock()
  422. return
  423. }
  424. mouseAlert.active = false
  425. overlay := mouseAlert.overlayWnd
  426. mouseAlert.mu.Unlock()
  427. if overlay != 0 {
  428. procShowWindow.Call(overlay, 0) // SW_HIDE
  429. }
  430. }
  431. // mouseAlertLoop 常驻工作线程:注册窗口类、创建半透明置顶气泡窗口、
  432. // 启动跟随/闪烁定时器,进入消息循环。
  433. func mouseAlertLoop() {
  434. // 关键:Go 的 goroutine 会在 OS 线程间迁移。窗口消息循环(CreateWindowEx +
  435. // GetMessage + DispatchMessage)必须固定在同一个 OS 线程上,否则 WM_TIMER /
  436. // WM_PAINT 等消息投递到创建窗口的线程,而 GetMessage 在另一线程永远收不到,
  437. // 导致窗口出现后卡死(不跟随鼠标、不重绘、无文字)。LockOSThread 锁定本
  438. // goroutine 到当前 OS 线程,保证消息循环与窗口同线程。
  439. runtime.LockOSThread()
  440. hInst, _, _ := procGetModuleHandleW.Call(0)
  441. mouseAlert.mu.Lock()
  442. className, _ := syscall.UTF16PtrFromString("TengTuMouseAlertBubble")
  443. wc := wndclassex{
  444. CbSize: uint32(unsafe.Sizeof(wndclassex{})),
  445. LpfnWndProc: mouseAlert.wndProcAddr(),
  446. HInstance: hInst,
  447. LpszClassName: className,
  448. HCursor: 0,
  449. }
  450. atom, _, _ := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
  451. if atom != 0 {
  452. mouseAlert.classOK = true
  453. } else {
  454. fmt.Fprintf(os.Stderr, "[mousealert] RegisterClassEx failed (classOK=%v)\n", mouseAlert.classOK)
  455. }
  456. mouseAlert.mu.Unlock()
  457. // 创建半透明置顶气泡窗口(不抢焦点、不占任务栏)
  458. // dwStyle 必须含 WS_POPUP(0x80000000):无边框无标题的弹出窗口,
  459. // 否则 CreateWindowEx 可能失败或窗口不可见。
  460. style := uintptr(wndExLayered | wndExTool | wndExTopMost | wndExNoActivate)
  461. mouseAlert.mu.Lock()
  462. w, h := mouseAlert.cfgWidth, mouseAlert.cfgHeight
  463. if w <= 0 {
  464. w = overlayWidth // 首次触发配置尚未缓存时用默认
  465. }
  466. if h <= 0 {
  467. h = overlayHeight
  468. }
  469. mouseAlert.mu.Unlock()
  470. overlay, _, _ := procCreateWindowEx.Call(
  471. style,
  472. uintptr(unsafe.Pointer(className)),
  473. 0,
  474. uintptr(0x80000000) /* WS_POPUP */, 0, 0, uintptr(w), uintptr(h), 0,
  475. 0, 0, hInst, 0,
  476. )
  477. if overlay == 0 {
  478. fmt.Fprintf(os.Stderr, "[mousealert] CreateWindowEx failed\n")
  479. }
  480. mouseAlert.mu.Lock()
  481. mouseAlert.overlayWnd = overlay
  482. if overlay != 0 {
  483. // 背景透明(LWA_COLORKEY):把背景色 bgColorRef 的像素抠成透明,只留白色
  484. // 文字。WM_PAINT 用普通 GDI 绘制气泡(背景+文字)。
  485. // 注意:不要用 UpdateLayeredWindow——它会接管分层窗口内容,导致
  486. // WM_PAINT 完全失效(这正是当前「完全不显示」的根因)。
  487. bg := mouseAlert.cfgBgColor
  488. if bg == 0 {
  489. bg = bgColorRef
  490. }
  491. brush, _, _ := procCreateSolidBrush.Call(bg)
  492. mouseAlert.bgBrush = brush
  493. // LWA_COLORKEY:crKey=背景色,bAlpha=0(忽略),dwFlags=LWA_COLORKEY
  494. procSetLayeredWindowAttr.Call(overlay, bg, 0, uintptr(lwaColorKey))
  495. }
  496. mouseAlert.mu.Unlock()
  497. // 启动跟随/闪烁定时器(窗口线程内轮询鼠标位置)
  498. if overlay != 0 {
  499. procSetTimer.Call(overlay, timerFollow, followIntervalMs, 0)
  500. // 建窗后立即用当前鼠标位置定位并重绘一次,保证首次触发即可见
  501. var pt point
  502. curRet, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
  503. if curRet != 0 {
  504. mouseAlert.mu.Lock()
  505. if mouseAlert.active {
  506. mouseAlert.lastX, mouseAlert.lastY = pt.X, pt.Y
  507. mouseAlert.mu.Unlock()
  508. mouseAlert.positionAndDraw(overlay, pt.X, pt.Y)
  509. } else {
  510. mouseAlert.mu.Unlock()
  511. }
  512. }
  513. }
  514. // 消息循环(常驻,直到线程退出)
  515. var m msg
  516. for {
  517. ret, _, _ := procGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
  518. if ret == 0 {
  519. break // WM_QUIT
  520. }
  521. procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
  522. procDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
  523. }
  524. // 清理
  525. if overlay != 0 {
  526. procKillTimer.Call(overlay, timerFollow)
  527. procDestroyWindow.Call(overlay)
  528. }
  529. mouseAlert.mu.Lock()
  530. if mouseAlert.bgBrush != 0 {
  531. procDeleteObject.Call(mouseAlert.bgBrush)
  532. mouseAlert.bgBrush = 0
  533. }
  534. mouseAlert.overlayWnd = 0
  535. mouseAlert.mu.Unlock()
  536. }
  537. // wndProcAddr 返回覆盖层窗口过程地址(保持 Go 函数引用,防 GC)
  538. func (s *mouseAlertState) wndProcAddr() uintptr {
  539. if s.wndProc != 0 {
  540. return s.wndProc
  541. }
  542. s.wndProc = syscall.NewCallback(s.wndProcCallback)
  543. return s.wndProc
  544. }
  545. // wndProcCallback 气泡窗口过程:处理跟随/闪烁定时器、自定义刷新、绘制与销毁。
  546. // 此回调由 DispatchMessageW 在消息循环线程同步调用,是 Go runtime 支持的安全路径。
  547. func (s *mouseAlertState) wndProcCallback(hwnd uintptr, msg uint32, wParam uintptr, lParam uintptr) uintptr {
  548. switch msg {
  549. case wmRefresh, wmTimer:
  550. if msg == wmRefresh || uintptr(wParam) == timerFollow {
  551. // 主动用 GetCursorPos 读取当前鼠标位置(窗口线程,安全)
  552. var pt point
  553. curRet, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
  554. s.mu.Lock()
  555. if !s.active {
  556. s.mu.Unlock()
  557. procShowWindow.Call(hwnd, 0) // SW_HIDE
  558. return 0
  559. }
  560. if curRet != 0 {
  561. s.lastX, s.lastY = pt.X, pt.Y
  562. }
  563. // 到期判断
  564. if !s.stopTime.IsZero() && time.Now().After(s.stopTime) {
  565. s.active = false
  566. s.mu.Unlock()
  567. procShowWindow.Call(hwnd, 0) // SW_HIDE
  568. return 0
  569. }
  570. s.flashOn = !s.flashOn
  571. // 超长文字滚动:仅当「允许滚动」且文字宽度超过可用区时,按配置速度
  572. // 推进偏移循环滚动;否则保持静止,超出部分右侧裁剪(不滚动)。
  573. w := s.cfgWidth
  574. if w <= 0 {
  575. w = overlayWidth
  576. }
  577. if s.cfgScroll && s.textWidth > w-24 {
  578. step := int32(s.cfgSpeed * 60 / 1000) // 每 60ms 帧推进(px)
  579. if step < 1 {
  580. step = 1
  581. }
  582. s.scrollX += step
  583. // 头尾相联无缝循环:滚动一个完整周期(文字宽 + 间隔)后归零,
  584. // 下一份正好接上,形成连续跑马灯。
  585. cycle := s.textWidth + s.textGap
  586. if cycle <= 0 {
  587. cycle = s.textWidth + 40
  588. }
  589. if s.scrollX > cycle {
  590. s.scrollX = 0
  591. }
  592. } else {
  593. s.scrollX = 0
  594. }
  595. x, y := s.lastX, s.lastY
  596. s.mu.Unlock()
  597. s.positionAndDraw(hwnd, x, y)
  598. return 0
  599. }
  600. return 0
  601. case wmPaint:
  602. // WM_PAINT 用普通 GDI 绘制气泡(背景 + 文字)。分层窗口已设 LWA_COLORKEY
  603. // 抠透明,此处只画内容,不调用 UpdateLayeredWindow(会接管窗口)。
  604. // 双缓冲:先在内存 DC(兼容位图)上合成背景+文字,再一次性 BitBlt 上屏,
  605. // 避免多遍描边 + 正文逐笔直接画到屏幕导致滚动时闪烁。
  606. var ps paintstruct
  607. hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
  608. if hdc != 0 {
  609. s.mu.Lock()
  610. fw, fh := s.cfgWidth, s.cfgHeight
  611. s.mu.Unlock()
  612. if fw <= 0 {
  613. fw = overlayWidth
  614. }
  615. if fh <= 0 {
  616. fh = overlayHeight
  617. }
  618. // 创建内存 DC + 兼容位图作为双缓冲画布
  619. memDC, _, _ := procCreateCompatibleDC.Call(hdc)
  620. memBmp, _, _ := procCreateCompatibleBitmap.Call(hdc, uintptr(fw), uintptr(fh))
  621. oldBmp, _, _ := procSelectObject.Call(memDC, memBmp)
  622. if memDC != 0 && memBmp != 0 {
  623. // 背景:填满整个客户区(LWA_COLORKEY 把该色抠成透明,只留文字)
  624. var full rect
  625. full.Left = 0
  626. full.Top = 0
  627. full.Right = fw
  628. full.Bottom = fh
  629. if s.bgBrush != 0 {
  630. procFillRect.Call(memDC, uintptr(unsafe.Pointer(&full)), s.bgBrush)
  631. }
  632. // 文字:在内存 DC 上绘制(TRANSPARENT 背景模式,不覆盖气泡背景)
  633. s.paintText(memDC)
  634. // 一次性把合成结果拷贝上屏,避免逐笔绘制的闪烁
  635. procBitBlt.Call(hdc, 0, 0, uintptr(fw), uintptr(fh), memDC, 0, 0, 0x00CC0020 /* SRCCOPY */)
  636. }
  637. // 清理双缓冲对象
  638. if memDC != 0 {
  639. procSelectObject.Call(memDC, oldBmp)
  640. if memBmp != 0 {
  641. procDeleteObject.Call(memBmp)
  642. }
  643. procDeleteDC.Call(memDC)
  644. }
  645. procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
  646. }
  647. return 0
  648. case wmDestroy, wmNcDestroy:
  649. procKillTimer.Call(hwnd, timerFollow)
  650. return 0
  651. }
  652. ret, _, _ := procDefWindowProc.Call(hwnd, uintptr(msg), wParam, lParam)
  653. return ret
  654. }
  655. // positionAndDraw 把气泡窗口定位到鼠标旁,设置整体 alpha,并触发 WM_PAINT 重绘。
  656. // 窗口线程内调用。绘制本身由 WM_PAINT(普通 GDI)完成。
  657. // 不闪烁:固定 alpha=235(此前 60ms 翻转 235↔150 导致闪烁严重,已去掉)。
  658. func (s *mouseAlertState) positionAndDraw(overlay uintptr, x, y int32) {
  659. if overlay == 0 {
  660. return
  661. }
  662. s.mu.Lock()
  663. w, h := s.cfgWidth, s.cfgHeight
  664. if w <= 0 {
  665. w = overlayWidth
  666. }
  667. if h <= 0 {
  668. h = overlayHeight
  669. }
  670. above := s.aboveMode
  671. s.mu.Unlock()
  672. var left, top int32
  673. if above {
  674. // 正上方模式(资源管理器悬停标签提示):气泡水平居中于鼠标、置于光标正上方,
  675. // 留 8px 间隙,既不遮挡光标,也不与资源管理器原有的信息提示(光标右下方)重叠。
  676. left = x - w/2
  677. top = y - h - 8
  678. // 顶部越界(鼠标太靠近屏幕顶)时,回退到光标下方显示,保证可见
  679. if top < 0 {
  680. left = x + 20
  681. top = y + 24
  682. }
  683. } else {
  684. // 默认:气泡左上角位于鼠标右下偏移,避免遮挡光标
  685. left = x + 20
  686. top = y + 24
  687. }
  688. // 背景透明(LWA_COLORKEY)只在创建窗口时设置一次,避免每帧重复设置导致闪烁。
  689. // 定位 + 显示(不激活)
  690. procSetWindowPos.Call(overlay, hwndTopMost,
  691. uintptr(int32(left)), uintptr(int32(top)),
  692. uintptr(w), uintptr(h), swpNoActivate|swpShowWindow)
  693. // 触发重绘(WM_PAINT 绘制背景 + 文字)
  694. procInvalidateRect.Call(overlay, 0, 0)
  695. }
  696. // paintText 在指定 HDC 上绘制白色提示文字(WM_PAINT 内调用,窗口线程)。
  697. // 用 DrawTextW + 系统字体 + TRANSPARENT 背景模式:只画字形、不填充背景,
  698. // 这样不会覆盖 FillRect 画的气泡背景(此前 OPAQUE 模式导致文字区被填成黑色
  699. // 背景而不可见)。
  700. func (s *mouseAlertState) paintText(hdc uintptr) {
  701. s.mu.Lock()
  702. text := s.text
  703. scrollX := s.scrollX
  704. fontSize := s.cfgFontSize
  705. textColor := s.cfgTextColor
  706. outlineColor := s.cfgOutlineColor
  707. outlineWidth := s.cfgOutlineWidth
  708. width := s.cfgWidth
  709. s.mu.Unlock()
  710. if text == "" || hdc == 0 {
  711. return
  712. }
  713. if fontSize <= 0 {
  714. fontSize = DefaultMouseAlertFontSize // 默认 20px
  715. }
  716. if textColor == 0 {
  717. textColor = 0x00FFFFFF // 默认白字
  718. }
  719. if outlineColor == 0 {
  720. outlineColor = 0x00000000 // 默认黑边
  721. }
  722. if width <= 0 {
  723. width = overlayWidth
  724. }
  725. // TRANSPARENT:只画字形,不填背景(保留气泡背景)
  726. procSetBkMode.Call(hdc, 1)
  727. procSetTextColor.Call(hdc, textColor)
  728. // 大字体:CreateFontW 按配置字号创建清晰字体
  729. // 参数:h=-fontSize(px), w=0, esc=0, orient=0, weight=FW_NORMAL(400), italic=0,
  730. // underline=0, strikeout=0, charset=DEFAULT_CHARSET(1), outprec=0, clipprec=0,
  731. // quality=ANTIALIASED(4), pitch=0, face=微软雅黑
  732. facePtr, _ := syscall.UTF16PtrFromString("Microsoft YaHei")
  733. var fontH int32 = -fontSize // 负值=像素高度(字号 px),用变量避免常量溢出
  734. hFont, _, _ := procCreateFontW.Call(
  735. uintptr(fontH), 0, 0, 0, 400, 0, 0, 0,
  736. 1 /* DEFAULT_CHARSET */, 0, 0, 4 /* ANTIALIASED */, 0,
  737. uintptr(unsafe.Pointer(facePtr)),
  738. )
  739. if hFont == 0 {
  740. // 回退系统字体
  741. hFont, _, _ = procGetStockObject.Call(17) // DEFAULT_GUI_FONT
  742. }
  743. if hFont != 0 {
  744. procSelectObject.Call(hdc, hFont)
  745. }
  746. // 测量文字像素宽度(选中字体下),判断是否需要滚动
  747. textPtr, _ := syscall.UTF16PtrFromString(text)
  748. var ext size
  749. procGetTextExtentPoint32W.Call(hdc, uintptr(unsafe.Pointer(textPtr)),
  750. uintptr(len([]rune(text))), uintptr(unsafe.Pointer(&ext)))
  751. textW := ext.Cx
  752. availW := width - 24 // 左右各 12px 边距
  753. s.mu.Lock()
  754. s.textWidth = textW
  755. s.mu.Unlock()
  756. // 文字垂直居中:气泡高度 = 字号 + 34,上下留白各约 (34-字号)/2 + 基线偏移
  757. baseY := (fontSize + 10) / 2 // 字形基线 y 坐标(垂直居中)
  758. // 单行绘制(TextOutW)+ 超长时按 scrollX 偏移。文字从左边距开始画,
  759. // 滚动时整体向左平移(x - scrollX),实现文字从右向左循环滚动。
  760. // 文字超长时先画两遍(偏移 和 偏移+周期)实现头尾相联无缝循环。
  761. //
  762. // 描边反差:为避免文字在任意背景(亮/暗)上看不清,先用描边色把文字
  763. // 向 8 个方向各偏移 outlineWidth 各画一遍形成外描边(stroke),最后用
  764. // 正文色在中心画一遍(fill),构成带色边的文字,形成颜色反差。
  765. textLen := uintptr(len([]rune(text)))
  766. leftX := int32(12) - scrollX
  767. s.mu.Lock()
  768. scroll := s.cfgScroll
  769. s.mu.Unlock()
  770. if textW > availW && scroll {
  771. // 头尾相联:第二份从「文字头 + 文字宽 + 间隔」开始画,间隔为两个空格
  772. s.mu.Lock()
  773. gap := s.textGap
  774. s.mu.Unlock()
  775. if gap < 4 {
  776. gap = 4
  777. }
  778. // 第一遍:当前偏移处(文字头)
  779. s.drawOutlinedText(hdc, textPtr, textLen, leftX, baseY, outlineColor, outlineWidth, textColor)
  780. // 第二遍:文字头 + 文字宽 + 间隔,实现头尾相联无缝循环
  781. s.drawOutlinedText(hdc, textPtr, textLen, leftX+textW+gap, baseY, outlineColor, outlineWidth, textColor)
  782. } else if textW > availW {
  783. // 不滚动:超长部分右侧裁剪(TextOutW 超出窗口区域自然被裁),只画一份
  784. s.drawOutlinedText(hdc, textPtr, textLen, 12, baseY, outlineColor, outlineWidth, textColor)
  785. } else {
  786. // 未超长:左对齐单行
  787. s.drawOutlinedText(hdc, textPtr, textLen, 12, baseY, outlineColor, outlineWidth, textColor)
  788. }
  789. }
  790. // drawOutlinedText 绘制带描边的文字:先用 outlineColor 在 8 方向各偏移
  791. // outlineWidth 描一圈形成外轮廓,再在中心用 textColor 画正文字形。
  792. // outlineWidth<=0 时不描边,直接画正文(等同旧行为)。
  793. func (s *mouseAlertState) drawOutlinedText(hdc uintptr, textPtr *uint16, textLen uintptr, x, y int32, outlineColor uintptr, outlineWidth int32, textColor uintptr) {
  794. if textLen == 0 {
  795. return
  796. }
  797. draw := func(dx, dy int32, color uintptr) {
  798. procSetTextColor.Call(hdc, color)
  799. procTextOutW.Call(hdc, uintptr(x+dx), uintptr(y+dy), uintptr(unsafe.Pointer(textPtr)), textLen)
  800. }
  801. if outlineWidth > 0 {
  802. // 8 方向外描边(每像素偏移),形成环绕轮廓,避免不同背景下文字难辨认
  803. for dy := -outlineWidth; dy <= outlineWidth; dy++ {
  804. for dx := -outlineWidth; dx <= outlineWidth; dx++ {
  805. if dx == 0 && dy == 0 {
  806. continue
  807. }
  808. draw(dx, dy, outlineColor)
  809. }
  810. }
  811. }
  812. // 中心正文字形
  813. draw(0, 0, textColor)
  814. }
  815. // renderBubbleToDib 已移除:回退到 WM_PAINT 普通 GDI 绘制方案(见 wmPaint/paintText)。
  816. // 分层窗口用 LWA_ALPHA 整体半透明,不再用 DIB + UpdateLayeredWindow。