Detect Mouse and keyboard events globally #923
Unanswered
alihassan143
asked this question in
Q&A
Replies: 2 comments 1 reply
-
static bool _isMonitoring = false;
static int _keyboardHook = 0;
static int _mouseHook = 0;
//
static void startMonitoring() {
if (_isMonitoring) return;
_isMonitoring = true;
// Set keyboard hook
_keyboardHook = SetWindowsHookEx(
WINDOWS_HOOK_ID.WH_KEYBOARD_LL,
Pointer.fromFunction<HOOKPROC>(_keyboardProc, 0),
GetModuleHandle(nullptr),
0,
);
if (_keyboardHook == 0) {
debugPrint("Failed to set keyboard hook: ${GetLastError()}");
_isMonitoring = false;
return;
}
// Set mouse hook
_mouseHook = SetWindowsHookEx(
WINDOWS_HOOK_ID.WH_MOUSE_LL,
Pointer.fromFunction<HOOKPROC>(_mouseProc, 0),
GetModuleHandle(nullptr),
0,
);
if (_mouseHook == 0) {
UnhookWindowsHookEx(_keyboardHook); // Clean up if mouse hook fails
debugPrint("Failed to set mouse hook: ${GetLastError()}");
_isMonitoring = false;
return;
}
debugPrint("Monitoring started.");
}
static void stopMonitoring() {
if (!_isMonitoring) return;
_isMonitoring = false;
if (_keyboardHook != 0) {
UnhookWindowsHookEx(_keyboardHook);
_keyboardHook = 0; // Reset the hook
}
if (_mouseHook != 0) {
UnhookWindowsHookEx(_mouseHook);
_mouseHook = 0; // Reset the hook
}
debugPrint("Monitoring stopped.");
}
static int _keyboardProc(int nCode, int wParam, int lParam) {
debugPrint("Keyboard event: wParam=$wParam, lParam=$lParam");
if (nCode >= 0) {
debugPrint("Keyboard event: wParam=$wParam, lParam=$lParam");
_keyBoardState.value = KeyboardState.active;
}
return CallNextHookEx(_keyboardHook, nCode, wParam, lParam);
}
static int _mouseProc(int nCode, int wParam, int lParam) {
if (nCode >= 0) {
debugPrint("Mouse event: wParam=$wParam, lParam=$lParam");
_mouseState.value = MouseState.active;
}
return CallNextHookEx(_mouseHook, nCode, wParam, lParam);
} I am not getting any event what will be the issue ? |
Beta Was this translation helpful? Give feedback.
1 reply
-
You need to create a Win32 window and run a message loop in another isolate, similar to the usb_drive.dart example and the example I gave in #912. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
@halildurmus is there is way to detect mouse movement and mouse clicks and any keyboard button click events
Beta Was this translation helpful? Give feedback.
All reactions