How can I get the current active window while running the script package?

I have a script package. I want to run hot keys, and this script should do some actions in the active window (for example, creating a specific set of folders or lowercase names of all files inside a folder). Thus, the script should refer to the active window when it is called.

I tried to leave the Start at field of the alias blank, but repeating% cd% always prints "C: \ Windows \ System32" instead of the currently active window.

+4
source share
2 answers

You can find which process got the window in the foreground using pinvoke user32.dll. I used this trick for the system.window.forms.sendkeys method in a script:

Add-Type @" using System; using System.Runtime.InteropServices; public class Tricks { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); } "@ $a = [tricks]::GetForegroundWindow() get-process | ? { $_.mainwindowhandle -eq $a } # in my case: Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 161 7 13984 15820 91 9,75 7720 Console 
+9
source

For those looking for a solution other than Powershell, here is a script package that uses cscript to invoke a JScript block. JScript creates a new child process, gets its PID, and then approaches the line ParentProcessID ancestors until it reaches explorer.exe , and then returns the PID of the direct child. It should return the correct PID for the console window in which the script is running, even if there are multiple instances of cmd.exe or cscript.exe .

What can I say? Today I felt creative.

 @if (@ a==@b ) @end /* JScript multiline comment :: begin batch portion @echo off setlocal for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0"') do ( echo PID of this console window is %%I ) goto :EOF :: end batch portion / begin JScript */ var oShell = WSH.CreateObject('wscript.shell'), johnConnor = oShell.Exec('%comspec% /k @echo;'); // returns PID of the direct child of explorer.exe function getTopPID(PID, child) { var proc = GetObject("winmgmts:Win32_Process=" + PID); // uncomment the following line to watch the script walk up the ancestor tree // WSH.Echo(proc.name + ' has a PID of ' + PID); return (proc.name == 'explorer.exe') ? child : getTopPID(proc.ParentProcessID, PID); } var PID = getTopPID(johnConnor.ProcessID); johnConnor.Terminate(); // send the console window to the back for a second, then refocus, just to show off oShell.SendKeys('%{ESC}'); WSH.Sleep(1000); oShell.AppActivate(PID); // output PID of console window WSH.Echo(PID); 
+1
source

Source: https://habr.com/ru/post/1401624/


All Articles