Make DOS window active after starting a Windows app.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Make DOS window active after starting a Windows app.

#1 Post by Jer » 20 Nov 2015 16:45

Automatically return to the DOS window after starting a Windows application?

I use the start command in a large batch application I am working on,
and currently have to click back into the DOS window after
Windows Media Player has started.

If this is possible, then we'll know for certain that DOS rules. 8)

Code: Select all

@Echo Off
Set "musFile=Sample1.mp3"
start "" "%musFile%"

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Make DOS window active after starting a Windows app.

#2 Post by Aacini » 20 Nov 2015 19:15

Code: Select all

@if (@CodeSection == @Batch) @then


@Echo Off
setlocal

set "title=This is an unique title"
title %title%

rem Start a process that wait 2 seconds and reselect this window
start "" cscript //nologo //E:JScript "%~F0" "%title%"

Set "musFile=Sample1.mp3"
start "" "%musFile%"

goto :EOF


@end


// JScript section

// Wait 2 seconds
WScript.Sleep(2000);

// Set focus on the cmd.exe window
WScript.CreateObject("WScript.Shell").AppActivate(WScript.Arguments(0));

For an explanation of this code, look for "Batch JScript hybrid script" in this forum, and review these links for AppActivate and Sleep methods.

Antonio

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Make DOS window active after starting a Windows app.

#3 Post by Jer » 21 Nov 2015 12:58

Aacini, the 2-second delay can be replaced by checking if the app is running and then
activating the CMD.EXE window after the process has been found.
Can I do two different jscript operations in the same batch file, one to check for
the process (wmplayer.exe) and the other to get the cursor back to the DOS window?

I did not find any examples of more than one jscript operation in a batch file.

Code: Select all

@if (@CodeSection == @Batch) @then


@echo off

SETLOCAL EnableExtensions
Set "EXE=wmplayer.exe"
Set "title=This is an unique title"
title %title%

:top
Set "aCount=0"

Set "rsp="
Set "is1or2=FALSE"
Set "mplayerOK=FALSE"

Echo(
Set /P rsp=Choose music file, #1 or #2 [1,2,Quit]

If "%rsp%"=="" GoTo:eof
If "%rsp:~0,1%"=="1" Set "is1or2=TRUE"
If "%rsp:~0,1%"=="2" Set "is1or2=TRUE"

If "%is1or2%"=="TRUE" (Set "musFile=Sample%rsp%.mp3") Else Echo Exiting.& GoTo:eof

If Not EXIST "%musFile%" Echo file not found: %musFile%.  Exiting. & GoTo:eof

start "" "%musFile%"

:check_player
If %aCount% gtr 1 (
   If %aCount% gtr 10 Echo There was a problem running the file %EXE%.&GoTo:eof
   rem tasklist not available in XP. replace the following line with a jscript solution.
   For /F %%x In ('tasklist /NH /FI "IMAGENAME eq %EXE%"') Do If %%x == %EXE% GoTo found
)
Set /A "aCount+=1"
GoTo check_player

:found
Set "mplayerOK=TRUE"
rem Start a process that will bring the focus back to this window
start "" cscript //nologo //E:JScript "%~F0" "%title%"
GoTo top

endlocal

@end


// JScript section

// Set focus on the cmd.exe window
WScript.CreateObject("WScript.Shell").AppActivate(WScript.Arguments(0));



adapt additional jscript code found on SO, slightly modified by me (Set "isRunning..."), to the above batch file:

Code: Select all

cscript //E:JScript //nologo "%~f0" | find /i "%EXE%" >nul 2>&1 && (
    Set "isRunning=TRUE"
) || (
    Set "isRunning=FALSE"
)

exit /b

************** end of JSCRIPT COMMENT **/


