I want to create tracking software, which can track which application/software/tools is open currently. Basically I want to get current Active Window. In case If you have multiple screens then I want to get current active window in both the screens.
I also want to check if there’s any software/tools running which keeps some software always keep on top, if possible.
How can I achieve this using Node.js.
Is there any specific library available for this?
I tried some low level C++ Code and compile it using node-gyp
and ran it. I was able to get current active window, but it is only for single screen, What if I have multiple screen and two different program is opened in those screen? I want those two programs.
Here’s C++ Code:
addon.cc
file
#include <napi.h>
#include <windows.h>
#include <Psapi.h>
Napi::Object GetActiveWindowInfo(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
HWND hwnd = GetForegroundWindow();
const int nMaxCount = 256;
TCHAR szWindowTitle[nMaxCount];
DWORD pid;
// Retrieve the window title
GetWindowText(hwnd, szWindowTitle, nMaxCount);
// Retrieve the process ID (PID) of the active window
GetWindowThreadProcessId(hwnd, &pid);
// Get the process handle using the PID
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
if (hProcess != NULL) {
// Retrieve the process name
GetModuleFileNameEx(hProcess, NULL, szProcessName, MAX_PATH);
CloseHandle(hProcess);
}
// Construct the return object
Napi::Object result = Napi::Object::New(env);
result.Set("title", Napi::String::New(env, szWindowTitle));
result.Set("processName", Napi::String::New(env, szProcessName));
return result;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("getActiveWindowInfo", Napi::Function::New(env, GetActiveWindowInfo));
return exports;
}
NODE_API_MODULE(addon, Init)
binding.gyp
file
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ],
"include_dirs": [
"<!@(node -p "require('node-addon-api').include")"
],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"defines": [
"NAPI_CPP_EXCEPTIONS"
],
"libraries": []
}
]
}
app.js
file
const addon = require("./build/Release/addon.node");
setInterval(() => {
const windowInfo = addon.getActiveWindowInfo();
console.log("Window Title:", windowInfo.title);
console.log("Process Name:", windowInfo.processName);
}, 1000);
package.json
file
{
"name": "addon",
"version": "1.0.0",
"description": "Node.js addon",
"main": "addon.cc",
"scripts": {
"build": "node-gyp configure build"
},
"dependencies": {
"node-addon-api": "^8.0.0"
}
}
How to Run
npm install
npm run build
node app.js