How can I determine the subsystem used by a given .NET assembly?

前端 未结 4 499
野趣味
野趣味 2020-12-06 19:22

In a C# application, I\'d like to determine whether another .NET application is a Console application or not.

Can this be done using the reflection APIs?

EDI

相关标签:
4条回答
  • 2020-12-06 19:59

    The SHGetFileInfo function can do this:

    [DllImport("shell32.dll", CharSet=CharSet.Auto, EntryPoint="SHGetFileInfo")]
    public static extern ExeType GetExeType(string pszPath, uint dwFileAttributes = 0, IntPtr psfi = default(IntPtr), uint cbFileInfo = 0, uint uFlags = 0x2000);
    
    [Flags]
    public enum ExeType
    {
        None = 0,
        WinNT = 0x04000000,
        PE = ((int)'P') | ((int)'E' << 8),
        NE = ((int)'N') | ((int)'E' << 8),
        MZ = ((int)'M') | ((int)'Z' << 8),
    }
    

    Then, according to the specification, if it's only MZ or PE, it is opened in console, otherwise (if a version is specified), it is open in a window.

    ExeType type = GetExeType("program.exe");
    if(type == ExeType.PE || type == ExeType.MZ) return "console";
    else return "window";
    
    0 讨论(0)
  • 2020-12-06 20:07

    I suppose it should the same as for native apps so then you might be able to adapt this article from C++ to C# to read the PE headers: How To Determine Whether an Application is Console or GUI

    0 讨论(0)
  • 2020-12-06 20:08

    This is out of the scope of managed code. From the .NET perspective, Console and Windows UI applications are the same. You have to peek into the PE file header. Search for the word, "Subsystem" on this page http://msdn.microsoft.com/en-us/magazine/bb985997.aspx

    0 讨论(0)
  • 2020-12-06 20:18

    I don't think there's a scientific way to determine it, the closest workaround that comes to my mind is using reflection to check if the application references and loads the WinForms assembly, but I'm not entirely sure. Might give it a try.

    0 讨论(0)
提交回复
热议问题