Skip to content

Instantly share code, notes, and snippets.

@ceymard
Last active August 29, 2015 14:10
Show Gist options
  • Save ceymard/c54a19469abd18f9f3c7 to your computer and use it in GitHub Desktop.
Save ceymard/c54a19469abd18f9f3c7 to your computer and use it in GitHub Desktop.
// You need to `npm install ref ffi` for the following code to run.
// What it does basically is get the foreground window in windows and fetch its
// title and the path of the .exe that launched it.
var ref = require('ref');
var ffi = require('ffi');
var stringPtr = ref.refType('string');
var voidPtr = ref.refType('void');
var intPtr = ref.refType('int');
var user32 = new ffi.Library('user32', {
'GetForegroundWindow' : [voidPtr, []], // HWND
'GetWindowTextA' : ['int32', ['pointer', stringPtr, 'int32']],
'GetWindowThreadProcessId' : ['int32', ['pointer', intPtr]],
});
var kernel32 = new ffi.Library('kernel32', {
'OpenProcess': [voidPtr, ['int32', 'int32', 'int32']],
'CloseHandle': ['int32', [voidPtr]],
});
var psapi = new ffi.Library('psapi', {
'GetModuleFileNameExA': ['int32', [voidPtr, voidPtr, stringPtr, 'int32']],
});
var i = 0;
var str = '';
for (i = 0; i < 1024; i++) {
str += ' ';
}
// reusable buffers.
var buf = ref.allocCString(str, 'ucs2');
var pid = ref.alloc('int');
function processInfo() {
var res = {};
// handle to the currently focused window
var handle = user32.GetForegroundWindow();
// Get the currently focused window title.
user32.GetWindowTextA(handle, buf, buf.length);
res.title = ref.readCString(buf, 0);
// Get the PID of the process to query its name later on.
user32.GetWindowThreadProcessId(handle, pid);
res.pid = pid.deref();
// QUERY_INFORMATION | VM_READ
var process = kernel32.OpenProcess(0x0400 | 0x0010, false, pid.deref());
// Get the process path
psapi.GetModuleFileNameExA(process, null, buf, buf.length);
res.process = ref.readCString(buf, 0);
// free the memory of the handle.
kernel32.CloseHandle(handle);
return res;
}
setTimeout(function () {
console.log(processInfo());
}, 2000);
exports.getProcessInfo = processInfo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment