MFC OnFileNew OnFileOpen过程分析代码(以记录MFC学习点滴)

       对OnFileNew()/OnFileOpen()的MFC代码跟踪简析,简析可能也谈不上了,为了快速的理解MFC的实现思路以及文档视图架构的应用,在学习的过程当中我也没有进行学习理解的注解。不过细细阅读整个的实现流程,相信你我都能理解掌握MFC的整体思路。以后有机会再进行注解吧。

A) OnFileNew()执行过程分析

1.     void CWinApp::OnFileNew()

{

       if (m_pDocManager != NULL)

              m_pDocManager->OnFileNew();

}

注释:MFCID_FILE_NEW菜单的响应函数,系统默认操作.

2.     void CDocManager::OnFileNew()

{

       if (m_templateList.IsEmpty())

       {

              TRACE0("Error: no document templates registered with CWinApp./n");

              AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);

              return;

       }

 

       CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetHead();

       if (m_templateList.GetCount() > 1)

       {

              // more than one document template to choose from

              // bring up dialog prompting user

              CNewTypeDlg dlg(&m_templateList);

              int nID = dlg.DoModal();

              if (nID == IDOK)

                     pTemplate = dlg.m_pSelectedTemplate;

              else

                     return;     // none - cancel operation

       }

 

       ASSERT(pTemplate != NULL);

       ASSERT_KINDOF(CDocTemplate, pTemplate);

 

       pTemplate->OpenDocumentFile(NULL);

              // if returns NULL, the user has already been alerted

}

:如果跳过此函数而手动操作直接进入pTemplate->OpenDocumentFile(),那么文档模版列表选择对话框也就不会出现了.

3.     CDocument* CMultiDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,BOOL bMakeVisible)

{

       CDocument* pDocument = CreateNewDocument();

       if (pDocument == NULL)

       {

              TRACE0("CDocTemplate::CreateNewDocument returned NULL./n");

              AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);

              return NULL;

       }

       ASSERT_VALID(pDocument);

 

       BOOL bAutoDelete = pDocument->m_bAutoDelete;

       pDocument->m_bAutoDelete = FALSE;   // don't destroy if something goes wrong

       CFrameWnd* pFrame = CreateNewFrame(pDocument, NULL);

       pDocument->m_bAutoDelete = bAutoDelete;

       if (pFrame == NULL)

       {

              AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);

              delete pDocument;       // explicit delete on error

              return NULL;

       }

       ASSERT_VALID(pFrame);

 

       if (lpszPathName == NULL)

       {

              // create a new document - with default document name

              SetDefaultTitle(pDocument);

 

              // avoid creating temporary compound file when starting up invisible

              if (!bMakeVisible)

                     pDocument->m_bEmbedded = TRUE;

 

              if (!pDocument->OnNewDocument())

              {

                     // user has be alerted to what failed in OnNewDocument

                     TRACE0("CDocument::OnNewDocument returned FALSE./n");

                     pFrame->DestroyWindow();

                     return NULL;

              }

 

              // it worked, now bump untitled count

              m_nUntitledCount++;

       }

       else

       {

              // open an existing document

              CWaitCursor wait;

              if (!pDocument->OnOpenDocument(lpszPathName))

              {

                     // user has be alerted to what failed in OnOpenDocument

                     TRACE0("CDocument::OnOpenDocument returned FALSE./n");

                     pFrame->DestroyWindow();

                     return NULL;

              }

              pDocument->SetPathName(lpszPathName);

       }

 

       InitialUpdateFrame(pFrame, pDocument, bMakeVisible);

       return pDocument;

}

 

4.     CDocument* CDocTemplate::CreateNewDocument()

{

       // default implementation constructs one from CRuntimeClass

       if (m_pDocClass == NULL)

       {

              TRACE0("Error: you must override CDocTemplate::CreateNewDocument./n");

              ASSERT(FALSE);

              return NULL;

       }

       CDocument* pDocument = (CDocument*)m_pDocClass->CreateObject();

       if (pDocument == NULL)

       {

              TRACE1("Warning: Dynamic create of document type %hs failed./n",

                     m_pDocClass->m_lpszClassName);

              return NULL;

       }

       ASSERT_KINDOF(CDocument, pDocument);

       AddDocument(pDocument);

       return pDocument;

}

 

