Is it a bug to pass a single-element array to SendInput?

Short answer: Maybe.

Longer answer: It depends.

To see what it depends on, and when this matters, it helps to understand, why SendInput was introduced into the Windows API: For one, it consolidates the keybd_event and mouse_event APIs into a single API call. More importantly, it adds a significant feature that isn’t available to the previous calls. This is called out in the documentation:

The SendInput function inserts the events in the INPUT structures serially into the keyboard or mouse input stream. These events are not interspersed with other keyboard or mouse input events inserted either by the user (with the keyboard or mouse) or by calls to keybd_event, mouse_event, or other calls to SendInput.

In other words: SendInput establishes atomicity of injected input sequences, irrespective of external events outside the control of the calling code.

It is usually important to atomically inject input, when the input consists of a sequence of individual events, like in the question. The code injects a mouse button down followed by a mouse button up in 2 individual calls to SendInput. While the intention is to have a single mouse click event, the implementation allows other input sources to intersperse input. When another input source produces a mouse move event in between the mouse button down and up events, the intended click has turned into a drag-and-drop operation. Instead of selecting a file in File Explorer, that very same code has thrown the file into the Recycle Bin. That clearly constitutes a bug.

Likewise, injecting keyboard input consisting of key combinations generally requires atomicity guarantees. Injecting Ctrl+C requires all four input events to be in a single transaction. Otherwise, a (malicious) input source could synthesize a Ctrl key up event right after the Ctrl key down, leaving the code injecting a C, with a stray Ctrl key up event trailing. That’s probably not what was intended either.

In summary: It is a bug to call SendInput repeatedly, passing 1 as the first argument if the following conditions are true:

  • The input consists of a sequence of individual input events.
  • The input is required to be interpreted as a single unit.

Leave a Comment