使用 SetWindowsHookEx 要留意的地方

最近在公司發現一個小問題,

當我們在 Debug Process A 的時候 (Process A 處於 break mode),

如果我們在其它 Process B 例如: Chrome、記事本有打字的話,Process B 會直接 hang 住。

而造成這個現象的原因是來自於公司之前有人為了做熱鍵功能,

因此使用 SetWindowsHookEx hook global keyboard event。

但是由於 Process A 在 break mode,所以 OS 沒辦法將 keyboard event 交給 Process A 處理,

因此 OS 只能 suspend Process B 直到 keyboard event 被 Process A 處理完成。

補充說明一下:以上是 Windows 10 針對 SetWindowsHookEx 行為,不同版本可能有不同行為。

例如: 在 Windows 7 則是會將 DLL Inject 到其它 Process ,

但因為 Windows 7 有 64 位元的版本,所以 DLL 可能會有位元相容性問題,

針對不能相容的 DLL,Windows 7 行為跟 Windows 10 相同 (Context switch 回 Process A),

至於能相容的 Process 則不需要 Context switch (所以也不會有卡住的問題)。

了解整個來龍去脈後,要解決問題就簡單了,

第一種就是在編譯 Debug 版本不 hook global keyboard event (workaround),

第二種就是改用 RegisterHotKey 處理熱鍵 ,

第二種才是比較好的解法,

因為熱鍵而要 hook global keyboard event 非常不合理 (有資安上疑慮),

且其行為一般會被防毒軟體視為惡意軟體,

因此大家要做熱鍵功能還是乖乖使用 RegisterHotKey 吧 ~

留言

  1. If might have} by no means performed a sport at an internet on line casino earlier than, all of this will appear astonishing. However, we can't 카지노사이트 emphasize enough want to|the necessity to} discover the platform earlier than placing your data there. Online on line casino video games may be addictive, but it's far from inevitable that you're going to get hooked. If think you studied} you are be} changing into addicted, want to} stop instantly and get remedy.

    回覆刪除

張貼留言

這個網誌中的熱門文章

[面試心得] Synology / 群暉 - Product Developr

[面試心得] VICI Holdings / 威旭(高頻交易) - Software Engineer

[面試心得] GoFreight / 聖學科技(Freight Forwarder) - Full-Stack Engineer