5.     CFrameWnd* CDocTemplate::CreateNewFrame(CDocument* pDoc, CFrameWnd* pOther)

{

       if (pDoc != NULL)

              ASSERT_VALID(pDoc);

       // create a frame wired to the specified document

 

       ASSERT(m_nIDResource != 0); // must have a resource ID to load from

       CCreateContext context;

       context.m_pCurrentFrame = pOther;

       context.m_pCurrentDoc = pDoc;

       context.m_pNewViewClass = m_pViewClass;

       context.m_pNewDocTemplate = this;

 

       if (m_pFrameClass == NULL)

       {

              TRACE0("Error: you must override CDocTemplate::CreateNewFrame./n");

              ASSERT(FALSE);

              return NULL;

       }

       CFrameWnd* pFrame = (CFrameWnd*)m_pFrameClass->CreateObject();

       if (pFrame == NULL)

       {

              TRACE1("Warning: Dynamic create of frame %hs failed./n",

                     m_pFrameClass->m_lpszClassName);

              return NULL;

       }

       ASSERT_KINDOF(CFrameWnd, pFrame);

 

       if (context.m_pNewViewClass == NULL)

              TRACE0("Warning: creating frame with no default view./n");

 

       // create new from resource

       if (!pFrame->LoadFrame(m_nIDResource,

                     WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE,   // default frame styles

                     NULL, &context))

       {

              TRACE0("Warning: CDocTemplate couldn't create a frame./n");

              // frame will be deleted in PostNcDestroy cleanup

              return NULL;

       }

 

       // it worked !

       return pFrame;

}

 

6.     BOOL CDocument::OnNewDocument()

{

       if (IsModified())

              TRACE0("Warning: OnNewDocument replaces an unsaved document./n");

 

       DeleteContents();

       m_strPathName.Empty();      // no path name yet

       SetModifiedFlag(FALSE);     // make clean

 

       return TRUE;

}

 

7.     BOOL CDocument::OnOpenDocument(LPCTSTR lpszPathName)

{

       if (IsModified())

              TRACE0("Warning: OnOpenDocument replaces an unsaved document./n");

 

       CFileException fe;

       CFile* pFile = GetFile(lpszPathName,

              CFile::modeRead|CFile::shareDenyWrite, &fe);

       if (pFile == NULL)

       {

              ReportSaveLoadException(lpszPathName, &fe,

                     FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);

              return FALSE;

       }

 

       DeleteContents();

       SetModifiedFlag();  // dirty during de-serialize

 

       CArchive loadArchive(pFile, CArchive::load | CArchive::bNoFlushOnDelete);

       loadArchive.m_pDocument = this;

       loadArchive.m_bForceFlat = FALSE;

       TRY

       {

              CWaitCursor wait;

              if (pFile->GetLength() != 0)

                     Serialize(loadArchive);     // load me

              loadArchive.Close();

              ReleaseFile(pFile, FALSE);

       }

       CATCH_ALL(e)

       {

              ReleaseFile(pFile, TRUE);

              DeleteContents();   // remove failed contents

 

              TRY

              {

                     ReportSaveLoadException(lpszPathName, e,

                            FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);

              }

              END_TRY

              DELETE_EXCEPTION(e);

              return FALSE;

       }

       END_CATCH_ALL

 

       SetModifiedFlag(FALSE);     // start off with unmodified

 

       return TRUE;

}

 

8.     BOOL CFrameWnd::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle,  CWnd* pParentWnd, CCreateContext* pContext)

{

       // only do this once

       ASSERT_VALID_IDR(nIDResource);

       ASSERT(m_nIDHelp == 0 || m_nIDHelp == nIDResource);

 

       m_nIDHelp = nIDResource;    // ID for help context (+HID_BASE_RESOURCE)

 

       CString strFullString;

       if (strFullString.LoadString(nIDResource))

              AfxExtractSubString(m_strTitle, strFullString, 0);    // first sub-string

 

       VERIFY(AfxDeferRegisterClass(AFX_WNDFRAMEORVIEW_REG));

 

       // attempt to create the window

       LPCTSTR lpszClass = GetIconWndClass(dwDefaultStyle, nIDResource);

       LPCTSTR lpszTitle = m_strTitle;

       if (!Create(lpszClass, lpszTitle, dwDefaultStyle, rectDefault,

         pParentWnd, MAKEINTRESOURCE(nIDResource), 0L, pContext))

       {

              return FALSE;   // will self destruct on failure normally

       }

 

       // save the default menu handle

       ASSERT(m_hWnd != NULL);

       m_hMenuDefault = ::GetMenu(m_hWnd);

 

       // load accelerator resource

       LoadAccelTable(MAKEINTRESOURCE(nIDResource));

 

       if (pContext == NULL)   // send initial update

              SendMessageToDescendants(WM_INITIALUPDATE, 0, 0, TRUE, TRUE);

 

       return TRUE;

}

 

