### Install uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Install the uiohook-napi package using npm. ```bash npm install uiohook-napi ``` -------------------------------- ### start() Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Starts the global input hook, enabling the dispatch of keyboard and mouse events. This method should be called after setting up all desired event listeners. ```APIDOC ## Method: start() Starts the global input hook. Events will begin being dispatched after this is called. ### Signature ```typescript start(): void ``` **Returns:** `void` **Throws:** Multiple error types listed in [errors.md](../errors.md) **Behavior:** - Initializes the native input hook on the current platform - Enters an event loop that monitors keyboard and mouse input - All events are dispatched to registered listeners after this call - Should be called after setting up all event listeners with `on()` **Example:** ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { console.log('Key down:', e.keycode) }) // Start listening for input events uIOhook.start() ``` ``` -------------------------------- ### Start uIOhook Singleton and Listen to Keydown Events Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Use the uIOhook singleton to register a 'keydown' event listener and then start the global input hook. This is the recommended way to use the library. ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { console.log('Key down:', e.keycode) }) // Start listening for input events uIOhook.start() ``` -------------------------------- ### Start uiohook-napi with Graceful Degradation Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This snippet demonstrates how to start the uiohook-napi and provides a fallback mechanism if the hook is unavailable. It logs success or a warning with the error message. ```typescript import { uIOhook } from 'uiohook-napi' async function startHook() { try { uIOhook.start() console.log('Input hook started successfully') return true } catch (e) { console.warn('Input hook unavailable:', e.message) return false } } startHook().then((success) => { if (!success) { console.log('Falling back to other input methods') } }) ``` -------------------------------- ### Basic Event Listening Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Start listening for keyboard, mouse, and wheel events. Imports the necessary uIOhook and UiohookKey objects. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' uIOhook .on('keydown', (e) => console.log('Key:', e.keycode)) .on('mousemove', (e) => console.log(`Mouse: ${e.x}, ${e.y}`)) .on('wheel', (e) => console.log('Wheel:', e.amount)) .start() ``` -------------------------------- ### Basic Try-Catch for uiohook-napi Start Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This is a fundamental error handling pattern for starting the uIOhook input hook. It uses a try-catch block to gracefully handle potential errors during the `start()` operation and logs the error message. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook .on('keydown', (e) => console.log('Key:', e.keycode)) .start() } catch (e) { console.error('Failed to start input hook:', e.message) process.exit(1) } ``` -------------------------------- ### Start uiohook-napi with Retry Mechanism Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This function attempts to start the uiohook-napi multiple times with a delay between attempts. It's useful for transient errors during startup. The maximum number of attempts can be configured. ```typescript import { uIOhook } from 'uiohook-napi' async function startHookWithRetry(maxAttempts = 3) { for (let i = 0; i < maxAttempts; i++) { try { uIOhook.start() console.log('Hook started successfully') return true } catch (e) { console.log(`Attempt ${i + 1} failed:`, e.message) if (i < maxAttempts - 1) { await new Promise(resolve => setTimeout(resolve, 1000)) } } } console.error(`Failed to start hook after ${maxAttempts} attempts`) return false } ``` -------------------------------- ### Instantiate UiohookNapi and Listen to Keydown Events Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Create a new instance of UiohookNapi, set up a listener for the 'keydown' event to log the keycode, and then start the hook. ```typescript import { UiohookNapi } from 'uiohook-napi' const hook = new UiohookNapi() hook.on('keydown', (e) => console.log('Key pressed:', e.keycode)) hook.start() ``` -------------------------------- ### Error Handling for Starting the Hook Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Safely start the uIOhook service within a try-catch block to handle potential errors during initialization. Exits the process if startup fails. ```typescript try { uIOhook.start() } catch (e) { console.error('Failed to start input hook:', e.message) process.exit(1) } ``` -------------------------------- ### Listen for Mouse Wheel Events Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Example of how to register a listener for the 'wheel' event and log scroll direction and amount. Ensure 'uiohook-napi' is imported. ```typescript import { uIOhook, WheelDirection } from 'uiohook-napi' uIOhook.on('wheel', (e: UiohookWheelEvent) => { const direction = e.direction === WheelDirection.VERTICAL ? 'vertical' : 'horizontal' const amount = e.rotation > 0 ? 'down/right' : 'up/left' console.log(`${direction} scroll ${amount} by ${e.amount}`) }) ``` -------------------------------- ### Listen for Keydown Events and Remove Listener Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Demonstrates how to listen for 'keydown' events using uiohook-napi. It includes an example of removing a specific listener when a certain key (Escape) is pressed. Ensure uIOhook is started before listening for events. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' const escapeHandler = (e) => { if (e.keycode === UiohookKey.Escape) { console.log('Escape pressed, removing listener') uIOhook.off('keydown', escapeHandler) } } uIOhook.on('keydown', escapeHandler) uIOhook.start() ``` -------------------------------- ### Using the Exported uIOhook Singleton Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md The `uIOhook` singleton instance is the recommended way to interact with the library. Import it directly and use its methods like `on` and `start` for event handling and hook activation. ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { console.log('Key:', e.keycode) }) uIOhook.start() ``` -------------------------------- ### Basic Usage of uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Start listening for keyboard events and stop when the Escape key is pressed. Requires importing necessary components from 'uiohook-napi'. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' uIOhook.on('keydown', (e) => { console.log(`Key pressed: ${e.keycode}`) if (e.keycode === UiohookKey.Escape) { uIOhook.stop() } }) uIOhook.start() ``` -------------------------------- ### Exported Singleton Instance (uIOhook) Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Provides a pre-configured, exported singleton instance of `UiohookNapi` for immediate use. This is the recommended approach for interacting with the uiohook-napi library, simplifying setup and ensuring consistent access to the input monitoring functionality. ```APIDOC ## Exported Singleton ### uIOhook ```typescript export const uIOhook: UiohookNapi ``` A pre-created singleton instance of `UiohookNapi` available for immediate use. **Source:** `src/index.ts:271` **Usage:** ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { console.log('Key:', e.keycode) }) uIOhook.start() ``` This is the recommended way to use the library; in most cases you do not need to create additional instances. ``` -------------------------------- ### Platform-Specific Error Handling for uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This snippet demonstrates how to implement platform-specific error handling when starting the uIOhook. It checks the operating system and specific error messages to provide tailored advice for Linux, macOS, and Windows. ```typescript import { uIOhook } from 'uiohook-napi' import { platform } from 'os' try { uIOhook.start() } catch (e) { if (platform() === 'linux' && e.message.includes('X11')) { console.error('X11 display not available on Linux') } else if (platform() === 'darwin' && e.message.includes('AXAPI')) { console.error('Grant Accessibility permissions on macOS') } else if (platform() === 'win32' && e.message.includes('hook')) { console.error('May require administrator privileges on Windows') } else { console.error('Unknown error:', e.message) } } ``` -------------------------------- ### Simulate Key Tap (keyTap) Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Simulates a complete key tap action, which includes pressing and releasing a key. This method can optionally apply modifier keys like Ctrl, Shift, Alt, or Meta simultaneously with the key tap. It does not require the input hook to be started. ```APIDOC ## Method: keyTap ### Description Simulates a key tap (press and release). Optionally applies modifier keys. ### Method `keyTap(key: number, modifiers?: number[]): void` ### Parameters #### Path Parameters - **key** (number) - Required - The keycode to tap (see `UiohookKey`) - **modifiers** (number[]) - Optional - Array of modifier keycodes (Ctrl, Shift, Alt, Meta) to apply simultaneously ### Response #### Success Response (200) - **void** ### Behavior: - If no modifiers, sends a key press followed by key release - If modifiers provided: 1. Presses each modifier in order 2. Presses and releases the main key 3. Releases each modifier in reverse order - Does not require the hook to be started ### Request Example: ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Simple key tap uIOhook.keyTap(UiohookKey.A) // Key tap with Ctrl+Shift modifiers uIOhook.keyTap(UiohookKey.S, [UiohookKey.Ctrl, UiohookKey.Shift]) // Equivalent to Ctrl+C uIOhook.keyTap(UiohookKey.C, [UiohookKey.Ctrl]) ``` ``` -------------------------------- ### Catching UIOHOOK_ERROR_GET_RUNLOOP on macOS Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This snippet shows how to catch the error that occurs when the `start()` function is not called from the main thread on macOS. It specifically checks for 'UIOHOOK_ERROR_GET_RUNLOOP' in the error message. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_GET_RUNLOOP')) { console.error('Must call start() from the main thread on macOS') } } ``` -------------------------------- ### UiohookNapi Class Methods Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md The UiohookNapi class is the core manager for input event hooks. It provides methods to start and stop event monitoring, register listeners, and simulate keyboard input. ```APIDOC ## UiohookNapi Class Methods ### `start()` **Description**: Begin listening for input events. ### `stop()` **Description**: Stop listening and clean up resources. ### `on(event, listener)` **Description**: Register event listeners. Listens for various input events like 'keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove', 'click', and 'wheel'. ### `keyTap(key, modifiers?)` **Description**: Simulate a key press and release. - **key** (string | number) - The key to tap. - **modifiers** (string[] | number[]) - Optional. An array of modifier keys (e.g., 'Ctrl', 'Shift'). ### `keyToggle(key, toggle)` **Description**: Press or release a key. - **key** (string | number) - The key to toggle. - **toggle** (boolean) - `true` to press the key, `false` to release it. ``` -------------------------------- ### Simulate Key Toggle (keyToggle) Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Simulates either pressing ('down') or releasing ('up') a key without performing the opposite action. This is useful for scenarios where a key needs to be held down while other actions occur, such as typing other characters or simulating modifier key states. It does not require the input hook to be started. ```APIDOC ## Method: keyToggle ### Description Simulates a key press or release (without the opposite action). ### Method `keyToggle(key: number, toggle: 'down' | 'up'): void` ### Parameters #### Path Parameters - **key** (number) - Required - The keycode to toggle (see `UiohookKey`) - **toggle** ('down' | 'up') - Required - `'down'` to press, `'up'` to release ### Response #### Success Response (200) - **void** ### Behavior: - `'down'` — Sends a key press without a corresponding release - `'up'` — Sends a key release without a prior press - Useful for holding down a key while sending other keystrokes - Does not require the hook to be started ### Request Example: ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Hold Shift and press A uIOhook.keyToggle(UiohookKey.Shift, 'down') uIOhook.keyTap(UiohookKey.A) uIOhook.keyToggle(UiohookKey.Shift, 'up') ``` ``` -------------------------------- ### Catching UIOHOOK_ERROR_AXAPI_DISABLED on macOS Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This snippet demonstrates how to catch the specific error that occurs when Accessibility API permissions are not granted on macOS. It checks the error message for 'UIOHOOK_ERROR_AXAPI_DISABLED' after attempting to start the hook. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_AXAPI_DISABLED')) { console.error('Accessibility permissions not granted on macOS') } } ``` -------------------------------- ### Stop uIOhook Singleton on Escape Key Press Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Listen for keydown events and stop the uIOhook global input hook when the Escape key is pressed. Ensure the hook is started before this listener becomes active. ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Escape) { console.log('Stopping hook...') uIOhook.stop() } }) uIOhook.start() ``` -------------------------------- ### Main Class Methods Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md This section details the core methods available on the `uIOhook` instance for managing input event listening and simulation. ```APIDOC ## `start()` ### Description Begin listening for input events. ### Method `start()` ### Returns `void` ## `stop()` ### Description Stop listening and release resources. ### Method `stop()` ### Returns `void` ## `on(event, listener)` ### Description Register an event listener. This method is chainable. ### Method `on(event, listener)` ### Parameters #### Arguments - **event** (string) - The type of event to listen for (e.g., 'keydown', 'mousemove'). - **listener** (function) - The callback function to execute when the event occurs. ### Returns `this` (for chaining) ## `keyTap(key, modifiers?)` ### Description Simulate a key press and release. ### Method `keyTap(key, modifiers?)` ### Parameters #### Arguments - **key** (UiohookKey) - The key to tap. - **modifiers** (Array, optional) - An array of modifier keys to hold during the tap. ### Returns `void` ## `keyToggle(key, toggle)` ### Description Press or release a key without simulating a full tap. ### Method `keyToggle(key, toggle)` ### Parameters #### Arguments - **key** (UiohookKey) - The key to toggle. - **toggle** (string) - Either 'down' to press the key or 'up' to release it. ### Returns `void` ``` -------------------------------- ### File Organization Structure Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Illustrates the directory structure of the uiohook-napi project, including source files, native addon implementation, and build configurations. ```text uiohook-napi/ ├── src/ │ ├── index.ts # Main TypeScript entry point │ ├── demo.ts # Demo application │ └── lib/ │ ├── addon.c # N-API native addon implementation │ ├── napi_helpers.c # Helper functions │ └── uiohook_worker.c # Worker thread implementation ├── libuiohook/ # Git submodule: libuiohook source ├── binding.gyp # Build configuration ├── package.json # Package metadata └── dist/ # Compiled output (generated) ├── index.js # Compiled JavaScript └── index.d.ts # TypeScript declarations ``` -------------------------------- ### Keyboard Event Handling and Simulation Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Demonstrates how to listen for keyboard events and simulate key presses with modifiers using the uIOhook library. Ensure you import `uIOhook` and `UiohookKey` before use. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Listen for specific key uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.A) { console.log('A key was pressed') } }) // Simulate key press with modifiers uIOhook.keyTap(UiohookKey.C, [UiohookKey.Ctrl]) // Ctrl+C // Toggle modifier key uIOhook.keyToggle(UiohookKey.Shift, 'down') // Hold Shift ``` -------------------------------- ### Basic Event Listener for Keydown Source: https://github.com/snosme/uiohook-napi/blob/master/README.md This snippet demonstrates how to listen for keydown events and react to specific key presses like 'Q' or 'Escape'. It requires importing `uIOhook` and `UiohookKey` from the library. The `uIOhook.start()` function must be called to begin listening for events. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Q) { console.log('Hello!') } if (e.keycode === UiohookKey.Escape) { process.exit(0) } }) uIOhook.start() ``` -------------------------------- ### Exports Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md This section lists the main exports from the `uiohook-napi` library, including the singleton instance, class definitions, and type/enum constants. ```APIDOC ## Exports ### `uIOhook` - **Type:** `UiohookNapi` - **Description:** A pre-created singleton instance of the event hook manager. ### `UiohookNapi` - **Type:** class - **Description:** The main class responsible for managing input hooks and events. ### `EventType` - **Type:** enum - **Description:** Constants representing different types of input events. ### `UiohookKeyboardEvent` - **Type:** interface - **Description:** Defines the structure of keyboard event objects. ### `UiohookMouseEvent` - **Type:** interface - **Description:** Defines the structure of mouse event objects. ### `UiohookWheelEvent` - **Type:** interface - **Description:** Defines the structure of mouse wheel event objects. ### `WheelDirection` - **Type:** enum - **Description:** Constants indicating the direction of mouse wheel scrolling (vertical or horizontal). ### `UiohookKey` - **Type:** object - **Description:** An object containing mappings for various keycodes, useful for keyboard simulation and detection. ``` -------------------------------- ### Control Methods Source: https://github.com/snosme/uiohook-napi/blob/master/README.md Provides methods to programmatically control keyboard input, such as tapping a key or toggling key states. ```APIDOC ## Control Methods ### Description Programmatically simulate keyboard input. ### Methods #### `keyTap(key: keycode, modifiers?: keycode[])` Simulates a key tap (press and release). - **key**: The keycode of the key to tap. - **modifiers**: An optional array of keycodes for modifier keys (e.g., Shift, Ctrl). #### `keyToggle(key: keycode, toggle: 'down' | 'up')` Simulates pressing or releasing a key. - **key**: The keycode of the key to toggle. - **toggle**: Specifies whether to press ('down') or release ('up') the key. ``` -------------------------------- ### Event Listeners (on) Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Register callback functions to listen for various input events like key presses, mouse movements, and wheel scrolls. Multiple listeners can be added for the same event, and they are executed in the order they were registered. The `on` method supports method chaining. ```APIDOC ## Method: on ### Description Registers a listener function for a specified event. ### Method `on(event: string, listener: function): this` ### Parameters #### Path Parameters - **event** (string) - Required - Event name: `'input'`, `'keydown'`, `'keyup'`, `'mousedown'`, `'mouseup'`, `'mousemove'`, `'click'`, `'wheel'` - **listener** (function) - Required - Callback function that receives the event object ### Response #### Success Response (200) - **this** (this) - Returns the instance for chainability ### Event Types: - **`'input'`** — Any input event (keyboard, mouse, wheel). Emitted before type-specific events. - **`'keydown'`** — Key pressed down (corresponds to `EventType.EVENT_KEY_PRESSED`) - **`'keyup'`** — Key released (corresponds to `EventType.EVENT_KEY_RELEASED`) - **`'mousedown'`** — Mouse button pressed (corresponds to `EventType.EVENT_MOUSE_PRESSED`) - **`'mouseup'`** — Mouse button released (corresponds to `EventType.EVENT_MOUSE_RELEASED`) - **`'mousemove'`** — Mouse cursor moved (corresponds to `EventType.EVENT_MOUSE_MOVED`) - **`'click'`** — Mouse button clicked (corresponds to `EventType.EVENT_MOUSE_CLICKED`) - **`'wheel'`** — Mouse wheel scrolled (corresponds to `EventType.EVENT_MOUSE_WHEEL`) ### Behavior: - Listeners are called with the event object as the only argument - Multiple listeners can be registered for the same event - Listeners are called in the order they were registered - This method returns the instance for chainability ### Request Example: ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Listen to all input events uIOhook.on('input', (e) => { console.log('Input event:', e.type) }) // Listen to specific key uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Q) { console.log('Q key pressed') } }) // Chain multiple listeners uIOhook .on('mousemove', (e) => console.log(`Mouse at ${e.x}, ${e.y}`)) .on('wheel', (e) => console.log(`Wheel amount: ${e.amount}`)) .start() ``` ``` -------------------------------- ### Simulating Key Taps with uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md The `keyTap` method simulates a key press followed by a release. It can optionally include modifier keys like Ctrl, Shift, Alt, or Meta, which are pressed before the main key and released afterward. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Simple key tap uIOhook.keyTap(UiohookKey.A) // Key tap with Ctrl+Shift modifiers uIOhook.keyTap(UiohookKey.S, [UiohookKey.Ctrl, UiohookKey.Shift]) // Equivalent to Ctrl+C uIOhook.keyTap(UiohookKey.C, [UiohookKey.Ctrl]) ``` -------------------------------- ### Registering Event Listeners with uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Use the `on` method to register callback functions for various input events like 'input', 'keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove', 'click', and 'wheel'. Multiple listeners can be added for the same event. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Listen to all input events uIOhook.on('input', (e) => { console.log('Input event:', e.type) }) // Listen to specific key uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Q) { console.log('Q key pressed') } }) // Chain multiple listeners uIOhook .on('mousemove', (e) => console.log(`Mouse at ${e.x}, ${e.y}`)) .on('wheel', (e) => console.log(`Wheel amount: ${e.amount}`)) .start() ``` -------------------------------- ### on() Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Registers an event listener for input events. This method supports multiple overloads for different event types. ```APIDOC ## Method: on() Registers an event listener. Has multiple overloads for different event types. ``` -------------------------------- ### Event Types and Listeners Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md uiohook-napi supports various event types that can be listened to using the `on()` method. These include general input events, specific keyboard and mouse actions, and mouse wheel events. ```APIDOC ## Event Types and Listeners Register listeners using `uIOhook.on(event, listener)`: - **'input'**: Catches all types of input events. - **'keydown'**: Fires when a keyboard key is pressed down. - **'keyup'**: Fires when a keyboard key is released. - **'mousedown'**: Fires when a mouse button is pressed down. - **'mouseup'**: Fires when a mouse button is released. - **'mousemove'**: Fires when the mouse cursor is moved. - **'click'**: Fires when a mouse button is clicked (pressed and released). - **'wheel'**: Fires when the mouse wheel is scrolled. ``` -------------------------------- ### uIOhook Singleton Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md The uIOhook singleton is a pre-created instance of the UiohookNapi class, ready to be used immediately for event monitoring and simulation without explicit instantiation. ```APIDOC ## uIOhook Singleton **Description**: A pre-created instance of the `UiohookNapi` class that is available for immediate use. You can call methods like `start()`, `stop()`, and `on()` directly on `uIOhook`. ``` -------------------------------- ### Handle Input Events by Type Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Demonstrates how to use the EventType enum with the 'input' event listener to differentiate between various input actions like key presses and mouse movements. ```typescript import { uIOhook, EventType } from 'uiohook-napi' uIOhook.on('input', (e) => { switch (e.type) { case EventType.EVENT_KEY_PRESSED: console.log('Key pressed') break case EventType.EVENT_MOUSE_MOVED: console.log('Mouse moved') break } }) ``` -------------------------------- ### Event Listeners Source: https://github.com/snosme/uiohook-napi/blob/master/README.md The `uIOhook` object allows you to register listeners for various input events such as keyboard, mouse, and wheel events. The `on` method takes an event name and a callback function that receives event data. ```APIDOC ## Event Listeners ### Description Register listeners for input events. ### Method `on(event: string, listener: function): this` ### Parameters #### Event Types - **input**: Listens for any input event (keyboard, mouse, wheel). - **keydown**: Listens for key press events. - **keyup**: Listens for key release events. - **mousedown**: Listens for mouse button down events. - **mouseup**: Listens for mouse button up events. - **mousemove**: Listens for mouse movement events. - **click**: Listens for mouse click events. - **wheel**: Listens for mouse wheel scroll events. #### Listener Function Parameters - **e**: An object containing event details. The structure of `e` depends on the event type: - **UiohookKeyboardEvent**: `altKey`, `ctrlKey`, `metaKey`, `shiftKey`, `keycode` - **UiohookMouseEvent**: `altKey`, `ctrlKey`, `metaKey`, `shiftKey`, `x`, `y`, `button`, `clicks` - **UiohookWheelEvent**: `altKey`, `ctrlKey`, `metaKey`, `shiftKey`, `x`, `y`, `clicks`, `amount`, `direction`, `rotation` ### Example ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Q) { console.log('Q key pressed!') } }) uIOhook.start() ``` ``` -------------------------------- ### Simulate Keyboard Input Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Simulate single key taps, key taps with modifiers, and holding/releasing keys. Uses UiohookKey for key identification. ```typescript // Single key uIOhook.keyTap(UiohookKey.A) // With modifiers uIOhook.keyTap(UiohookKey.S, [UiohookKey.Ctrl, UiohookKey.Shift]) // Hold and release uIOhook.keyToggle(UiohookKey.Shift, 'down') uIOhook.keyTap(UiohookKey.A) uIOhook.keyToggle(UiohookKey.Shift, 'up') ``` -------------------------------- ### UiohookNapi Constructor Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Creates a new instance of the UiohookNapi class, which manages global input event hooks. This instance extends Node.js EventEmitter. ```APIDOC ## Class: UiohookNapi Extends: `EventEmitter` The main class for registering and handling global input events. ### Constructor ```typescript new UiohookNapi() ``` **Returns:** `UiohookNapi` instance **Example:** ```typescript import { UiohookNapi } from 'uiohook-napi' const hook = new UiohookNapi() hook.on('keydown', (e) => console.log('Key pressed:', e.keycode)) hook.start() ``` ``` -------------------------------- ### Log Keyboard Event Details Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Logs details of a keyboard event, such as the keycode and modifier key states, when a 'keydown' event occurs. Requires importing UiohookKeyboardEvent for type safety. ```typescript import { uIOhook, UiohookKey, EventType } from 'uiohook-napi' uIOhook.on('keydown', (e: UiohookKeyboardEvent) => { console.log(`Key ${e.keycode} pressed at ${new Date(e.time)}`) console.log(`Alt: ${e.altKey}, Ctrl: ${e.ctrlKey}, Shift: ${e.shiftKey}`) }) ``` -------------------------------- ### uiohook-napi API Interface Source: https://github.com/snosme/uiohook-napi/blob/master/README.md Defines the main interface for the uiohook-napi library, including event listeners for various input types and methods for key manipulation. This interface outlines the available events and functions for interacting with the system's input devices. ```typescript interface UiohookNapi { on(event: 'input', listener: (e: UiohookKeyboardEvent | UiohookMouseEvent | UiohookWheelEvent) => void): this on(event: 'keydown', listener: (e: UiohookKeyboardEvent) => void): this on(event: 'keyup', listener: (e: UiohookKeyboardEvent) => void): this on(event: 'mousedown', listener: (e: UiohookMouseEvent) => void): this on(event: 'mouseup', listener: (e: UiohookMouseEvent) => void): this on(event: 'mousemove', listener: (e: UiohookMouseEvent) => void): this on(event: 'click', listener: (e: UiohookMouseEvent) => void): this on(event: 'wheel', listener: (e: UiohookWheelEvent) => void): this keyTap(key: keycode, modifiers?: keycode[]) keyToggle(key: keycode, toggle: 'down' | 'up') } ``` -------------------------------- ### Event Listeners Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md This section lists the available events that can be listened to and the type of data passed to their respective callbacks. ```APIDOC ## Event Listeners ### `'input'` - **Callback Parameter:** `UiohookKeyboardEvent | UiohookMouseEvent | UiohookWheelEvent` - **Emitted When:** Any input event occurs. ### `'keydown'` - **Callback Parameter:** `UiohookKeyboardEvent` - **Emitted When:** A key is pressed. ### `'keyup'` - **Callback Parameter:** `UiohookKeyboardEvent` - **Emitted When:** A key is released. ### `'mousedown'` - **Callback Parameter:** `UiohookMouseEvent` - **Emitted When:** A mouse button is pressed. ### `'mouseup'` - **Callback Parameter:** `UiohookMouseEvent` - **Emitted When:** A mouse button is released. ### `'mousemove'` - **Callback Parameter:** `UiohookMouseEvent` - **Emitted When:** The mouse pointer is moved. ### `'click'` - **Callback Parameter:** `UiohookMouseEvent` - **Emitted When:** A mouse click is registered. ### `'wheel'` - **Callback Parameter:** `UiohookWheelEvent` - **Emitted When:** The mouse wheel is scrolled. ``` -------------------------------- ### Catch UIOHOOK_ERROR_X_OPEN_DISPLAY Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md Handle errors when the X11 display cannot be opened, which is necessary for input hooking on Linux. This can happen if running headless or if the DISPLAY environment variable is not set. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_X_OPEN_DISPLAY')) { console.error('X11 display not available') } } ``` -------------------------------- ### Catch UIOHOOK_ERROR_SET_WINDOWS_HOOK_EX Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md Handle errors related to failing to register a low-level Windows hook. This may require administrator privileges or indicate a conflict with other hooking applications. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_SET_WINDOWS_HOOK_EX')) { console.error('Failed to register Windows hook, may require administrator privileges') } } ``` -------------------------------- ### Toggling Key Presses and Releases with uiohook-napi Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Use `keyToggle` to simulate pressing ('down') or releasing ('up') a key without the opposite action. This is useful for holding keys, such as Shift, while performing other actions. ```typescript import { uIOhook, UiohookKey } from 'uiohook-napi' // Hold Shift and press A uIOhook.keyToggle(UiohookKey.Shift, 'down') uIOhook.keyTap(UiohookKey.A) uIOhook.keyToggle(UiohookKey.Shift, 'up') ``` -------------------------------- ### Graceful Shutdown on Exit Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/README.md Register a process listener for SIGINT to ensure uIOhook is stopped and resources are released before the application exits. Imports uIOhook. ```typescript import { uIOhook } from 'uiohook-napi' process.on('SIGINT', () => { console.log('Shutting down...') uIOhook.stop() process.exit(0) }) ``` -------------------------------- ### Log Mouse Movement and Click Events Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Logs the coordinates of the mouse cursor during movement and detects double-clicks. Requires importing UiohookMouseEvent for type safety. ```typescript import { uIOhook, EventType } from 'uiohook-napi' uIOhook.on('mousemove', (e: UiohookMouseEvent) => { console.log(`Mouse at (${e.x}, ${e.y})`) }) uIOhook.on('click', (e: UiohookMouseEvent) => { if (e.clicks === 2) { console.log(`Double click at (${e.x}, ${e.y})`) } }) ``` -------------------------------- ### UiohookKeyboardEvent Interface Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Represents an event object emitted for keyboard input. It includes details about the key pressed or released, along with modifier key states. ```APIDOC ## Interface: UiohookKeyboardEvent Event object emitted for keyboard input. | Field | Type | Description | |-------|------|-------------| | `type` | `EventType.EVENT_KEY_PRESSED | EventType.EVENT_KEY_RELEASED` | The event type (key pressed or released) | | `time` | `number` | Unix timestamp in milliseconds when the key event occurred | | `altKey` | `boolean` | True if Alt key was held during the event | | `ctrlKey` | `boolean` | True if Control key was held during the event | | `metaKey` | `boolean` | True if Meta/Windows key was held during the event | | `shiftKey` | `boolean` | True if Shift key was held during the event | | `keycode` | `number` | The keycode of the pressed/released key (see `UiohookKey` constants) | **Events:** Emitted by `'keydown'` and `'keyup'` event listeners, and also by `'input'` listener. **Example:** ```typescript import { uIOhook, UiohookKey, EventType } from 'uiohook-napi' uIOhook.on('keydown', (e: UiohookKeyboardEvent) => { console.log(`Key ${e.keycode} pressed at ${new Date(e.time)}`) console.log(`Alt: ${e.altKey}, Ctrl: ${e.ctrlKey}, Shift: ${e.shiftKey}`) }) ``` ``` -------------------------------- ### Catching Generic UIOHOOK_FAILURE Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md This snippet provides a general catch-all for any unmapped error codes from the libuiohook library. It logs the error message when an unexpected hook error occurs. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { console.error('Unexpected hook error:', e.message) } ``` -------------------------------- ### stop() Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/api-reference/uiohook-napi.md Stops the global input hook, ceasing the dispatch of all input events and releasing native resources. This method can be safely called multiple times. ```APIDOC ## Method: stop() Stops the global input hook. ### Signature ```typescript stop(): void ``` **Returns:** `void` **Throws:** Throws if already stopped or on memory allocation failure (see [errors.md](../errors.md)) **Behavior:** - Stops the event dispatch loop - Releases the native hook resources - No further events will be emitted after this call - Can be called multiple times without error if already stopped **Example:** ```typescript import { uIOhook } from 'uiohook-napi' uIOhook.on('keydown', (e) => { if (e.keycode === UiohookKey.Escape) { console.log('Stopping hook...') uIOhook.stop() } }) uIOhook.start() ``` ``` -------------------------------- ### Catch UIOHOOK_ERROR_OUT_OF_MEMORY Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md Handle errors indicating memory allocation failures during hook initialization or cleanup. This typically occurs when the system is low on memory. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_OUT_OF_MEMORY')) { console.error('Out of memory') process.exit(1) } } ``` -------------------------------- ### Catch UIOHOOK_ERROR_THREAD_CREATE Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/errors.md Catch errors related to failing to create a worker thread for the input hook. This often indicates system resource limitations. ```typescript import { uIOhook } from 'uiohook-napi' try { uIOhook.start() } catch (e) { if (e.message.includes('UIOHOOK_ERROR_THREAD_CREATE')) { console.error('Failed to create input hook thread') } } ``` -------------------------------- ### UiohookKeyboardEvent Interface Source: https://github.com/snosme/uiohook-napi/blob/master/README.md Defines the structure for keyboard event objects, including modifier key states and the keycode. This interface is used when handling keyboard-related events like keydown and keyup. ```typescript export interface UiohookKeyboardEvent { altKey: boolean ctrlKey: boolean metaKey: boolean shiftKey: boolean keycode: number } ``` -------------------------------- ### UiohookKeyboardEvent Interface Definition Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Defines the structure of event objects for keyboard input, including event type, timestamp, modifier keys, and keycode. Used with 'keydown' and 'keyup' listeners. ```typescript interface UiohookKeyboardEvent { type: EventType.EVENT_KEY_PRESSED | EventType.EVENT_KEY_RELEASED time: number altKey: boolean ctrlKey: boolean metaKey: boolean shiftKey: boolean keycode: number } ``` -------------------------------- ### UiohookWheelEvent Structure Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Details the structure of the UiohookWheelEvent object, which is emitted for mouse wheel scrolling actions. It includes information about the event type, timestamp, modifier key states, cursor coordinates, scroll amount, and direction. ```APIDOC ## Interface: UiohookWheelEvent Event object emitted for mouse wheel scrolling. ### Fields - **type** (`EventType.EVENT_MOUSE_WHEEL`) - Always `EVENT_MOUSE_WHEEL` for wheel events - **time** (`number`) - Unix timestamp in milliseconds when the wheel event occurred - **altKey** (`boolean`) - True if Alt key was held during the event - **ctrlKey** (`boolean`) - True if Control key was held during the event - **metaKey** (`boolean`) - True if Meta/Windows key was held during the event - **shiftKey** (`boolean`) - True if Shift key was held during the event - **x** (`number`) - The X (horizontal) coordinate of the mouse cursor in screen pixels - **y** (`number`) - The Y (vertical) coordinate of the mouse cursor in screen pixels - **clicks** (`number`) - The number of scroll clicks/ticks - **amount** (`number`) - The scroll amount (usually 1 per tick) - **direction** (`WheelDirection`) - Direction of scroll: `VERTICAL` or `HORIZONTAL` - **rotation** (`number`) - Rotation value (-1 for up/left, 1 for down/right) **Events:** Emitted by `'wheel'` event listener and also by `'input'` listener. ### Example ```typescript import { uIOhook, WheelDirection } from 'uiohook-napi' uIOhook.on('wheel', (e: UiohookWheelEvent) => { const direction = e.direction === WheelDirection.VERTICAL ? 'vertical' : 'horizontal' const amount = e.rotation > 0 ? 'down/right' : 'up/left' console.log(`${direction} scroll ${amount} by ${e.amount}`) }) ``` ``` -------------------------------- ### UiohookMouseEvent Interface Source: https://github.com/snosme/uiohook-napi/blob/master/_autodocs/types.md Represents an event object emitted for mouse input, including movement, button presses, and releases. It provides coordinates, button state, and click counts. ```APIDOC ## Interface: UiohookMouseEvent Event object emitted for mouse input (movement, button press/release). | Field | Type | Description | |-------|------|-------------| | `type` | `EventType` | One of: `EVENT_MOUSE_CLICKED`, `EVENT_MOUSE_MOVED`, `EVENT_MOUSE_PRESSED`, `EVENT_MOUSE_RELEASED` | | `time` | `number` | Unix timestamp in milliseconds when the mouse event occurred | | `altKey` | `boolean` | True if Alt key was held during the event | | `ctrlKey` | `boolean` | True if Control key was held during the event | | `metaKey` | `boolean` | True if Meta/Windows key was held during the event | | `shiftKey` | `boolean` | True if Shift key was held during the event | | `x` | `number` | The X (horizontal) coordinate of the mouse cursor in screen pixels | | `y` | `number` | The Y (vertical) coordinate of the mouse cursor in screen pixels | | `button` | `unknown` | The mouse button identifier (1 for left, 2 for middle, 3 for right, etc.) | | `clicks` | `number` | The number of consecutive clicks (1 for single click, 2 for double click, etc.) | **Events:** Emitted by `'mousedown'`, `'mouseup'`, `'mousemove'`, and `'click'` event listeners, and also by `'input'` listener. **Example:** ```typescript import { uIOhook, EventType } from 'uiohook-napi' uIOhook.on('mousemove', (e: UiohookMouseEvent) => { console.log(`Mouse at (${e.x}, ${e.y})`) }) uIOhook.on('click', (e: UiohookMouseEvent) => { if (e.clicks === 2) { console.log(`Double click at (${e.x}, ${e.y})`) } }) ``` ``` -------------------------------- ### UiohookWheelEvent Interface Source: https://github.com/snosme/uiohook-napi/blob/master/README.md Defines the structure for mouse wheel event objects, including modifier key states, cursor coordinates, and detailed information about the scroll action. This interface is used for handling wheel events. ```typescript export interface UiohookWheelEvent { altKey: boolean ctrlKey: boolean metaKey: boolean shiftKey: boolean x: number y: number clicks: number amount: number direction: WheelDirection rotation: number } ``` -------------------------------- ### UiohookMouseEvent Interface Source: https://github.com/snosme/uiohook-napi/blob/master/README.md Defines the structure for mouse event objects, including modifier key states, cursor coordinates, button information, and click count. This interface is used for handling mouse events such as mousedown, mouseup, mousemove, and click. ```typescript export interface UiohookMouseEvent { altKey: boolean ctrlKey: boolean metaKey: boolean shiftKey: boolean x: number y: number button: unknown clicks: number } ```