Search code examples
node.jswinapielectronnode-ffi

Detect when the user unlocks the workstation


I'm trying to detect when a user unlocks their workstation. The following code attempts to register the window to receive session change messages using WTSRegisterSessionNotification(). Supposedly after this I can listen for WM_WTSSESSION_CHANGE which can contain WTS_SESSION_UNLOCK as a param.

Issue: Currently WTSRegisterSessionNotification() always returns false.

Anyone know how I can achieve this? I'm on Windows 10 btw.

var {remote} = require('electron');
var ffi = require('ffi');
var winctl = require('winctl');

var NOTIFY_FOR_ALL_SESSIONS = 1;
var WM_WTSSESSION_CHANGE = parseInt('0x02B1', 16);

var hwnd = remote.getCurrentWindow().getNativeWindowHandle();

var wtsapi32 = ffi.Library('wtsapi32', {
  'WTSRegisterSessionNotification': [ 'bool', [ 'int', 'int' ] ]
});

// Attempt to register
var isregistered = wtsapi32.WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_ALL_SESSIONS);

console.log(isregistered); // <----- RETURNS 0...?

IInspectable recommended GetLastError(). This is not something supported by node-ffi unfortunately. https://github.com/node-ffi/node-ffi/issues/261


Solution

  • Ended up giving up on this. I verified that the HWND was correct but it still wouldn't work for whatever reason. I ended up writing a small function in C# and executed it from within node/electron using node-edge.