Page 1 of 1

How to know whether my console program was launched from Explorer or from a command prompt?

Posted: Wed Jan 14, 2026 4:21 pm
by Axolotl
And once again, I asked myself a question? See subject.
Apologies in advance if this has already been addressed somewhere else.... (I didn't search for it...)

Here is a (small piece of software) for anyone who can use it.

Code: Select all

; How to know whether my console program was launched from Explorer or from a command prompt?
; Win Only 
; Executable Format: Console 
; No license. No warranties. Use at your own risk. 
; Written by Axolotl 
EnableExplicit 

ImportC ""  ; Kernel32 
  GetConsoleWindow() ;' 
  GetConsoleProcessList(lpdwProcessList, dwProcessCount.l) ; dw = .l 
; GetConsoleOriginalTitle(lpConsoleTitle, nSize.l)  ;' Linker Error ?? 
EndImport 

; ; QuickHelp  FormatMessage(ErrorCode, AppendErrorCode) - return "System Error String" 
; ProcedureDLL.s FormatMessage(ErrorCode, AppendErrorCode) 
;   Protected result$, *msg, msglen 
; 
;   msglen = FormatMessage_(#FORMAT_MESSAGE_ALLOCATE_BUFFER|#FORMAT_MESSAGE_FROM_SYSTEM|#FORMAT_MESSAGE_IGNORE_INSERTS, 0, ErrorCode, 0, @*msg, 0, 0)
;   If msglen 
;     result$ = PeekS(*msg, msglen-2)   ; remove #CRLF$, acc. to MSDN 
;     LocalFree_(*msg)  ; important, free the allocated memory 
; 
;     If AppendErrorCode = #True   ; append the number of the error 
;       result$ + Chr(160) + " 0x" + RSet(Hex(ErrorCode), 8, "0") + " (" + Str(ErrorCode) + ")" ; <= first Char is NBSP$  
;     EndIf 
;   EndIf 
;   ProcedureReturn result$ 
; EndProcedure 

Procedure IsStartedFromConsole()  ; BOOL 
  Protected count, Dim plist.l(4)  ; <==> 2 would be enough to figure this out as well 

  ;// MSDN: 
  ;//   If the function succeeds, the return value is less than or equal to dwProcessCount 
  ;//   and represents the number of process identifiers stored in the lpdwProcessList buffer. 
  ;
  count = GetConsoleProcessList(@plist(), 4) 
  Debug #PB_Compiler_Procedure + "()  Process Count = " + count 
  If count = 0     : Debug #PB_Compiler_Procedure + "()  Error: " ; + FormatMessage(GetLastError_(), #True) 
  ElseIf count = 1 : ProcedureReturn #False   ; <== single process -> started by Explorer, IDE, etc. 
  Else             : ProcedureReturn #True    ; <== count > 1 == more than one process -> started inside a console 
  EndIf 
  ProcedureReturn #False ; default 
EndProcedure 

If OpenConsole("Test App") 
  PrintN("") 
  PrintN("How did I get started?") 
  PrintN("") 

  If IsStartedFromConsole()  
    PrintN("started from the console")
    PrintN("") 
  Else 
    PrintN("started from the Explorer") 
    PrintN("") 
    PrintN("Waiting for RETURN before quit...")
    Input() 
  EndIf 
  CloseConsole() 
EndIf 

Re: How to know whether my console program was launched from Explorer or from a command prompt?

Posted: Thu Jan 15, 2026 10:46 am
by BarryG
Nice. See also: viewtopic.php?t=37743