9.     void DocTemplate::InitialUpdateFrame(CFrameWnd* pFrame, CDocument* pDoc,BOOL bMakeVisible)

{

       // just delagate to implementation in CFrameWnd

       pFrame->InitialUpdateFrame(pDoc, bMakeVisible);

}

 

10.     void CFrameWnd::InitialUpdateFrame(CDocument* pDoc, BOOL bMakeVisible)

{

       // if the frame does not have an active view, set to first pane

       CView* pView = NULL;

       if (GetActiveView() == NULL)

       {

              CWnd* pWnd = GetDescendantWindow(AFX_IDW_PANE_FIRST, TRUE);

              if (pWnd != NULL && pWnd->IsKindOf(RUNTIME_CLASS(CView)))

              {

                     pView = (CView*)pWnd;

                     SetActiveView(pView, FALSE);

              }

       }

 

       if (bMakeVisible)

       {

              // send initial update to all views (and other controls) in the frame

              SendMessageToDescendants(WM_INITIALUPDATE, 0, 0, TRUE, TRUE);

 

              // give view a chance to save the focus (CFormView needs this)

              if (pView != NULL)

                     pView->OnActivateFrame(WA_INACTIVE, this);

 

              // finally, activate the frame

              // (send the default show command unless the main desktop window)

              int nCmdShow = -1;      // default

              CWinApp* pApp = AfxGetApp();

              if (pApp != NULL && pApp->m_pMainWnd == this)

              {

                     nCmdShow = pApp->m_nCmdShow; // use the parameter from WinMain

                     pApp->m_nCmdShow = -1; // set to default after first time

              }

              ActivateFrame(nCmdShow);

              if (pView != NULL)

                     pView->OnActivateView(TRUE, pView, pView);

       }

 

       // update frame counts and frame title (may already have been visible)

       if (pDoc != NULL)

              pDoc->UpdateFrameCounts();

       OnUpdateFrameTitle(TRUE);

}

B) OnFileOpen()执行过程分析

11.             void CWinApp::OnFileOpen()

{

       ASSERT(m_pDocManager != NULL);

       m_pDocManager->OnFileOpen();

}

 

12.             void CDocManager::OnFileOpen()

{

       // prompt the user (with all document templates)

       CString newName;

       if (!DoPromptFileName(newName, AFX_IDS_OPENFILE,

         OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, NULL))

              return; // open cancelled

 

       AfxGetApp()->OpenDocumentFile(newName);

              // if returns NULL, the user has already been alerted

}

 

13.             CDocument* CWinApp::OpenDocumentFile(LPCTSTR lpszFileName)

{

       ASSERT(m_pDocManager != NULL);

       return m_pDocManager->OpenDocumentFile(lpszFileName);

}

 

14.             CDocument* CDocManager::OpenDocumentFile(LPCTSTR lpszFileName)

{

       // find the highest confidence

       POSITION pos = m_templateList.GetHeadPosition();

       CDocTemplate::Confidence bestMatch = CDocTemplate::noAttempt;

       CDocTemplate* pBestTemplate = NULL;

       CDocument* pOpenDocument = NULL;

 

       TCHAR szPath[_MAX_PATH];

       ASSERT(lstrlen(lpszFileName) < _countof(szPath));

       TCHAR szTemp[_MAX_PATH];

       if (lpszFileName[0] == '/"')

              ++lpszFileName;

       lstrcpyn(szTemp, lpszFileName, _MAX_PATH);

       LPTSTR lpszLast = _tcsrchr(szTemp, '/"');

       if (lpszLast != NULL)

              *lpszLast = 0;

       AfxFullPath(szPath, szTemp);

       TCHAR szLinkName[_MAX_PATH];

       if (AfxResolveShortcut(AfxGetMainWnd(), szPath, szLinkName, _MAX_PATH))

              lstrcpy(szPath, szLinkName);

 

       while (pos != NULL)

       {

              CDocTemplate* pTemplate = (CDocTemplate*)m_templateList.GetNext(pos);

              ASSERT_KINDOF(CDocTemplate, pTemplate);

 

              CDocTemplate::Confidence match;

              ASSERT(pOpenDocument == NULL);

              match = pTemplate->MatchDocType(szPath, pOpenDocument);

              if (match > bestMatch)

              {

                     bestMatch = match;

                     pBestTemplate = pTemplate;

              }

              if (match == CDocTemplate::yesAlreadyOpen)

                     break;      // stop here

       }

 

       if (pOpenDocument != NULL)

       {

              POSITION pos = pOpenDocument->GetFirstViewPosition();

              if (pos != NULL)

              {

                     CView* pView = pOpenDocument->GetNextView(pos); // get first one

                     ASSERT_VALID(pView);

                     CFrameWnd* pFrame = pView->GetParentFrame();

                     if (pFrame != NULL)

                            pFrame->ActivateFrame();

                     else

                            TRACE0("Error: Can not find a frame for document to activate./n");

                     CFrameWnd* pAppFrame;

                     if (pFrame != (pAppFrame = (CFrameWnd*)AfxGetApp()->m_pMainWnd))

                     {

                            ASSERT_KINDOF(CFrameWnd, pAppFrame);

                            pAppFrame->ActivateFrame();

                     }

              }

              else

              {

                     TRACE0("Error: Can not find a view for document to activate./n");

              }

              return pOpenDocument;

       }

 

       if (pBestTemplate == NULL)

       {

              AfxMessageBox(AFX_IDP_FAILED_TO_OPEN_DOC);

              return NULL;

       }

 

       return pBestTemplate->OpenDocumentFile(szPath);

}

 

15.             CDocument* CMultiDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,BOOL bMakeVisible)

{

       CDocument* pDocument = CreateNewDocument();

       if (pDocument == NULL)

       {

              TRACE0("CDocTemplate::CreateNewDocument returned NULL./n");

              AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);

              return NULL;

       }

       ASSERT_VALID(pDocument);

 

       BOOL bAutoDelete = pDocument->m_bAutoDelete;

       pDocument->m_bAutoDelete = FALSE;   // don't destroy if something goes wrong

       CFrameWnd* pFrame = CreateNewFrame(pDocument, NULL);

       pDocument->m_bAutoDelete = bAutoDelete;

       if (pFrame == NULL)

       {

              AfxMessageBox(AFX_IDP_FAILED_TO_CREATE_DOC);

              delete pDocument;       // explicit delete on error

              return NULL;

       }

       ASSERT_VALID(pFrame);

 

       if (lpszPathName == NULL)

       {

              // create a new document - with default document name

              SetDefaultTitle(pDocument);

 

              // avoid creating temporary compound file when starting up invisible

              if (!bMakeVisible)

                     pDocument->m_bEmbedded = TRUE;

 

              if (!pDocument->OnNewDocument())

              {

                     // user has be alerted to what failed in OnNewDocument

                     TRACE0("CDocument::OnNewDocument returned FALSE./n");

                     pFrame->DestroyWindow();

                     return NULL;

              }

 

              // it worked, now bump untitled count

              m_nUntitledCount++;

       }

       else

       {

              // open an existing document

              CWaitCursor wait;

              if (!pDocument->OnOpenDocument(lpszPathName))

              {

                     // user has be alerted to what failed in OnOpenDocument

                     TRACE0("CDocument::OnOpenDocument returned FALSE./n");

                     pFrame->DestroyWindow();

                     return NULL;

              }

              pDocument->SetPathName(lpszPathName);

       }

 

       InitialUpdateFrame(pFrame, pDocument, bMakeVisible);

       return pDocument;

}

 

16.             CDocument* CDocTemplate::CreateNewDocument()

