p align="left"> // 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(4); // 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 CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_EditAppTYPE, RUNTIME_CLASS(CEditAppDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CEditAppView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // call DragAcceptFiles only if there's a suffix // In an MDI app, this should occur immediately after setting m_pMainWnd // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // App command to run the dialog void CEditAppApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // CEditAppApp message handlers Первая карта сообщений (конструкция BEGIN_MESSAGE_MAP END_MESSAGE_MAP) принадлежит классу СEditApp. Вней сообщения с индетификатором ID_APP_ABOUT, ID_FILE_NEW, ID_FILE_OPEN, ID_FILE_PRINT_SETUP связываются соответственно с обработчиками OnAppAbout(), CWinApp::OnFileNew(), CWinApp::OnFileOpen(), CWinApp::OnFilePrintSetup(). В этом файле реализуется конструктор класса СEditApp, а также его методы OnAppAbout() и InitInstance(). Файл MainFrm.cpp. Этот файл содержит реализацию класса CMainFrame, которой порождается от класса CFrameWnd и управляет всеми дочерними MDI-окнами. #include "stdafx.h" #include "EditApp.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } // TODO: Delete these three lines if you don't want the toolbar to be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return TRUE; } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers В массиве indicators перечислены идентификаторы полей строки состояния, которые служат индикаторами нажатия некоторых клавиш. Добавление в окно приложения панели инструментов и строки состояния производится выделенным полужирным шрифтом. Функции-члены AssertValid() и Dump() используют объявления содержащиеся родительском классе. Класс CMainFrame изначально не имеет обработчиков сообщений. Файл EditAppDoc.cpp. Этот файл содержит реализацию класса CEditAppDoc, Который управляет работой с конкретными документами, а также обеспечивает загрузку и сохранение файлов. #include "stdafx.h" #include "EditApp.h" #include "EditAppDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CEditAppDoc IMPLEMENT_DYNCREATE(CEditAppDoc, CDocument) BEGIN_MESSAGE_MAP(CEditAppDoc, CDocument) END_MESSAGE_MAP() // CEditAppDoc construction/destruction CEditAppDoc::CEditAppDoc() { // TODO: add one-time construction code here } CEditAppDoc::~CEditAppDoc() { } BOOL CEditAppDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } // CEditAppDoc serialization void CEditAppDoc::Serialize(CArchive& ar) { // CEditView contains an edit control which handles all serialization reinterpret_cast<CEditView*>(m_viewList.GetHead())->SerializeRaw(ar); } // CEditAppDoc diagnostics #ifdef _DEBUG void CEditAppDoc::AssertValid() const { CDocument::AssertValid(); } void CEditAppDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CEditAppDoc commands Некоторые методы класса CEditAppDoc могут применяться для поддержки самых необходимых операций работы с документами. В функции OnNewDocument() используются эта же функция из родительского класса <CEditView*>(m_viewList.GetHead())->SerializeRaw(ar); Эта строка кода поддерживает работу команд меню File, обеспечивающих создание, открытие и сохранение файлов. Функции-члены AssertValid() и Dump() используют описание, предлагаемое родительским классом. Файл CEditAppView.cpp. Этот файл содержит реализацию класса CEditAppView, который порождается от класса CEditView и управляет отображением документа. #include "stdafx.h" #include "EditApp.h" #include "SeekDialog.h" #include "EditAppDoc.h" #include "EditAppView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CEditAppView IMPLEMENT_DYNCREATE(CEditAppView, CEditView) BEGIN_MESSAGE_MAP(CEditAppView, CEditView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CEditView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CEditView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CEditView::OnFilePrintPreview) ON_COMMAND(ID_SEEK, &CEditAppView::OnSeek) END_MESSAGE_MAP() // CEditAppView construction/destruction CEditAppView::CEditAppView() { // TODO: add construction code here } CEditAppView::~CEditAppView() { } BOOL CEditAppView::PreCreateWindow(CREATESTRUCT& cs) WS_HSCROLL); // Enable word-wrapping return bPreCreated; // CEditAppView printing BOOL CEditAppView::OnPreparePrinting(CPrintInfo* pInfo) { // default CEditView preparation return CEditView::OnPreparePrinting(pInfo); } void CEditAppView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { // Default CEditView begin printing CEditView::OnBeginPrinting(pDC, pInfo); } void CEditAppView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo) { // Default CEditView end printing CEditView::OnEndPrinting(pDC, pInfo); } // CEditAppView diagnostics #ifdef _DEBUG void CEditAppView::AssertValid() const { CEditView::AssertValid(); } void CEditAppView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } CEditAppDoc* CEditAppView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CEditAppDoc))); return (CEditAppDoc*)m_pDocument; } #endif //_DEBUG // CEditAppView message handlers void CEditAppView::OnSeek() { // TODO: Add your command handler code here CSeekDialog dlg(this); if( dlg.DoModal() == IDOK){ FindText( dlg.m_Sample); } } Класс CEditAppView управляет печатью документов с помощью функций OnPreparePrinting(), OnBeginPrinting(),OnEndPrinting(). Выделенный полужирным шрифтом тектс отвечает за поиск слов в тексте.
Страницы: 1, 2
|