display title and pid of current window?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
taripo
Posts: 228
Joined: 01 Aug 2011 13:48

display title and pid of current window?

#1 Post by taripo » 11 Dec 2012 12:00

how can I display the title and pid of the current window?

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

Re: display title and pid of current window?

#2 Post by Ed Dyreen » 11 Dec 2012 12:52

'
You can use a native solution using tasklist or non native using cmdow.EXE.
I do not know of a bulletproof tasklist solution.

ed

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: display title and pid of current window?

#3 Post by aGerman » 11 Dec 2012 15:06

Do you have WMIC on board?

Code: Select all

@echo off &setlocal
title This is a test.

setlocal EnableDelayedExpansion
set "uid="
for /l %%i in (1 1 128) do (set /a "bit=!random!&1" &set "uid=!uid!!bit!")
for /f "tokens=2 delims==" %%i in (
  'WMIC Process WHERE "Name='cmd.exe' AND CommandLine LIKE '%%!uid!%%'" GET ParentProcessID /value'
) do for /f %%j in ("%%i") do (endlocal &set "PID=%%j")
for /f "tokens=1* delims=:" %%i in ('tasklist /fo "LIST" /fi "PID eq %PID%" /v') do (
  for /f "tokens=*" %%k in ("%%j") do set "WindowTitle=%%k"
)


echo PID         = %PID%
echo WindowTitle = "%WindowTitle%"

pause

No, it's not bulletproof. Theoretically you have a one in 340282366920938463463374607431768211456 chance to get the wrong PID if you run this file twice at the same time :wink:

Regards
aGerman

EDIT: We better should use a colon as delimiter to get the title. Otherwise I fear it's not language independent.

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

Re: display title and pid of current window?

#4 Post by Aacini » 11 Dec 2012 20:33

You may use my Window.exe auxiliary program to show the window title (and achieve other window management tasks). I wanted to also return the window pid via errorlevel, but I am surprised that there is no direct nor easy way to get that info via Win-32 API functions! I have not enough time to research on this point (perhaps someone may give me the recipe to get the PID of the parent process...)

Antonio

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

Re: display title and pid of current window?

#5 Post by Ed Dyreen » 11 Dec 2012 20:42

'
Now that Aacini has posted a non-native solution might just aswell :lol:

Code: Select all

for /f "skip=1tokens=3" %%? in ('"!$cmdow.file!" @') do set "_=%%?"
set "_"

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

Re: display title and pid of current window?

#6 Post by Aacini » 11 Dec 2012 21:38

EDIT: Oops! I realized my former method will not work in the instant I posted it. The next one is the good one, but requires my Window.exe program.

I think this tasklist-based solution should work ok:

Code: Select all

@echo off
for /F "delims=" %%a in ('Window') do set title=%%a
rem This file is PID.BAT
set title=%title: - PID=%
set randNum=%random%
title %randNum%
for /F "tokens=2" %%a in ('tasklist /FI "WINDOWTITLE eq %randNum%"') do set PID=%%a
title %title%
echo Title: "%title%"
echo PID:   %PID%


Antonio

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

Re: display title and pid of current window?

#7 Post by einstein1969 » 14 Mar 2014 13:50

Hi,

this use title + tasklist but not change the title. For discovery the title (starting from the PID discovered) look at the aGerman post.

Code: Select all

@echo off & setlocal

set r=%random%_%time:,=%_%random%
for /f "tokens=2 delims=," %%i in ('title %r%^&tasklist /v /fo csv /nh ^|find "%r%"') do echo PID=%%~i


einstein1969

thefeduke
Posts: 211
Joined: 05 Apr 2015 13:06
Location: MA South Shore, USA

Re: display title and pid of current window?

#8 Post by thefeduke » 30 Aug 2016 17:21

I know that this topic lay dormant for a few years , but I had occasion to find this topic while while searching for a way to retrieve the window title to see how it reacts to LOCAL scope. The size of this post is deceptive.
Ed Dyreen wrote:You can use a native solution using tasklist or non native using cmdow.EXE.
I do not know of a bulletproof tasklist solution.ed
One sees a window TITLE when at the DOS Prompt. That is what I wish to retrieve and although it visibly changes while I am running a command that does not specifically change the TITLE. It is also what I expect it to be after the command returns to Prompt. The obstacle to getting this simple string is the format in which TASKLIST presents the "Window Title" value. All of the contributed methods successfully retrieve this value in the same format. Even if disguised by cmdow.exe or window.exe they all seem to rely on the TASK manager for this data.

