Skip to content

Instantly share code, notes, and snippets.

@fernandojunior
Created July 13, 2017 19:06
Show Gist options
  • Save fernandojunior/f3830baa2495dded70d15ab27505446a to your computer and use it in GitHub Desktop.
Save fernandojunior/f3830baa2495dded70d15ab27505446a to your computer and use it in GitHub Desktop.
Handle monitor(s) changes in Windows
const { spawn } = require('child_process');
/**
* Handle monitor(s) changes, ig, perform an action when a monitor is connected or disconnected.
*
* Notes:
* - Windows implementation is based on Windows Management Interface (WMI) and WMI Query Language (WQL)
*
* Reference:
* - https://stackoverflow.com/questions/5278860/using-wmi-to-identify-which-device-caused-a-win32-devicechangeevent
* - https://msdn.microsoft.com/en-us/library/aa394651(v=vs.85).aspx
* - http://wiki.splunk.com/Receive_events_whenever_someone_plugs/unplugs_a_USB_device
* - https://msdn.microsoft.com/en-us/library/aa392902(v=vs.85).aspx
*
* @param handler {function} A function to handle monitor changes
*/
function onMonitorChanged(handler) {
const MONITOR_CHANGED = 'monitor_changed';
const wql = "SELECT * FROM __InstanceOperationEvent WITHIN 0.5 WHERE TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.SERVICE = 'monitor'";
const command = `Register-WMIEvent -Query "${wql}" -Action { Write-Host "${MONITOR_CHANGED}"} > $null`;
const child = spawn('powershell.exe', [command]);
child.stdout.on('data', (data) => {
if (data.toString() === MONITOR_CHANGED) {
handler();
}
});
child.stderr.on('data', (data) => {
logger.error(`Powershell Errors: ${data}`);
});
child.on('exit', () => {
console.log('Powershell Script finished');
});
// child.stdin.end(); //end input
}
onMonitorChanged(() => console.log('monitor-changed'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment