Determine if an executable is a Console Application in C#

Thanks to Scott's comment I went on the hunt to figure out how to tell if an executable is a console application or not. After much hunting I figured out how to do it, here is what I came up with. Enjoy!

public const int SHGFI_EXETYPE = 0x000002000;
public const int IMAGE_NT_SIGNATURE = 0x00004550;

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHGetFileInfo(string pszPath, int dwFileAttributes, out SHFILEINFO psfi, int cbFileInfo, int uFlags);

public static bool IsConsoleApplication(string path)
{
    SHFILEINFO fi;
    int exeType = SHGetFileInfo(path, 0out fi, 0, SHGFI_EXETYPE);
    return (LoWord(exeType) == IMAGE_NT_SIGNATURE && HiWord(exeType) == 0); 
}
public static int LoWord(int dwValue)
{
    return dwValue & 0xFFFF;
}
public static int HiWord(int dwValue)
{
    return (dwValue >> 16) & 0xFFFF;
}

1 Comment

  • The SHFILEINFO struct was missing:


    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
    public IntPtr hIcon;
    public IntPtr iIcon;
    public uint dwAttributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
    };

Comments have been disabled for this content.