Code: Select all

Output from cmdow.exe using findEDtitle.bat:
Handle  Lev Pid -Window status- Image    Caption
0x4D06DE 1 1084 Res Act Ena Vis cmd      Command Prompt - findEDtitle

Title from TASKLIST findtitle.bat:      'Command Prompt - findtitle'

Actual Title of window:                 "Command Prompt"
Only Antonio's contribution made an attempt to remove the command portion from the TITLE string.

Ed's code was only seeking the PID, but cmdow used like

Code: Select all

:: formatted for full title
%$cmdow.file% @ /b
for /f "tokens=8*" %%a in ('cmdow @ /b') do set "_=%%b"
set "_"
call TrimTitle EDtitle "%_%"
Echo/Title: '%EDtitle%'
sets the variable "_" to the same result as the others and introduces my attempt to reduce the TASKLIST output to the TITLE string:

Code: Select all

:TrimTitle TITLEvariableName[out] RawTITLEValue[In]
@echo Off & SetLocal EnableDelayedExpansion
::  Post subject: Re: display title and pid of current window?
::  http://www.dostips.com/forum/viewtopic.php?p=22671#p22671
::  Posted: Mon Aug 30, 2016 by thefeduke
    Set "WindowTitle=%~2"
    Set "WindowTitle=%WindowTitle:"=""%"
    Rem.Removing up to and including " - " from the TASKLIST Window Title.
    Set "CommandName= %WindowTitle:* - =%"
    For /L %%a In (1,1,9) Do (
        Set "ChopTitle=!CommandName:* - =!"
        Rem.Cycling to find last " - " to isolate the command portion.
        If " !ChopTitle!" NEQ "!CommandName!" Set "CommandName=!ChopTitle!"
    )
    Set "WindowTitle=!WindowTitle: - %ChopTitle%=!
    Rem.One of these trims should work depending on the Space/Dash continuum.
    Set "WindowTitle=!WindowTitle: -%ChopTitle%=!
    Set "WindowTitle=%WindowTitle:""="%"
(EndLocal & Rem.Save "%~1" value.
    If "%~1" NEQ "" (SET "%~1=%WindowTitle%") ELSE Set "Title=%WindowTitle%")
Exit /B
This seems to handle spaces and blanks in the title which is so necessary because Windows adds strings like '- Shortcut' in normal operation. It does fail miserably if the name of the calling script contains ' - ' in its name.

If only the TITLE is need, the interpreted output of cmdow seemed the cleanest method to me, but, naturally, I persevered to make it more difficult.

John A.

END of Meaningful Contibution WARNING! - only intrepid viewers need follow after this point.

So it struck me that some methods to get the PID without using 'window' or 'cmdow' obscured the TITLE so as to render the PID useless to find the TITLE. I then decided to save a cleaned-up snapshot of the TASKLIST output before that happened, so that it could be used later. This yielded my stubborn learning exercise and demo. TASKLIST does yield interesting output.

Code: Select all

:FindTitle TITLEvariableName[out][Opt] PIDvariableName[Out][Opt]
@echo Off & setlocal EnableDelayedExpansion
:: Post subject: Re: display title and pid of current window?
::http://www.dostips.com/forum/viewtopic.php?p=22671#p22671
::Posted: Mon Aug 30, 2016 by thefeduke

Call :WindowLists

Call :WindowPid mypid

Call :WindowTitle MyWindowTitle "%MyPid%"

Echo/
Echo/Current Window PID and TITLE:
Echo/ PID : %myPid%
Echo/Title from TASKLIST: '%MyWindowTitle%'
Echo/
rem.For the preplanned TASKLIST output adjustment to work,
rem.if this file is FindTitle.bat it has to be called with the command: findtitle
rem.It is not case-sensitive and can also be called with: call Findtitle
set title=%MyWindowTitle: - findtitle=%
rem.TASKLIST adds an extra space between call and the command.
set title=%title: - call  findtitle=%
::Posted: Tue Dec 11, 2012 10:38 pm by Aacini
Echo.Adjusted Title^(using a preplanned naming method^): '%Title%'
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Done preplanned method

Call :TrimTitle MyWindowTitle "%MyWindowTitle%"

