Is it possible to react (via StylusButtonDown etc., or alternatives) to button presses (i.e. one of the stylus buttons, not buttons in some app) that happen when the stylus/pen is not touching the screen, i.e. hovering in the air somewhere in range of the notebook? Those only seem to trigger if the pen tip is actually touching the surface of the screen. Specifically, I do not need to know about the position of the button. Just literally when the barrel button is pressed.
I'm using a Microsoft Surface and the Surface Pen that comes with it in particular, if that makes any difference. I don't need it to be cross-platform, portable or anything. In fact, solutions in other languages (C++, etc.) are OK. Hacky solutions are very welcome.
AutoHotKey is the answer!
AutoHotKey is an open source tool that helps create custom automated responses to Windows input device events.
AutoHotKey supports Surface Pen. It also supports the scenario of pen being away from screen.
Surface Pen connects to Windows via Bluetooth, with a signal range of several metres. Therefore, it is technically possible to use a Surface pen as a remote controller for Windows!
One of the most popular scenarios is Using Surface Pen as a Presentation controller
Here is a working AutoHotKey script for controlling Powerpoint presentation with Surface Pen:
; File name: surface-pen-slide-show-control.ahk
;
; This program helps the presenter scroll through slides, using Surface Pen
;
; Single-click on pen button to scroll forward
; Double-click on pen button to scroll backward
;
#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%
#IfWinActive ahk_class screenClass
#F20::
Send, {Right}
Return
#F19::
Send, {Left}
Return
More information and Help:
The Complete Reference on AutoHotKey: https://www.autohotkey.com/
Demo code (pen away from screen): https://github.com/jonathanyip/Surface-Pro-3-AutoHotkey/blob/master/Pen.ah