@@ -7,20 +7,19 @@ namespace ComputerLock.Platforms;
77/// </summary>
88public class HotkeyHook : IDisposable
99{
10+ private List < int > ids = new List < int > ( ) ;
11+
1012 [ DllImport ( "user32.dll" ) ]
1113 private static extern bool RegisterHotKey ( IntPtr hWnd , int id , uint fsModifiers , uint vk ) ;
1214
1315 [ DllImport ( "user32.dll" ) ]
1416 private static extern bool UnregisterHotKey ( IntPtr hWnd , int id ) ;
1517
16- private const int HotkeyId = 90 ;
17- private bool _isRegistered ;
18-
19- public event Action ? HotkeyPressed ;
18+ public event Action < int > ? HotkeyPressed ;
2019
2120 private sealed class HotkeyNativeWindow : NativeWindow
2221 {
23- public event Action ? OnHotkeyPressed ;
22+ public event Action < int > ? OnHotkeyPressed ;
2423
2524 public HotkeyNativeWindow ( )
2625 {
@@ -31,10 +30,7 @@ protected override void WndProc(ref Message m)
3130 {
3231 if ( m . Msg == 0x0312 ) // WM_HOTKEY
3332 {
34- if ( m . WParam . ToInt32 ( ) == HotkeyId )
35- {
36- OnHotkeyPressed ? . Invoke ( ) ;
37- }
33+ OnHotkeyPressed ? . Invoke ( m . WParam . ToInt32 ( ) ) ;
3834 }
3935 else
4036 {
@@ -48,38 +44,32 @@ protected override void WndProc(ref Message m)
4844 public HotkeyHook ( )
4945 {
5046 _nativeWindow = new HotkeyNativeWindow ( ) ;
51- _nativeWindow . OnHotkeyPressed += ( ) => HotkeyPressed ? . Invoke ( ) ;
47+ _nativeWindow . OnHotkeyPressed += ( id ) => HotkeyPressed ? . Invoke ( id ) ;
5248 }
5349
5450 /// <summary>
5551 /// 注册快捷键
5652 /// </summary>
57- public void Register ( Hotkey hotKey )
53+ public void Register ( int id , Hotkey hotKey )
5854 {
59- if ( _isRegistered )
55+ var success = RegisterHotKey ( _nativeWindow . Handle , id , ( uint ) hotKey . Modifiers , ( uint ) hotKey . Key ) ;
56+ if ( ! success )
6057 {
61- Unregister ( ) ;
58+ throw new Exception ( $ "注册快捷键失败。id( { id } )" ) ;
6259 }
6360
64- var success = RegisterHotKey ( _nativeWindow . Handle , HotkeyId , ( uint ) hotKey . Modifiers , ( uint ) hotKey . Key ) ;
65- if ( ! success )
61+ if ( ! ids . Contains ( id ) )
6662 {
67- throw new Exception ( "注册快捷键失败" ) ;
63+ ids . Add ( id ) ;
6864 }
69- _isRegistered = success ;
7065 }
7166
7267 /// <summary>
7368 /// 注销快捷键
7469 /// </summary>
75- public void Unregister ( )
70+ public void Unregister ( int id )
7671 {
77- if ( ! _isRegistered )
78- {
79- return ;
80- }
81- UnregisterHotKey ( _nativeWindow . Handle , HotkeyId ) ;
82- _isRegistered = false ;
72+ UnregisterHotKey ( _nativeWindow . Handle , id ) ;
8373 }
8474
8575 public void Dispose ( )
@@ -95,7 +85,10 @@ protected virtual void Dispose(bool disposing)
9585 return ;
9686 }
9787
98- Unregister ( ) ;
88+ foreach ( var id in ids )
89+ {
90+ Unregister ( id ) ;
91+ }
9992 _nativeWindow . DestroyHandle ( ) ;
10093 }
10194
0 commit comments