Echo.Adjusted Title ^(using a more generalized method^): '%MyWindowTitle%'
Echo/
(EndLocal & Rem.Save values if requested.
    If "%~1" NEQ "" SET "%~1=%MyWindowTitle%"
    If "%~2" NEQ "" SET "%~2=%MyPid%"
)
pause
Goto :EOF

:WindowLists [No Arguments] produces temporary output files
rem.Save a PID/TITLE list because a following temporary TITLE change
rem.prevents real TITLE access for duration of the script.
    @echo Off & SetLocal EnableDelayedExpansion
    >"%Temp%\%~n0_Windows.txt" Echo.
    >"%Temp%\%~n0_RawWindows.txt" Echo.

    For /F "delims=" %%i IN (
        'TASKLIST /FI "imagename eq cmd.exe" /v /fo list ^| FindStr "PID: Title"'
    ) do (
        Set "WinPID=%%i"
        If /I "!WinPID:~0,4!" EQU "PID:" Set "lastPid=!WinPID:~14!"
        If /I "!WinPID:~0,13!" EQU "Window Title:" (
            Set "Pid=!lastPid: =!"
            IF /I "!WinPID:~14,3!" NEQ "N/A" (
                >>"%Temp%\%~n0_Windows.txt" Echo.!Pid! !WinPID:~14!
            )
            >>"%Temp%\%~n0_RawWindows.txt" Echo.Pid: !Pid! %%i
        )
    )
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :WindowLists
Exit /B

:WindowPid PIDVariableName[In,Out]
@echo Off & SetLocal
::  Credit to Post: Tue Dec 11, 2012 4:06 pm by aGerman
rem.for /l %%i in (1 1 128) do (set /a "bit=!random!&1" &set "QuiteUnique=!QuiteUnique!!bit!")
    set "QuiteUnique=Quite%random%Unique"
::  Credit to Post: Fri Mar 14, 2014 3:50 pm by einstein1969
::  Credit to Post: Tue Dec 11, 2012 10:38 pm by Aacini
    for /f "tokens=2 delims=," %%i in (
        'title %QuiteUnique%^&tasklist /v /fo csv /nh ^|find "%QuiteUnique%"'
    ) do Set PID=%%~i
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :WindowPid Setting PId=%PID%
(EndLocal & Rem.Save "%~1" value.
    If "%~1" NEQ "" (SET "%~1=%Pid%") ELSE Echo/PID not determined.)
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :WindowPID after EndLocal
Exit /B

:WindowTitle TITLEVariableName[In,Out] PIDValue[In]
    @echo Off & SetLocal
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Entering :WindowTitle Seeing PId=%~2 to Set %~1
    For /F "usebackq tokens=1* delims= " %%i IN (`Type "%Temp%\%~n0_Windows.txt"`
    ) do If /I "%%i" EQU "%~2" Set "WindowTitle=%%j"
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :WindowTitle Setting %~1 to %WindowTitle%
(EndLocal & Rem."%~2" Was only an input value
    If "%~1" NEQ "" (SET "%~1=%WindowTitle%") ELSE Set "WinTitle=%WindowTitle%")
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :WindowTitle after EndLocal
Exit /B

:TrimTitle TITLEvariableName[out] RawTITLEValue[In]
@echo Off & SetLocal EnableDelayedExpansion
::  Post subject: Re: display title and pid of current window?
::  http://www.dostips.com/forum/viewtopic.php?p=22671#p22671
::  Posted: Mon Aug 29, 2016 by thefeduke
    Set "WindowTitle=%~2"
    Set "WindowTitle=%WindowTitle:"=""%"
    Rem.Removing up to and including " - " from the TASKLIST Window Title.
    Set "CommandName= %WindowTitle:* - =%"
    For /L %%a In (1,1,4) Do (
        Set "ChopTitle=!CommandName:* - =!"
        Rem.Cycling to find last " - " to isolate the command portion.
        If " !ChopTitle!" NEQ "!CommandName!" Set "CommandName=!ChopTitle!"
    )
    Set "WindowTitle=!WindowTitle: - %ChopTitle%=!
    Rem.One of these trims should work depending on the Space/Dash continuum.
    Set "WindowTitle=!WindowTitle: -%ChopTitle%=!
    Set "WindowTitle=%WindowTitle:""="%"
(EndLocal & Rem.Save "%~1" value.
    If "%~1" NEQ "" (SET "%~1=%WindowTitle%") ELSE Set "Title=%WindowTitle%")
    >>"%Temp%\%~n0_RawWindows.txt" Echo.Exiting :TrimTitle
