How can I determine if the running application is a Windows Forms or a Console application?
If it doesn't need to be done programmatically you could maybe use a program like ProcessExplorer and see if the System.Winforms.dll is loaded. I don't think this is foolproof but it may be a start.
One option might be to check if System.Windows.Forms.Application.OpenForms
contains any elements.
Another option might be to check whether Console.Title
or Console.WindowTop
throws an exception (it would if no console window is open).
EDIT
However, note that an application may have a console window and a form open at the same time... What kind of application is it then?
p/invoke:
[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, it's a console application.
-Oisin
You can't do this reliably. For example, start a new project from the Windows Forms Application project template. Project + Properties, change Output Type to "Console Application". Press F5 to see what that looks like. While every reasonable test will say it is a console mode application, it is very much a WF app.
The opposite is true as well, merely the presence of System.Windows.Forms.dll doesn't make it a WF app. A console app might use it to display a MessageBox for example.
Furthermore, it could be neither. Your code might be called by a service.
Punt this problem, the author of the app never has a problem telling you what your code should do. Add a property to your class to allow her to do so. Or use events. Or use dependency injection.