I’m trying to get the current active window in Nodejs and Electron.
I’ve tried literally every package available but all are unsopported or not working.
I’m able to access the list of the current running applications on Windows 11, but cannot know what is the one active now.
I can get the list of the current running apps with this:
function getOpenApplications(callback) {
const command = `powershell "gps | where {$_.MainWindowTitle} | select-object Description, Id, MainWindowTitle"`;
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Errore durante l'esecuzione del comando: ${error.message}`);
return;
}
if (stderr) {
console.error(`Errore standard: ${stderr}`);
return;
}
callback(stdout);
});
}
But I can only see the movements inside the windows of my electron app when running this:
function getFocusedApp(callback) {
const command = 'powershell "(gps | Where-Object {$_.MainWindowTitle} | Sort-Object StartTime -Descending | Select-Object -First 1).MainWindowTitle"';
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Errore durante l'esecuzione del comando: ${error.message}`);
return;
}
if (stderr) {
console.error(`Errore standard: ${stderr}`);
return;
}
callback(stdout);
});
}
Also this is a powershell script i found that is working when launched on Powershell but not on my code, it return empty:
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class APIFuncs
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hwnd,StringBuilder
lpString, int cch);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern Int32 GetWindowThreadProcessId(IntPtr hWnd,out
Int32 lpdwProcessId);
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern Int32 GetWindowTextLength(IntPtr hWnd);
}
"@
$w = [apifuncs]::GetForegroundWindow()
$len = [apifuncs]::GetWindowTextLength($w)
$sb = New-Object text.stringbuilder -ArgumentList ($len + 1)
$rtnlen = [apifuncs]::GetWindowText($w,$sb,$sb.Capacity)
write-host "Window Title: $($sb.tostring())"
Doublegram is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.