var winmgmts = GetObject("winmgmts:\\\\.\\root\\cimv2");
var colProcess = winmgmts.ExecQuery("Select * from Win32_Process");
var processes =  new Enumerator(colProcess);
for (;!processes.atEnd();processes.moveNext()) {
    var process=processes.item();
    WScript.Echo( process.processID + "   " + process.Name );
}                                     

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Make DOS window active after starting a Windows app.

#4 Post by Squashman » 21 Nov 2015 16:59

Jer, you can use cscript JOB option too have more than two.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Make DOS window active after starting a Windows app.

#5 Post by Ed Dyreen » 21 Nov 2015 17:36

I'll give an example of what squash means as I imagine you may have some difficulties finding the relevant info:

Code: Select all

<!-- : Enable embedded WSF comment

:: some batch code here
@echo off &blablabla
...

:: ( disable embedded WSF comment -->
<package>

   <job id="JScript"><script language="JScript">

      if ( WScript.Arguments.length > 0 ) {

         if ( WScript.Arguments(0) == "sleep_" ) {

            var $time;
            //
            if ( WScript.Arguments.length > 1 ) {

               $time = WScript.Arguments(1);

            } else    $time = 1;

            $time = $time +'000';
            //
            WSH.sleep( $time );
         };
      };

   </script></job>

   <job id="VBScript"><script language="VBScript">

      If WScript.Arguments.length > 0 Then
      rem (
         If WScript.Arguments(0) = "asciiMapHex" Then
         rem (
            Call WScript.Stdout.Write( "#" )

            for i=1 to 255
            rem (
               if i <> 10 then
               rem (
                  Call WScript.Stdout.Write( chr(i) + chr(i) + right( "0" + hex( i ), 2 ) + "#" )
               rem )
               end if
            rem )
            next
         rem )
         End If

         If WScript.Arguments(0) = "getCharMap" Then
         rem (
            for i=1 to 255
            rem (
               if i = 10 then
               rem (
                  Call WScript.Stdout.Write( " " )
               rem )
               else
               rem (
                  Call WScript.Stdout.Write( chr(i) )
               rem )
               end if
            rem )
            next
         rem )
         End If
      rem )
      End If

   </script></job>

</package>
<!-- : Enable embedded WSF comment :: )

:: some batch code here
blablabla

:: let's call the jscript here as proof of concept
cScript.EXE //noLogo "!$function.fullPathFile!?.WSF" //job:JScript sleep_ !$time!
...

:: disable embedded WSF comment, must be last line in batch ! -->
replace the !$function.fullPathFile! with something like %~f0 but keep the ?.WSF part especially the question mark, this IS the trick to trick to WSF extension.

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Make DOS window active after starting a Windows app.

#6 Post by Jer » 23 Nov 2015 17:15

I'm at a roadblock. The code below does not leave the DOS window active.
If the VBScript parts are removed and JScript sleep command uncommented,
the DOS window is activated after starting a media player.

My goal is to be able to check if the media player is running, and when it is found
to be running, activate the DOS window with negligible waiting.

Can the two hybrid scripts be used together to minimize the wait time?
Thanks.

Code: Select all

@if (@CodeSection == @Batch) @then

<!-- : Begin batch script

@Echo Off

rem this batch code uses the files sample.mp3 and wmplayer.exe

setlocal

set "title=This is an unique title"
title %title%
pause

Set "musFile=Sample1.mp3"
start "" "%musFile%"
cscript //nologo "%~f0?.wsf" "wmplayer.exe"

rem Start a process that will reselect this window
start "" cscript //nologo //E:JScript "%~F0" "%title%"

endlocal&GoTo :EOF


@end


// JScript section
// WScript.Sleep(1000);

// Set focus on the cmd.exe window
WScript.CreateObject("WScript.Shell").AppActivate(WScript.Arguments(0));
WScript.EXIT


----- Begin wsf script --->
<job><script language="VBScript">

Set args = Wscript.Arguments

Dim objWMIService, objProcess, colProcess
Dim strComputer
Dim numArgs
Dim strMediaPlayer

numArgs = WScript.Arguments.Count

If numArgs = 0 Then WScript.Quit

strMediaPlayer = Args(0)

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate}!\\" _
  & strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _
  ("Select * from Win32_Process")

ret = 0

For count = 0 To 4
   If ret = 1 Then Exit For
   For Each objProcess in colProcess
     If objProcess.Name = strMediaPlayer Then
       ret = 1
       Exit For
     End If
   Next
   If ret = 0 Then WScript.Sleep 250
Next

WScript.Echo "exiting vbscript with return code: " & ret
WScript.QUIT ret

</script></job>


foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Make DOS window active after starting a Windows app.

#7 Post by foxidrive » 23 Nov 2015 19:18

Is it a task you are trying to solve, or a technique to do some other tasks?

This starts an MP3 here and returns to the same window

Code: Select all

@echo Off

rem this batch code uses the files sample.mp3 and wmplayer.exe

findstr "^:" "%~f0" >_.vbs
set "title=This is an unique title"
title %title%
start "" "sample.mp3"
cscript /nologo _.vbs
:set fso=CreateObject("WScript.Shell")
:wscript.sleep 100
:fso.AppActivate("This is an unique title")
del _.vbs
pause

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Make DOS window active after starting a Windows app.

#8 Post by Jer » 23 Nov 2015 20:49

foxidrive, I am looking for a method to save a mouse click each time the media player is started.

The batch program browses pages of music files in a numbered list. Keyboard entry of
a number, numbers, and/or range of numbers is interpreted into a list of individual numbers,
file names for items selected are retrieved from a text file using a 'For' loop and 'skip' to find each
file name based on the line number, then a .m3u playlist with the path and file names is written to play,
and the list starts playing.
That's where I want to get the cursor back in the DOS window.

How can I get your code to not drop off the end.
This is my attempt, which does not work.

Code: Select all

@echo Off

rem this batch code uses the files sample.mp3 and wmplayer.exe

