Is it possible to put a command into a batch file that will enter text into a specified window and hit the enter key as if the user was interacting with it?
I know of a handy little exe for command prompt called "keystuff" that is capable of changing windows and inserting text, but i cant find where it has the capability to specify which window to change to since it just utilizes Alt+Tab to change the window.
You can, sort of -- but not entirely reliably, and not with pure Batch. You can use the Wscript.Shell
COM object both for its AppActivate
and SendKeys
methods. AppActivate
will let you change the focus to another window either by its PID or its title. When focusing by window title, the match is first attempted by full title, then title beginning, then title ending, in that order. So, for example, if you wanted to send keystrokes to Firefox, you could just shellObj.AppActivate('Firefox')
(because Firefox tabs end in "Mozilla Firefox").
Unfortunately, there's no easy way to specify what part of the window gets the focus. If you want to SendKeys
to the URL bar but the Search bar was last focused before the window was last blurred, then keys get sent to the Search bar. There's no way around that unless you simulate keyboard navigation (something like Ctrl+F to focus the Find-in-page, then Tab four times to focus the URL bar). It can get a little messy.
Caveats aside, here's an example Batch + Jscript hybrid script (save it with a .bat extension) demonstrating both the AppActivate
and the SendKeys
methods. See the SendKeys
TechNet article for a cheat sheet of symbols and their meanings (such as ~
sending Enter).
@if (@CodeSection == @Batch) @then
@echo off
setlocal
if "%~2"=="" (
echo usage: %~nx0 "window title" "keys to send"
echo See https://technet.microsoft.com/en-us/library/ee156592.aspx
goto :EOF
)
cscript /nologo /e:Jscript "%~f0" "%~1" "%~2"
goto :EOF
@end // end batch / begin JScript chimera
var osh = WSH.CreateObject('WScript.Shell'),
args = { title: WSH.Arguments(0), keys: WSH.Arguments(1) };
function type(what) {
var keys = what.split('{PAUSE}');
for (var i=0; i<keys.length;) {
osh.SendKeys(keys[i]);
if (++i < keys.length) WSH.Sleep(500);
}
}
osh.AppActivate(args.title);
type(args.keys);
Using this script, if you enter
scriptname.bat "Firefox" "^f{BS}{PAUSE}{TAB 4}{PAUSE}http://www.google.com~{PAUSE}^f{ESC}"
... you'll focus Firefox, send Ctrl+F to open or focus find-in-page, Backspace to erase any existing search string, Tab to the URL bar, navigate to Google, then close the find-in-page footer bar.
See? I told you. Messy. But doable.