{

       // default implementation constructs one from CRuntimeClass

       if (m_pDocClass == NULL)

       {

              TRACE0("Error: you must override CDocTemplate::CreateNewDocument./n");

              ASSERT(FALSE);

              return NULL;

       }

       CDocument* pDocument = (CDocument*)m_pDocClass->CreateObject();

       if (pDocument == NULL)

       {

              TRACE1("Warning: Dynamic create of document type %hs failed./n",

                     m_pDocClass->m_lpszClassName);

              return NULL;

       }

       ASSERT_KINDOF(CDocument, pDocument);

       AddDocument(pDocument);

       return pDocument;

}

 

17.             CFrameWnd* CDocTemplate::CreateNewFrame(CDocument* pDoc, CFrameWnd* pOther)

{

       if (pDoc != NULL)

              ASSERT_VALID(pDoc);

       // create a frame wired to the specified document

 

       ASSERT(m_nIDResource != 0); // must have a resource ID to load from

       CCreateContext context;

       context.m_pCurrentFrame = pOther;

       context.m_pCurrentDoc = pDoc;

       context.m_pNewViewClass = m_pViewClass;

       context.m_pNewDocTemplate = this;

 

       if (m_pFrameClass == NULL)

       {

              TRACE0("Error: you must override CDocTemplate::CreateNewFrame./n");

              ASSERT(FALSE);

              return NULL;

       }

       CFrameWnd* pFrame = (CFrameWnd*)m_pFrameClass->CreateObject();

       if (pFrame == NULL)

       {

              TRACE1("Warning: Dynamic create of frame %hs failed./n",

                     m_pFrameClass->m_lpszClassName);

              return NULL;

       }

       ASSERT_KINDOF(CFrameWnd, pFrame);

 

       if (context.m_pNewViewClass == NULL)

              TRACE0("Warning: creating frame with no default view./n");

 

       // create new from resource

       if (!pFrame->LoadFrame(m_nIDResource,

                     WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE,   // default frame styles

                     NULL, &context))

       {

              TRACE0("Warning: CDocTemplate couldn't create a frame./n");

              // frame will be deleted in PostNcDestroy cleanup

              return NULL;

       }

 

       // it worked !

       return pFrame;

}

 

18.             BOOL CDocument::OnNewDocument()

{

       if (IsModified())

              TRACE0("Warning: OnNewDocument replaces an unsaved document./n");

 

       DeleteContents();

       m_strPathName.Empty();      // no path name yet

       SetModifiedFlag(FALSE);     // make clean

 

       return TRUE;

}

 

19.             BOOL CDocument::OnOpenDocument(LPCTSTR lpszPathName)

{

       if (IsModified())

              TRACE0("Warning: OnOpenDocument replaces an unsaved document./n");

 

       CFileException fe;

       CFile* pFile = GetFile(lpszPathName,

              CFile::modeRead|CFile::shareDenyWrite, &fe);

       if (pFile == NULL)

       {

              ReportSaveLoadException(lpszPathName, &fe,

                     FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);

              return FALSE;

       }

 

       DeleteContents();

       SetModifiedFlag();  // dirty during de-serialize

 

       CArchive loadArchive(pFile, CArchive::load | CArchive::bNoFlushOnDelete);

       loadArchive.m_pDocument = this;

       loadArchive.m_bForceFlat = FALSE;

       TRY

       {

              CWaitCursor wait;

              if (pFile->GetLength() != 0)

                     Serialize(loadArchive);     // load me

              loadArchive.Close();

              ReleaseFile(pFile, FALSE);

       }

       CATCH_ALL(e)

       {

              ReleaseFile(pFile, TRUE);

              DeleteContents();   // remove failed contents

 

              TRY

              {

                     ReportSaveLoadException(lpszPathName, e,

                            FALSE, AFX_IDP_FAILED_TO_OPEN_DOC);

              }

              END_TRY

              DELETE_EXCEPTION(e);

              return FALSE;

       }

       END_CATCH_ALL

 

       SetModifiedFlag(FALSE);     // start off with unmodified

 

       return TRUE;

}

 

20.             void DocTemplate::InitialUpdateFrame(CFrameWnd* pFrame, CDocument* pDoc,BOOL bMakeVisible)

{

       // just delagate to implementation in CFrameWnd

       pFrame->InitialUpdateFrame(pDoc, bMakeVisible);

}

 

21.     void CFrameWnd::InitialUpdateFrame(CDocument* pDoc, BOOL bMakeVisible)

