Page 1 of 1

Detect type of exe (console vs windowed)

Posted: Thu Apr 18, 2013 6:33 pm
by jassing
I have a program that provides some user feedback; then launches an external application -- this application can be a console or windowed program.
Is there a way to detect if an exe is a console application (in which case, I want to wait for it to complete) or a windowed program?

ie: if I pass 'notepad.exe' to it - I want to detect that it is a windowed program, or if I run 'ipconfig.exe' I need to know it's a console app.

Re: Detect type of exe (console vs windowed)

Posted: Fri Apr 19, 2013 3:48 am
by Danilo
jassing wrote:I have a program that provides some user feedback; then launches an external application -- this application can be a console or windowed program.
Is there a way to detect if an exe is a console application (in which case, I want to wait for it to complete) or a windowed program?

ie: if I pass 'notepad.exe' to it - I want to detect that it is a windowed program, or if I run 'ipconfig.exe' I need to know it's a console app.
Console/Window type switch is only 1 word within the EXE header:

Code: Select all

EnableExplicit

#IMAGE_SUBSYSTEM_WINDOWS_GUI        = 2  ; Image runs in the Windows GUI subsystem.
#IMAGE_SUBSYSTEM_WINDOWS_CUI        = 3  ; Image runs in the Windows character subsystem.

Procedure GetEXESubsystem(filename$)
    Protected result = 0
    Protected filesize = FileSize(filename$)
    Protected file, ntheader
    
    If filesize
        file = ReadFile(#PB_Any,filename$);,#PB_File_SharedRead) ; #PB_File_SharedRead required?
        If file
            If filesize > SizeOf(IMAGE_DOS_HEADER)
                FileSeek(file,OffsetOf(IMAGE_DOS_HEADER\e_lfanew),#PB_Absolute)
                ntheader = ReadLong(file)
                If filesize > ntheader + SizeOf(IMAGE_NT_HEADERS) + SizeOf(IMAGE_OPTIONAL_HEADER)
                    FileSeek(file,ntheader + OffsetOf(IMAGE_NT_HEADERS\OptionalHeader)+OffsetOf(IMAGE_OPTIONAL_HEADER\Subsystem),#PB_Absolute)
                    result = ReadWord(file)
                EndIf
            EndIf
            CloseFile(file)
        EndIf
    EndIf
    
    ProcedureReturn result
EndProcedure

Debug GetEXESubsystem( ProgramFilename() )

Debug GetEXESubsystem( #PB_Compiler_Home + "PureBasic.exe" )
Debug GetEXESubsystem( #PB_Compiler_Home + "Compilers\pbcompiler.exe" )

Debug GetEXESubsystem( "c:\windows\notepad.exe" )
Debug GetEXESubsystem( "c:\windows\system32\ipconfig.exe" )

Re: Detect type of exe (console vs windowed)

Posted: Fri Apr 19, 2013 3:36 pm
by jassing
Slick! Thank you.

Re: Detect type of exe (console vs windowed)

Posted: Thu Apr 25, 2013 3:07 pm
by Kwai chang caine
Thanks DANILO good tips 8)