I want to create a doskey command that closes the current CMD console window, without affecting any other open CMD console windows.
It has to work even when cmd.exe has been run (manually or by batch file) within that window. Ordinarily I would just use the exit command, but this does not close the window if other instances of cmd.exe have been run within that window.
I therefore decided to create a 'close' command that would always close the current window regardless of what had been run inside it. I chose the PID method of window detection (to avoid issues of windows with identical titles) and then used taskkill with /F and /T switches to kill the process. It worked fine, but it had the same problem as using the standard 'exit' command.
I ran tasklist and realised that the PID of the current CMD window changes whenever cmd.exe is run within it (you can see the multiple instances of cmd.exe listed, even though no new window has been opened) so using cmd.exe PID is not a usable method. However, each window does have its own conhost.exe process associated with it (regardless of the number of cmd instances) so killing the comhost process seems to be the best way to achieve what I want.
I tried it manually and it works exactly as I wanted.
- Open one cmd console window, then run cmd.exe a couple of times within that window.
- Open a second cmd console window, run cmd.exe a few times in that second window.
- Use tasklist to find the PID of the conhost process for the window you want to close.
- Manually run: taskkill /PID <PID of conhost process> /F to kill the selected conhost.
The above immediately closes the specified console window (and all of its related cmd.exe instances) while leaving the other console window alone.
I therefore just need to replicate the above process in a batch file so that I can use my doskey command to call that instead of my existing cmd PID checking code.
This is this code that I am using for current cmd PID detection (which I found online). I don't understand it (I'm a code newbie) but it works perfectly.
I then looked for method to determine the conhost PID based on the exiting cmd.exe PID of the current window, but I couldn't find anything except for this, which did not work (and which also caused various other problems with unrelated existing commands in my batch file).
Maybe there is an much simpler way of achieving my goal, but if killing conhost is the way to go then it seems to me that a modified version of the code below (to make it find the current conhost PID instead of the current cmd PID) would be the answer, because works reliably in a batch file very few lines of code.
set T=%TEMP%\sthUnique.tmp
wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") get ParentProcessId /value | find "ParentProcessId" >%T%
set /P A=<%T%
set PID=%A:~16%