:top
set "rsp="
Echo(
set /p "rsp=Press Enter to start the music or q to quit..."
If /I "%rsp%"=="Q" exit /b

findstr "^:" "%~f0" >_.vbs
set "title=This is an unique title"
title %title%
start "" "sample.mp3"
Call :doScript
GoTo:top

:doScript
cscript /nologo _.vbs
:set fso=CreateObject("WScript.Shell")
:wscript.sleep 100
:fso.AppActivate("This is an unique title")
del _.vbs
:WScript.EXIT

and the error:
C:\Temp\_.vbs(1, 2) Microsoft VBScript runtime error: Type mismatch: 'top'

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Make DOS window active after starting a Windows app.

#9 Post by foxidrive » 24 Nov 2015 07:39

To get it into a prompt, replace the last line of pause with cmd /k

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Make DOS window active after starting a Windows app.

#10 Post by Squashman » 24 Nov 2015 07:41

Jer, look at the last word in the error. Where do you think that is coming from?
Hint. Look at how the VBS is being created.

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Make DOS window active after starting a Windows app.

#11 Post by Jer » 24 Nov 2015 23:44

foxidrive & squashman: my experience level is such that I can't understand where to go with those hints.

All of the help from this thread and other recent posts from Aacini on hybrid scripts has helped me to
get it running with the batch file below. The goal of this project was to have the test-code
do what its supposed to do without error on my Win 7 laptop, Win 7 desktop, and the same
desktop booted in XP: activate the DOS window after starting a media player. I've explained in
a previous post that this method of activating a DOS window will be implemented in a larger batch project.

The code, before the latest revision, ran as expected on the laptop.

I found that when I tested on the desktop PC in Win 7, a blinking icon for the DOS window appeared
on the taskbar about once every 4 iterations. Then I would need to click on the DOS window.
Occasionally the media player kept the focus. I added closing media player before opening it, and
adding a 2nd AppActivate statement in the script, plus the "on error..." statements before and after,
and then the DOS window was activated every time.
In this revision, I have added a second job for the vbScript, closing the media player.

Please add your comments if there are any parts of this code that can be corrected where I will gain
instruction from the corrections.

Code: Select all

<!-- : Begin batch script
@echo off
rem hybrid vbScript code demonstrates opening media player from batch and
rem then activating the DOS cmd window.

rem this batch file uses these 3 files: sample1.mp3, sample2.mp3, wmplayer.exe

Set "mPlayer=wmplayer.exe"

set "title=This is an unique title"
title %title%

:top
Set "rsp="
Set "mFile="
Echo(&Echo Enter 1 or 2 to play music file #1 or #2
Set /p "rsp=or 's' to stop player, or just press Enter to quit. "

If "%rsp%"=="" Exit /b
Set "rsp=%rsp:~0,1%"
If "%rsp%"=="1" Set "mFile=sample1.mp3"
If "%rsp%"=="2" Set "mFile=sample2.mp3"

If /I "%rsp%"=="S" (
   cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 1
) Else If Not "%mFile%"=="" (
    If Not EXIST "%mFile%" (
       Echo %mFile% was not found.
       Echo Copy two mp3 music files to this folder and name them
       Echo sample1.mp3 and sample2.mp3, then run this batch file again.
       exit /b
    ) Else (
        cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 1
        start %mPlayer% /play %~dp0\%mFile%
        cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 0
    )
) Else (
    Echo(&Echo That was not one of the choices.  Try again.&GoTo:top
)

GoTo:top


----- Begin wsf script --->
<job><script language="VBScript">

Set args = Wscript.Arguments

Dim objWMIService, objProcess, colProcess
Dim strComputer
Dim strMediaPlayer
Dim numArgs, found, c

numArgs = args.Count

If numArgs = 0 Then WScript.Quit

strMediaPlayer = Args(0)

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate}!\\" _
  & strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _
  ("Select * from Win32_Process")

found = 0
For c = 1 To 5
   If found > 0 Then Exit For
   For Each objProcess in colProcess
     If objProcess.Name = strMediaPlayer Then
        If args(2) = 1 Then
           On Error Resume Next
           objProcess.Terminate()
           On Error GoTo 0
           found = 2
           WScript.Sleep 100
           Exit For
        Else
           found = 1
           Exit For
        End If
     End If
   Next
   If args(2) <> 1 Then WScript.Sleep 250
Next

If found = 1 Then
   Set WshShell = WScript.CreateObject("WScript.Shell")
   WScript.Sleep 100
   On Error Resume Next
   WshShell.AppActivate (Args(1))
   WshShell.AppActivate (Args(1))
   On Error GoTo 0
End If

</script></job>

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Make DOS window active after starting a Windows app.

#12 Post by foxidrive » 25 Nov 2015 00:50

Jer wrote:The goal of this project was to have the test-code
do what its supposed to do without error on my Win 7 laptop, Win 7 desktop, and the same
desktop booted in XP: activate the DOS window after starting a media player.

Jer, the problem as I see it is that the task wasn't described - and the your first post says just this:

Automatically return to the DOS window after starting a Windows application?

I use the start command in a large batch application I am working on,
and currently have to click back into the DOS window after
Windows Media Player has started.



You only get good programming help when the task is properly laid out for us to see, because any program is based upon the actual task - and isn't written in 'fuzzy logic'.

What is fuzzy logic?

Date: 15-APR-93

Fuzzy logic is a superset of conventional (Boolean) logic that has been
extended to handle the concept of partial truth -- truth values between
"completely true" and "completely false". It was introduced by Dr. Lotfi
Zadeh of UC/Berkeley in the 1960's as a means to model the uncertainty
of natural language.

einstein1969
Expert
Posts: 961
Joined: 15 Jun 2012 13:16
Location: Italy, Rome

Re: Make DOS window active after starting a Windows app.

#13 Post by einstein1969 » 25 Nov 2015 04:09

Jer, the script work very well on windows 7

I have added 2 standard music files for testing.

Code: Select all

<!-- : Begin batch script
@echo off
rem hybrid vbScript code demonstrates opening media player from batch and
rem then activating the DOS cmd window.

rem this batch file uses these 3 files: sample1.mp3, sample2.mp3, wmplayer.exe

Set "mPlayer=wmplayer.exe"

set "title=This is an unique title"
title %title%

:top
Set "rsp="
Set "mFile="
Echo(&Echo Enter 1 or 2 to play music file #1 or #2
Set /p "rsp=or 's' to stop player, or just press Enter to quit. "

If "%rsp%"=="" Exit /b
Set "rsp=%rsp:~0,1%"
If "%rsp%"=="1" Set "mFile=%SystemRoot%\media\onestop.mid"
If "%rsp%"=="2" Set "mFile=%SystemRoot%\media\flourish.mid"

If /I "%rsp%"=="S" (
   cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 1
) Else If Not "%mFile%"=="" (
    If Not EXIST "%mFile%" (
       Echo %mFile% was not found.
       Echo Copy two mp3 music files to this folder and name them
       Echo sample1.mp3 and sample2.mp3, then run this batch file again.
       exit /b
    ) Else (
        cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 1
        rem start %mPlayer% /play %~dp0\%mFile%
        start %mPlayer% /play %mFile%
        cscript //nologo "%~f0?.wsf" "%mPlayer%" "%title%" 0
    )
) Else (
    Echo(&Echo That was not one of the choices.  Try again.&GoTo:top
)

GoTo:top


----- Begin wsf script --->
<job><script language="VBScript">

Set args = Wscript.Arguments

Dim objWMIService, objProcess, colProcess
Dim strComputer
Dim strMediaPlayer
Dim numArgs, found, c

numArgs = args.Count

If numArgs = 0 Then WScript.Quit

strMediaPlayer = Args(0)

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
  & "{impersonationLevel=impersonate}!\\" _
  & strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _
  ("Select * from Win32_Process")

found = 0
For c = 1 To 5
   If found > 0 Then Exit For
   For Each objProcess in colProcess
     If objProcess.Name = strMediaPlayer Then
        If args(2) = 1 Then
           On Error Resume Next
           objProcess.Terminate()
           On Error GoTo 0
           found = 2
           WScript.Sleep 100
           Exit For
        Else
           found = 1
           Exit For
        End If
     End If
   Next
   If args(2) <> 1 Then WScript.Sleep 250
Next

If found = 1 Then
   Set WshShell = WScript.CreateObject("WScript.Shell")
   WScript.Sleep 100
   On Error Resume Next
   WshShell.AppActivate (Args(1))
   WshShell.AppActivate (Args(1))
   On Error GoTo 0
End If

</script></job>


It is possible start the Wmplayer minimized?


einstein1969

Jer
Posts: 177
Joined: 23 Nov 2014 17:13
Location: California USA

Re: Make DOS window active after starting a Windows app.

#14 Post by Jer » 25 Nov 2015 10:31

Thank you for your comments. I will try to make future requests for help fully accurate.

Thanks for testing my batch file. It may not be logical to use AppActivate the way I did,
but neither is is logical for the Windows taskbar blinking icon to interrupt the program flow
telling me I need to click something to continue. This only happened on my desktop
Pentium 4 PC, not the laptop. Windows 7 32bit version is the same on both.

Running media player minimized is not a good option for my application. Each of my
mp3 files, over 1,200, has custom album art, and for me, this enhances the music
listening experience. So, for example, when I am listening to Afternoon of a Faun, the image is
of a fawn (a young deer) in a meadow. Even though Windows Media Player has settings to
disable retrieving and inserting its own images, frequently it cheated and replaced my image.
I then added code to delete, just before starting up the player, any .jpg files that WMP may have created
in my music files folder. After many months, I have not seen a replacement of album art by WMP.
Jerry

Post Reply