{

       // if the frame does not have an active view, set to first pane

       CView* pView = NULL;

       if (GetActiveView() == NULL)

       {

              CWnd* pWnd = GetDescendantWindow(AFX_IDW_PANE_FIRST, TRUE);

              if (pWnd != NULL && pWnd->IsKindOf(RUNTIME_CLASS(CView)))

              {

                     pView = (CView*)pWnd;

                     SetActiveView(pView, FALSE);

              }

       }

 

       if (bMakeVisible)

       {

              // send initial update to all views (and other controls) in the frame

              SendMessageToDescendants(WM_INITIALUPDATE, 0, 0, TRUE, TRUE);

 

              // give view a chance to save the focus (CFormView needs this)

              if (pView != NULL)

                     pView->OnActivateFrame(WA_INACTIVE, this);

 

              // finally, activate the frame

              // (send the default show command unless the main desktop window)

              int nCmdShow = -1;      // default

              CWinApp* pApp = AfxGetApp();

              if (pApp != NULL && pApp->m_pMainWnd == this)

              {

                     nCmdShow = pApp->m_nCmdShow; // use the parameter from WinMain

                     pApp->m_nCmdShow = -1; // set to default after first time

              }

              ActivateFrame(nCmdShow);

              if (pView != NULL)

                     pView->OnActivateView(TRUE, pView, pView);

       }

 

       // update frame counts and frame title (may already have been visible)

       if (pDoc != NULL)

              pDoc->UpdateFrameCounts();

       OnUpdateFrameTitle(TRUE);

}

 

 
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
// FiveChess.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "FiveChess.h" #include "MainFrm.h" #include "FiveChessDoc.h" #include "FiveChessView.h" #include "afxsock.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //////////////////////////////////////////////////////////////////////////// // CFiveChessApp BEGIN_MESSAGE_MAP(CFiveChessApp, CWinApp) //{{AFX_MSG_MAP(CFiveChessApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFiveChessApp construction CFiveChessApp::CFiveChessApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CFiveChessApp object CFiveChessApp theApp; ///////////////////////////////////////////////////////////////////////////// // CFiveChessApp initialization BOOL CFiveChessApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CFiveChessDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CFiveChessView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CFiveChessApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CFiveChessApp message handlers
Visual Studio 2019 (VS2019) 是一款非常强大的集成开发环境,其中包含了支持多种开发技术的工具,包括 MFC (Microsoft Foundation Class) 库。在 VS2019 中使用 MFC 连接 SQL 数据库非常便捷。 首先,我们需要创建一个 MFC 应用程序项目。打开 VS2019,选择“文件”菜单,点击“新建”>“项目”。在“创建新项目”对话框中,选择“Visual C++”>“MFC”,然后选择“MFC 应用程序”模板。在下一步中,为项目命名,选择存放项目的位置并点击“确定”按钮。 接下来,我们需要添加一个数据库连接。在“资源视图”中,右键点击“资源文件”文件夹,选择“添加”>“添加类”。然后在弹出的对话框中选择“数据”>“ODBC 数据源类”,点击“添加”按钮。在下一步中,选择我们要连接的数据库类型(如 SQL Server)和数据源的名称,然后点击“完成”按钮。 现在,我们可以在代码中使用 MFC 提供的类和方法连接数据库和执行 SQL 语句。在项目的 MainFrame.cpp 文件中,找到 `BEGIN_MESSAGE_MAP` 宏,下方会有一个叫 OnFileNew 的函数,我们可以在此函数中添加我们的数据库连接代码。 首先,创建一个 CDatabase 对象,然后调用 `OpenEx` 函数来打开数据库连接。在这个函数的参数中,我们需要指定数据库的名称、登录名和密码等信息。如果连接成功,可以通过调用 `IsOpen` 函数来判断连接是否成功。 接下来,我们可以使用 `ExecuteSQL` 函数来执行 SQL 语句。该函数的参数是一个字符串,我们可以在其中编写我们的 SQL 语句。执行完 SQL 语句后,可以调用 `Close` 函数来关闭数据库连接。 以上就是使用 MFC 连接 SQL 数据库的主要步骤。通过使用 VS2019 提供的 MFC 库,我们可以轻松地编写连接 SQL 数据库的应用程序,并执行各种数据库操作。在实际开发中,我们可以根据具体的需求,进一步加强对数据库的操作和管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值