This function is called by the MFC-supplied WinMain function, as part of the CWinApp initialization of a GUI-based application, to initialize MFC.


      BOOL AFXAPI AfxWinInit(
   HINSTANCE hInstance,
   HINSTANCE hPrevInstance,
   LPTSTR lpCmdLine,
   int nCmdShow 


  • hInstance
    The handle of the currently running module.

  • hPrevInstance
    A handle to a previous instance of the application. For a Win32-based application, this parameter is always NULL.

  • lpCmdLine
    Points to a null-terminated string specifying the command line for the application.

  • nCmdShow
    Specifies how the main window of a GUI application would be shown.


For a console application, which does not use the MFC-supplied WinMain function, you must call AfxWinInit directly to initialize MFC.

If you call AfxWinInit yourself, you should declare an instance of a CWinApp class. For a console application, you might choose not to derive your own class from CWinApp and instead use an instance of CWinApp directly. This technique is appropriate if you decide to leave all functionality for your application in your implementation of main.


When it creates an activation context for an assembly, MFC uses a manifest resource provided by the user module. The activation context is created in AfxWinInit. For more information, see Support for Activation Contexts in the MFC Module State.


#include <afx.h>
#include <afxdb.h>

int _tmain(int /*argc*/, TCHAR* /*argv[]*/, TCHAR* /*envp[]*/)
   int nRetCode = 0;

   // initialize MFC and print and error on failure
   if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
      // TODO: change error code to suit your needs
      _tprintf(_T("Fatal Error: MFC initialization failed\n"));
      nRetCode = 1;
      // try to connect to an ODBC database that doesn't exist
      // (this wouldn't work at all without initializing MFC)

      CDatabase db;
         db.Open(_T("This Databsae Doesn't Exist"));

         // we shouldn't realistically get here

            _T("Closing ...\n"));
      catch (CDBException* pEx)
         // we got an exception! print an error message
         // (this wouldn't work without initializing MFC)

         TCHAR sz[1024];

         _tprintf_s(_T("Error: "));
         if (pEx->GetErrorMessage(sz, 1024))
            _tprintf_s(_T("No error message was available"));


         nRetCode = 1;

   return nRetCode;


Header: afxwin.h

See Also

MFC Macros and Globals
CWinApp Class
CWinApp: The Application Class
main: Program Startup