Exit /B
There is a log, of sorts, in a temporary file.

douglas.swehla
Posts: 75
Joined: 01 Jun 2016 09:25

Re: display title and pid of current window?

#9 Post by douglas.swehla » 31 Aug 2016 10:28

thefeduke wrote:I know that this topic lay dormant for a few years


Rob Van Der Woude issued a challenge some years ago (http://www.robvanderwoude.com/gettitle.php), asking people to write a pure batch script that would get the title of the currently running window. I'm not sure how long ago, since the page isn't dated, but it treats Windows 7 as the latest version.

www.RobVanDerWoude.com wrote:
  • must still function if multiple console windows are open
  • if possible, must even function correctly if multiple instances of the batch file are running
  • must take into account (and strip) the Administrator: prefix added in UAC enabled Windows versions

. . .

All "contestants" seem to agree on the use of TASKLIST to retrieve the window title.

Correctly running multiple instances of the batch files was the hardest requirement to meet.


The linked page describes the testing regime applied to each script, and provides a table of which scripts succeeded at which portions of the task, and links to each script's full content. One pure batch solution met all the requirements (http://www.robvanderwoude.com/files/gettitle_brianwilliams4.txt). One hybrid solution that worked "flawlessly" used VBScript to generate an executable, and Rob wrote his own in C# before issuing the challenge. I don't know if the VB solution used TASKLIST or not. The winning script got around the problem of "not really %RANDOM%" by checking for duplicate temp files and creating a new temp file if any were found.

While not strictly part of the challenge, most of the scripts, including the winner, seem to rely on PID to find the window title, so displaying that should be pretty easy to derive.

I haven't taken the time to compare and contrast the contest entries with any of the solutions here, including yours, so I can't say which are superior, or duplicates. I also don't know whether any of the submissions took into account language differences, or at least used approaches that would handle them, intended or not. I think it's worth noting that this seems to be a problem that other talented people have struggled with, and that it's worth looking at their work, if only for educational purposes.

If any of the solutions here meet or beat the challenge requirements, or if we can supplement the winner with language independence, I think it's worth contacting Rob and asking him to post an update. His site is one the handful that I consider authoritative, and is a repository of useful and advanced techniques. It would be nice if we, he, and maybe SS64.com were all in sync on this.

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

Re: display title and pid of current window?

#10 Post by foxidrive » 04 Sep 2016 02:02

That's an interesting conundrum and comments that both of you write.

I have a viewpoint that is not quite as legitimate with batch files and it's because I spent so much time scripting in the MSDOS days that I view it this way.

For those without much contact with MSDOS scripting: back then the command set was far more limited and kludges with recursive scripts and file I/O in temporary files was necessary for almost everything. Qbasic was a valuable tool for a huge number of tasks as it was both reliable and quick, compared to batch scripting with a large amount of temporary file writing/reading on very slow hard drive media.

Qbasic was a standard tool in everybody's arsenal who wrote batch filesat that time, and writing batch files was the domain of the seriously geeky. Few places existed where batch scripting was discussed. Fidonet had an echo called "Batpower" on bulletin board system computers, using the Fidonet worldwide discussion forums via POTS dialup modems and not on the Internet.

So the way I view this task is that writing a tool in c# and compiling it on the fly by adding an embedded script is not cheating in any way, shape, or form, and is actually a reliable and simple way to solve the task.

Scripting back then was hideously complicated to even get the date and time in variables. Scripts often had far larger amounts of code compared with what would be necessary for the same task today.

So yeah. I always enjoyed making scripts bend to my will in vanilla batch and it was such an enjoyable pastime. I'm far older these days and not as supple or as nimble in my mind so the aspects that I view today as valuable are:

1) simpler code that you can re-read 12 or 24 months later and decipher easily
2) tools that are robust.

With point number 2: we've all battled trying to make code robust in any situation and there is a good measure of enjoyment in that kind of task.

Over time, and doing that with many scripts it has become clear that it's just not possible or feasible in many situations and it leads to code that doesn't comply with my point number 1. :)

That's why I lean to solutions with a HLL (and using Qbasic gave me that view in MSDOS) or some utility which is robust or faster and requires far less code (helping to meet the requirements of point 1).

Just waffling on here. I must eat too many waffles. ;)

Post Reply