mousealert_windows.go 32 KB

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