我正在尝试获取 Nodejs 和 Electron 中当前的活动窗口。
我几乎尝试了所有可用的软件包,但所有软件包都不支持或无法工作。
我可以访问 Windows 11 上当前正在运行的应用程序的列表,但无法知道现在正在运行的应用程序是什么。
我可以通过以下方式获取当前正在运行的应用程序的列表:
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);
});
}
但是运行此命令时我只能看到电子应用程序窗口内的移动:
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);
});
}
这也是一个 powershell 脚本,我发现它在 Powershell 上启动时有效,但在我的代码上无效,它返回空:
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())"
我找到了解决方案:
为了清楚起见,在另一个文件中运行 powershell
const command = `powershell -File "C:\\Users\\lenovo\\Desktop\\Creofeel-nodejs\\Communication\\ps.ps1"`;
并在 ps.ps1 上使用此脚本:
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class User32Methods {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
$foregroundHandle = [User32Methods]::GetForegroundWindow()
$foregroundProcess = Get-Process |
Where-Object { $_.MainWindowHandle -eq $foregroundHandle } |
Sort-Object StartTime -Descending |
Select-Object -First 1
$foregroundProcess.MainWindowTitle