@@ -75,7 +75,46 @@ On macOS running the global hook requires that the main run-loop be present. lib
7575is run on the main thread. It's also taken care of by UI frameworks since they need an event loop on the main thread
7676to run. But if you're using a global hook in a console app or a background service and want to run it on some thread
7777other than the main one then you should take care of it yourself. You can do that by P/Invoking the native
78- ` CFRunLoopRun ` function on the main thread.
78+ ` CFRunLoopRun ` function on the main thread:
79+
80+
81+ ``` c#
82+ internal static partial class CoreFoundation
83+ {
84+ private const string CoreFoundationLib = " /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation" ;
85+
86+ [LibraryImport (CoreFoundationLib )]
87+ public static partial void CFRelease (IntPtr @ref );
88+
89+ // It's better to use a type derived from SafeHandle as the return type, but it's omitted for brevity
90+ [LibraryImport (CoreFoundationLib )]
91+ public static partial IntPtr CFRunLoopGetCurrent ();
92+
93+ [LibraryImport (CoreFoundationLib )]
94+ public static partial void CFRunLoopRun ();
95+
96+ [LibraryImport (CoreFoundationLib )]
97+ public static partial void CFRunLoopStop (IntPtr rl );
98+ }
99+
100+ // ...
101+
102+ // This method must be called on the main thread
103+ public static void RunMainLoop (CancellationToken token )
104+ {
105+ var loop = CoreFoundation .CFRunLoopGetCurrent ();
106+ token .Register (() => CoreFoundation .CFRunLoopStop (loop ));
107+ CoreFoundation .CFRunLoopRun (); // This method will block the current thread until CFRunLoopStop is called
108+ CoreFoundation .CFRelease (loop ); // Ideally, this method should be called when a SafeHandle is released instead
109+ }
110+
111+ // ...
112+
113+ var tokenSource = new CancellationTokenSource ();
114+ hook .HookDisabled += (sender , e ) => tokenSource .Cancel ();
115+ _ = hook .RunAsync (); // Ignore the result of RunAsync, do not await it
116+ RunMainLoop (tokenSource .Token );
117+ ```
79118
80119### Simulating Multiple Mouse Clicks
81120
0 commit comments