The comments in the code list the applications I've already tested.
Code: Select all
@echo off &setlocal
:: Returns 0 if %isterminal% is executed in a terminal emulator.
:: - Windows Terminal
:: - ConEmu
:: - Alacritty
:: - Cmder
:: - Terminus
:: - Hyper
:: Returns 1 if executed in a console.
:: - Windows Console Host (usual console window)
:: - Console2
:: - ConsoleZ
set isterminal=powershell.exe -nop -ep Bypass -c ^"$c=Add-Type -Name pInv -PassThru -MemberDefinition '^
%=% [DllImport(\"user32.dll\")] public static extern IntPtr SendMessageW(IntPtr hWnd,int Msg,IntPtr wParam,IntPtr lParam);^
%=% [DllImport(\"kernel32.dll\")] public static extern IntPtr GetConsoleWindow(); ';^
%=% exit [int]($c::SendMessageW($c::GetConsoleWindow(),($WM_GETICON=0x7F),[IntPtr]::Zero,[IntPtr]::Zero) -ne [IntPtr]::Zero);^"
%isterminal% && (
echo is a terminal
) || (
echo is a console
)
pause
I'm not sure how useful this actually is. Probably not of much interest for scripts but rather for apps that use the console API which might behave differently in a terminal. However, based on the current reactions found in this issue ...
https://github.com/microsoft/terminal/issues/7434
... I don't believe Microsoft is willing to implement an API for this purpose. So, for those of you who need the C equivalent of the code above, here you go
Code: Select all
#include <windows.h>
int main(void)
{
return 0 != SendMessageW(GetConsoleWindow(), WM_GETICON, 0, 0);
}
Steffen
// EDIT
Based on the comments of Eureka! I tried to combine his command lines for an alternative using WMIC:
// EDIT 2
Nope. The default Windows Terminal on Win 11 runs in a completely different process structure where the below doesn't work any longer.
( If you need to get the terminal attached to your shell process, see: viewtopic.php?f=3&t=10576 )
Code: Select all
@echo off &setlocal
for /f "tokens=2 delims==" %%i in (
'wmic process WHERE ^"CommandLine LIKE '%comspec:\=\\% /c wmic process WHERE \^"CommandLine LIKE%%'^" get ParentProcessId /value'
) do for /f %%j in ("%%i") do 2>nul wmic process WHERE "ParentProcessId=%%j" get Caption|>nul findstr /i "conhost.exe" && (
echo Console
) || (
echo No Console
)
pause