Two steps: first use UpdateDeviceState() instead of replicating the device changing code. And emulate XI events instead of core events.
Two steps: first use UpdateDeviceState() instead of replicating the device changing code. And emulate XI events instead of core events.