"MouseButtonClicker clicks the mouse so you don't have to!" [Releasing binaries and source for a nifty mouse utility]
I first came across the notion of automatic mouse button clicking some time ago. The basic idea can be summarized as follows:
The nearly universal pattern of mouse use is: move/click/wait... move/click/wait... move/click/wait.... In the overwhelming majority of cases, the only reason the mouse gets moved is to position the pointer over the next user interface element that needs to be clicked. Because every move is immediately followed by a click, it should be possible to simplify the process by performing the click automatically when the mouse stops moving (i.e., moves to a new location and stays still for a few moments). This automatic click saves the user only a tiny bit of effort each time it happens, but it eliminates a conceptually unnecessary, repetitive motion that's carried out many, many times over the course of every day. As an additional ergonomic benefit, automatic clicking enables the user to hold the mouse in a variety of new ways now that it's no longer necessary to keep a finger on the mouse button.
My first reaction was that the automatic clicking behavior would be nearly impossible to live with - and for the first couple of minutes I tried using it, it was. :) But, once I got out of the habit of wiggling the mouse needlessly and got into the habit of moving it where I needed when I needed, I found I quite liked the behavior after all. As I became more comfortable, I got used to the timing and found I could manage double clicks with just a single click by timing that click to happen right after the automatic click! The only challenge was to learn what parts of the user interface do nothing when clicked on - because these are the "safe areas" where the mouse can be "parked" if you start moving it and then decide you don't really want to click anything after all.
I found I liked automatic clicking so much, I wrote my own tool to implement it - and I've used that tool happily for nearly a decade. But my tool has a specific hardware dependency as a consequence of some other functionality it implements and that became a problem a few days ago when I changed hardware. So I decided this was a great opportunity to extract the clicking functionality into its own, dedicated, hardware-agnostic tool - and then blog about it!
The new tool I wrote is called MouseButtonClicker and does exactly what I describe above. It's written completely in native code - partly because I saw no need for the overhead of managed code for a simple "always-on" scenario like this one - and partly because it was a good excuse to brush up on my (rusty) native coding skills. MouseButtonClicker is a UI-less application - which means it doesn't have a window, or a notification icon, or anything to look at - it just runs invisibly and does its job. Of course, it wouldn't be hard to add a simple notification icon, but that's unnecessary for my purposes: MouseButtonClicker auto-starts with my computer and never gets closed. If you find you need to exit MouseButtonClicker, simply kill it with Task Manager or via TaskKill /IM MouseButtonClicker.exe
- MouseButtonClicker maintains no persistent state and terminating it is completely safe to do at any time. And while the standard 32-bit executable works just fine on 64-bit operating systems, I've also provided a 64-bit version for those who prefer not to mix their bits. :)
Implementation notes:
- MouseButtonClicker finds out about mouse activity via the raw input API which provides low-level access to input devices like mice and keyboards in a simple, flexible manner. Using the raw input API makes it easy to distinguish between mouse input (where automatic clicking makes sense) and input from a tablet pen or digitizer device (where it does not make sense). This is of particular interest to me because I'm a long-time user of Wacom's fine tablet products and frequently switch between mouse and pen while using my computer; having the wrong behavior for the pen would be simply unacceptable.
- MouseButtonClicker generates the automatic click with the SendInput function which provides an easy way to inject input events into the system. This works quite nicely, but it's worth noting that on recent operating systems like Vista and Server 2008, the SendInput API is restricted by User Interface Privilege Isolation. Specifically, MSDN notes that "Applications are permitted to inject input only into applications that are at an equal or lesser integrity level". It's my experience that this restriction usually exhibits itself as an inability to click processes that are running in an elevated security context (i.e., as Administrator) or to click in Command Windows that aren't currently active.
- There are a couple of cases where MouseButtonClicker suppresses the automatic click. For example, there will be no automatic click if any mouse button has been manually clicked since the mouse stopped moving or if any of the mouse buttons is currently pressed. As such, the automatic click doesn't interfere with right clicking to get a context menu, pausing while dragging a window around the screen, or simply clicking the button yourself when you're in too much of a hurry to let MouseButtonClicker do so for you!
- Some mouse hardware exhibits a small amount of "jitter" that causes single unit move messages from time to time (note: the size of a unit is less than that of a pixel, so these jitters aren't usually visible). My thinking is that this jitter is due to the mouse being *just* on the threshold of moving and then getting nudged slightly (perhaps the table gets bumped, a butterfly flaps its wings, etc.). Whatever the cause, this occasional jitter is an annoyance because it results in occasional - seemingly unprovoked - clicks wherever the mouse happens to be. So MouseButtonClicker has a small jitter-prevention measure that requires the mouse to move at least a little bit (2 units) before an automatic click will be performed.
- MouseButtonClicker deliberately does not clean up its application-level resources (like the window class it registers) because Windows contractually promises to clean such things up during process exit. I formerly believed this to be lazy, but eventually decided that the best code is code I don't have to write, debug, and maintain. :) For cases like this where someone else is already going to handle resource clean-up - probably more quickly and efficiently than I could - it seems prudent to let them do so. This approach avoids the possibility of bugs in clean-up code, keeps the executable size down (which avoids unnecessary disk access), and keeps the source code just a little bit simpler.
- The
COMPILE_TIME_ASSERT
macro provides a handy way of implementing a compile-time assert (also known as a static assert). Compile-time asserts are handy because they do the same thing normal asserts do, but they take effect at compile time and will actually fail the build process if the specified condition is not true. So instead of having to hope that the test cases exercise all the assertions in the code, the simple presence of a successful compile guarantees that all compile-time asserts are valid! - The variably-sized buffer for the WM_INPUT message is allocated on the stack via the _malloca/_freea CRT library calls. Allocating memory on the stack isn't usually appropriate, but for situations like this where a small, short-lived buffer of unknown size is needed, allocating on the stack can be more efficient than allocating on the heap.
- The delay before the automatic click is determined by the result of the GetDoubleClickTime() API. Though the delay MouseButtonClicker implements is not technically for a double-click, the result of this call is the unofficial basis for a variety of different UI timings across the system.
- Yes, I drew the icon myself; no, I don't have any artistic skill. :) It's supposed to be a robotic finger clicking a mouse button, but I agree it's probably more of a Rorschach inkblot test... If you can do better and want to send me an ICO file with 32x32 and 16x16 images I can freely redistribute, I will pick my favorite submission, include it with the next version of MouseButtonClicker, and credit you publically for your contribution.
So if you're in the mood to try something new and you don't mind a bit of a learning curve, give MouseButtonClicker a try for an hour or two. If you're lucky, you may never need to click again... :)
PS - For the benefit of casual readers and search engines, here is MouseButtonClicker.cpp:
// MouseButtonClicker - http://blogs.msdn.com/Delay // // "MouseButtonClicker clicks the mouse so you don't have to!" // // Simple Windows utility to click the primary mouse button whenever the mouse // stops moving as a usability convenience/enhancement. #include <windows.h> #include <tchar.h> #include <malloc.h> #include <strsafe.h> // Macro for compile-time assert #define COMPILE_TIME_ASSERT(e) typedef int CTA[(e) ? 1 : -1] // Constants for code simplification #define RI_ALL_MOUSE_BUTTONS_DOWN (RI_MOUSE_BUTTON_1_DOWN | RI_MOUSE_BUTTON_2_DOWN | RI_MOUSE_BUTTON_3_DOWN | RI_MOUSE_BUTTON_4_DOWN | RI_MOUSE_BUTTON_5_DOWN) #define RI_ALL_MOUSE_BUTTONS_UP (RI_MOUSE_BUTTON_1_UP | RI_MOUSE_BUTTON_2_UP | RI_MOUSE_BUTTON_3_UP | RI_MOUSE_BUTTON_4_UP | RI_MOUSE_BUTTON_5_UP) // Check that bit-level assumptions are correct COMPILE_TIME_ASSERT(RI_MOUSE_BUTTON_1_DOWN == (RI_MOUSE_BUTTON_1_UP >> 1)); COMPILE_TIME_ASSERT(RI_MOUSE_BUTTON_2_DOWN == (RI_MOUSE_BUTTON_2_UP >> 1)); COMPILE_TIME_ASSERT(RI_MOUSE_BUTTON_3_DOWN == (RI_MOUSE_BUTTON_3_UP >> 1)); COMPILE_TIME_ASSERT(RI_MOUSE_BUTTON_4_DOWN == (RI_MOUSE_BUTTON_4_UP >> 1)); COMPILE_TIME_ASSERT(RI_MOUSE_BUTTON_5_DOWN == (RI_MOUSE_BUTTON_5_UP >> 1)); COMPILE_TIME_ASSERT(RI_ALL_MOUSE_BUTTONS_DOWN == (RI_ALL_MOUSE_BUTTONS_UP >> 1)); // Macro for absolute value #define ABS(v) ((0 <= v) ? v : -v) // Application-level constants #define APPLICATION_NAME (TEXT("MouseButtonClicker")) #define TIMER_EVENT_ID (1) #define MOUSE_MOVE_THRESHOLD (2) // Window procedure LRESULT CALLBACK WndProc(const HWND hWnd, const UINT message, const WPARAM wParam, const LPARAM lParam) { // Tracks the mouse move delta threshold across calls to WndProc static LONG lLastClickDeltaX = 0; static LONG lLastClickDeltaY = 0; static bool fOkToClick = false; switch (message) { // Raw input message case WM_INPUT: { // Query for required buffer size UINT cbSize = 0; if(0 == GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, NULL, &cbSize, sizeof(RAWINPUTHEADER))) { // Allocate buffer on stack (falls back to heap) const LPVOID pData = _malloca(cbSize); if(NULL != pData) { // Get raw input data if(cbSize == GetRawInputData(reinterpret_cast<HRAWINPUT>(lParam), RID_INPUT, pData, &cbSize, sizeof(RAWINPUTHEADER))) { // Only interested in mouse input const RAWINPUT* const pRawInput = static_cast<LPRAWINPUT>(pData); if (RIM_TYPEMOUSE == pRawInput->header.dwType) { // Only interested in devices that use relative coordinates // Specifically, input from pens/tablets is ignored if(0 == (pRawInput->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) { // Tracks the state of the mouse buttons across calls to WndProc static UINT usMouseButtonsDown = 0; // Update mouse delta variables lLastClickDeltaX += pRawInput->data.mouse.lLastX; lLastClickDeltaY += pRawInput->data.mouse.lLastY; // Enable clicking once the mouse has exceeded the threshold in any direction fOkToClick |= ((MOUSE_MOVE_THRESHOLD < ABS(lLastClickDeltaX)) || (MOUSE_MOVE_THRESHOLD < ABS(lLastClickDeltaY))); // Determine the input type const UINT usButtonFlags = pRawInput->data.mouse.usButtonFlags; if(0 == (usButtonFlags & (RI_ALL_MOUSE_BUTTONS_DOWN | RI_ALL_MOUSE_BUTTONS_UP | RI_MOUSE_WHEEL))) { // Mouse move: (Re)set click timer if no buttons down and mouse moved enough to avoid jitter if((0 == usMouseButtonsDown) && fOkToClick) { // Use double-click time as an indication of the user's responsiveness preference (void)SetTimer(hWnd, TIMER_EVENT_ID, GetDoubleClickTime(), NULL); } } else { // Mouse button down/up or wheel rotation: Cancel click timer (void)KillTimer(hWnd, TIMER_EVENT_ID); // Update mouse button state variable (asserts above ensure the bit manipulations are correct) usMouseButtonsDown |= (usButtonFlags & RI_ALL_MOUSE_BUTTONS_DOWN); usMouseButtonsDown &= ~((usButtonFlags & RI_ALL_MOUSE_BUTTONS_UP) >> 1); } } } } // Free buffer (void)_freea(pData); } } } break; // Timer message case WM_TIMER: { // Timeout, stop timer and click primary button (void)KillTimer(hWnd, TIMER_EVENT_ID); INPUT pInputs[2] = {0}; pInputs[0].type = INPUT_MOUSE; pInputs[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN; pInputs[1].type = INPUT_MOUSE; pInputs[1].mi.dwFlags = MOUSEEVENTF_LEFTUP; (void)SendInput(2, pInputs, sizeof(INPUT)); // Reset mouse delta and threshold variables lLastClickDeltaX = 0; lLastClickDeltaY = 0; fOkToClick = false; } break; // Close message case WM_DESTROY: (void)PostQuitMessage(0); break; // Unhandled message default: return DefWindowProc(hWnd, message, wParam, lParam); } // Return value 0 indicates message was processed return 0; } // WinMain entry point int APIENTRY _tWinMain(const HINSTANCE hInstance, const HINSTANCE hPrevInstance, const LPTSTR lpCmdLine, const int nCmdShow) { // Avoid compiler warnings for unreferenced parameters UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); // Create a mutex to prevent running multiple simultaneous instances const HANDLE mutex = CreateMutex(NULL, FALSE, APPLICATION_NAME); if((NULL != mutex) && (ERROR_ALREADY_EXISTS != GetLastError())) { // Register the window class WNDCLASS wc = {0}; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.lpszClassName = APPLICATION_NAME; if(0 != RegisterClass(&wc)) { // Create a message-only window to receive WM_INPUT and WM_TIMER const HWND hWnd = CreateWindow(APPLICATION_NAME, APPLICATION_NAME, 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_MESSAGE, NULL, hInstance, NULL); if (NULL != hWnd) { // Register for the mouse's raw input data RAWINPUTDEVICE rid = {0}; rid.usUsagePage = 1; // HID_DEVICE_SYSTEM_MOUSE rid.usUsage = 2; // HID_DEVICE_SYSTEM_MOUSE rid.dwFlags = RIDEV_INPUTSINK; rid.hwndTarget = hWnd; if(RegisterRawInputDevices(&rid, 1, sizeof(rid))) { // Pump Windows messages MSG msg = {0}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Return success return static_cast<int>(msg.wParam); } } } // Failed to initialize, output a diagnostic message (which is not more // friendly because it represents a scenario that should never occur) TCHAR szMessage[64]; if(SUCCEEDED(StringCchPrintf(szMessage, sizeof(szMessage)/sizeof(szMessage[0]), TEXT("Initialization failure. GetLastError=%d\r\n"), GetLastError()))) { (void)MessageBox(NULL, szMessage, APPLICATION_NAME, MB_OK | MB_ICONERROR); } } // Return failure return 0; // By contract, Windows frees all resources as part of process exit }