Determining the type of running application (.NET)

How to determine if a Windows Forms application or a console application is running?

+3
source share
4 answers

p / call:

[DllImport("shell32.dll")]
private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

Struct:

[StructLayout(LayoutKind.Sequential)]
private 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;
}

Method:

private static bool IsWindowsApplication(string fileName)
{
    SHFILEINFO psfi = new SHFILEINFO();
    switch (((int) SHGetFileInfo(fileName, 0, ref psfi, (uint) Marshal.SizeOf(psfi), 0x2000)))
    {
        case 0:
            return false;

        case 0x4550:
            return false;

        case 0x5a4d:
            return false;
    }
    return true;
}

If the above method returns false, this is a console application.

-Oisin

+4
source

You cannot do it reliably. For example, start a new project from the Windows Forms application project template. Project + Properties, change the output type to "Console Application". Press F5 to see how it looks. Although every reasonable test will say that this application is in console mode, it is very similar to a WF application.

, System.Windows.Forms.dll WF-. MessageBox, .

, . .

, , . , .

+5

, ProcessExplorer , System.Winforms.dll . , , .

0

, , System.Windows.Forms.Application.OpenForms .

Another option would be to check whether Console.Titleor not an Console.WindowTopexception was selected (if no console window were open).

EDIT

However, note that the application can have a console window and open the form at the same time ... What application is it then?

0
source

Source: https://habr.com/ru/post/1726743/


All Articles