John O
John O

Reputation: 5423

Is it possible to determine the window/application with focus from a bat script?

The function to do so is apparently in User32.dll. I've been trying to tinker with rundll32.exe, but when I run this:

rundll32 User32.dll,GetActiveWindow

It exits without error but does nothing. The exit code will of course only say whether or not there were errors running rundll32.

Is there a bat scripting trick to retrieve that value and stuff it into a variable?

Upvotes: 0

Views: 1019

Answers (1)

James L.
James L.

Reputation: 9451

The Window API functions are not designed to be called like that from DOS. You need to create a console application that runs minimized. It can call the GetActiveWindow() function and write the application title out to STDOUT. Then you can assign that value to an environment variable in the batch file like this:

setlocal ENABLEDELAYEDEXPANSION
for /f "delims=" %%i in ('start /wait /min YourCustomApp.exe') do set somevar=%%i
echo The active program is "!somevar!".
endlocal

The /wait /min make the batch file wait until your app has terminated before trying to assign the value on STDOUT to somevar. I like to use ENABLEDELAYEDEXPANSION whenever I assign an environment variable in a batch file and then use it later in the same batch file.

Upvotes: 1

Related Questions