May 282007
 
LinkedInDiggGoogle GmailGoogle BookmarksEmailShare Please

How to find out the type of an executable file, i.e. whether it’s a windows application or a console application or an MS-DOS application…

void GetFileType( LPCTSTR lpctszFilePath_i, CString& csFileType_o )
{
    // Get exe file type
    const DWORD dwRetVal = SHGetFileInfo( lpctszFilePath_i,
                                          FILE_ATTRIBUTE_NORMAL,
                                          0,
                                          0,
                                          SHGFI_EXETYPE );
    if( dwRetVal )
    {
        /*
           READ THIS!! dwRetVal is interpreted as follows...

           LOWORD = NE or PE and HIWORD = 3.0, 3.5, or 4.0  Windows application
           LOWORD = MZ and HIWORD = 0  MS-DOS .exe, .com, or .bat file
           LOWORD = PE and HIWORD = 0  Win32 console application
        */

        const WORD wLowWord =  LOWORD( dwRetVal );
        const WORD wHiWord = HIWORD( dwRetVal );
        const WORD wPEWord = MAKEWORD( 'P', 'E' );
        const WORD wMZWord = MAKEWORD( 'M', 'Z' );
        const WORD wNEWord = MAKEWORD( 'N', 'E' );

        // Read above comments to understand what's happening
        if( wLowWord == wPEWord || wLowWord == wNEWord )
        {
            if( wHiWord == 0 )
            {
                csFileType_o = _T( "Win32 Console Application" );
            }
            else
            {
                csFileType_o = _T( "Windows application" );
            }
        }
        else if( wLowWord == wMZWord && wHiWord == 0 )
        {
            csFileType_o = _T( "MS-DOS .exe, .com or .bat file" );
        }
        else
        {
            csFileType_o = _T( "Unknown file type" );
        }// End if
    }// End if
}// End GetFileType