Во второй, главной части статьи, мы закончим наш браузер. Нам нужен сейчас еще один метод OnNewURLEnter( void) . Он, собственно говоря и делает этот переход на новый веб адрес: void CMainFrame::OnNewURLEnter ( void) { CString str;
m_adressbar.GetEditCtrl( ) ->GetWindowText ( str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
COMBOBOXEXITEM item;
item.mask = CBEIF_TEXT; item.iItem = -1 ; item.pszText = ( LPTSTR) ( LPCTSTR) str; m_adressbar.InsertItem( &item) ; }
На конец, нам нужно отредактировать вручную MESSAGE_MAP( ) все того же класса «CMainFrame» таким обарзом: BEGIN_MESSAGE_MAP( CMainFrame, CFrameWnd) ON_WM_CREATE( ) ON_COMMAND( IDOK, OnNewURLEnter) //Эту стоку мы вставляем вручную END_MESSAGE_MAP( ) Компилируем и смотрим. Вводим какой-нибудь адрес и видим, что новую страницу. Работает, и это хорошо. 7 . Если приглядеться, то каждый уважающий себя браузер отображает заголовок загруженной им веб страницы. Наш этого почему-то не делает. Надо исправить это поскорее. В класс “CmybrowserDoc” добавляем переменную типа строка - CString url. Затем переходим в класс «CmybrowserView» и находим в панели «Properties»/«Overrides”. Там выбираем метод «OnDocumentComplete( ) » и кликаем на нем мышью. Затем переходим в сам метод и редактируем его: void CmybrowserView::OnDocumentComplete ( LPCTSTR lpszURL) {
CString title=" Web Browser" ; ( ( CMainFrame*) GetParentFrame( ) ) ->m_adressbar .SetWindowText( lpszURL) ;
AfxGetMainWnd( ) ->SetWindowText ( GetLocationName( ) + title) ;
( GetDocument( ) ) ->url =lpszURL;
CHtmlView::OnDocumentComplete ( lpszURL) ;
}
8 . Теперь идем в редактор ресурсов и выбираем «Menu», там находим пункт «Open…» . Там добавляем обработчик событий, установив его к классу «CmybrowserView». Далее переходим в саму функцию и редактируем следующим обрзаом: void CmybrowserView::OnFileOpen ( ) { static TCHAR BASED_CODE filter[ ] = _T( "HTML Files(*.htm)|*.htm|HTML Files(*.html)|*.html|All Files(*.*)|*.*||" ) ; CFileDialog dlg( TRUE ,_T( "html" ) ,NULL ,OFN_EXPLORER,filter,this) ; dlg.m_ofn.lpstrTitle=_T( "Open HTML file..." ) ; if ( dlg.DoModal( ) !=IDOK) { return ; } CString url( _T( "file://" ) ) ; url+=dlg.GetPathName( ) ; Navigate2( url,NULL ,NULL ) ; }
Пробуем. Мы можем открыть HTML страницу для просмотра..На этом все. Запускаем программу и видим результат. Браузер очень простой, но вполне рабочий. Далее собственно исходный код программы. // MainFrm.cpp : implementation of the CMainFrame class //
#include "stdafx.h" #include "mybrowser.h" #include "mainfrm.h" #include "afxinet.h" #include "mybrowserDoc.h" #include "mybrowserView.h" #include ".\mainfrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame
IMPLEMENT_DYNCREATE( CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP( CMainFrame, CFrameWnd) ON_WM_CREATE( ) ON_COMMAND( IDOK, OnNewURLEnter) 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) {
SetIcon( LoadIcon( AfxGetInstanceHandle( ) ,( LPCTSTR) IDI_ICON1) ,false ) ; CImageList img; //CString str; if ( CFrameWnd::OnCreate ( lpCreateStruct) == -1 ) return -1 ;
m_rebar.Create( this) ; m_toolbar.CreateEx( this) ; m_adressbar.Create( CBS_DROPDOWN | WS_CHILD, CRect( 0 , 0 , 200 , 120 ) , this, 101 ) ;
m_toolbar.GetToolBarCtrl( ) .SetButtonWidth( 50 , 150 ) ; m_toolbar.GetToolBarCtrl( ) .SetExtendedStyle( TBSTYLE_EX_DRAWDDARROWS) ;
img.Create( IDB_HOT, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetHotImageList( &img) ; img.Detach( ) ;
img.Create( IDB_COLD, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetImageList( &img) ; img.Detach( ) ;
m_toolbar.ModifyStyle( 0 , TBSTYLE_FLAT | TBSTYLE_TRANSPARENT) ; m_toolbar.SetButtons( NULL , 6 ) ; m_toolbar.SetButtonInfo( 0 , ID_BACK, TBSTYLE_BUTTON, 0 ) ; m_toolbar.SetButtonText( 0 , "Back" ) ;
m_toolbar.SetButtonInfo( 1 , ID_FORWARD, TBSTYLE_BUTTON, 1 ) ; m_toolbar.SetButtonText( 1 , "Forward" ) ;
m_toolbar.SetButtonInfo( 2 , ID_STOP, TBSTYLE_BUTTON, 2 ) ; m_toolbar.SetButtonText( 2 , "Stop" ) ;
m_toolbar.SetButtonInfo( 3 , ID_REFRESH, TBSTYLE_BUTTON, 3 ) ; m_toolbar.SetButtonText( 3 , "Refresh" ) ;
m_toolbar.SetButtonInfo( 4 , ID_HOME, TBSTYLE_BUTTON, 4 ) ; m_toolbar.SetButtonText( 4 , "Home" ) ;
m_toolbar.SetButtonInfo( 5 , ID_SEARCH, TBSTYLE_BUTTON, 5 ) ; m_toolbar.SetButtonText( 5 , "Search" ) ;
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
CRect toolrect;
// set up toolbar button sizes m_toolbar.GetItemRect( 0 , &toolrect) ; m_toolbar.SetSizes( toolrect.Size( ) , CSize( 30 ,20 ) ) ; m_rebar.AddBar( &m_toolbar) ;
m_rebar.AddBar( &m_adressbar, "address:" , NULL , RBBS_FIXEDBMP | RBBS_BREAK) ; return 0 ; }
BOOL CMainFrame::PreCreateWindow ( CREATESTRUCT& cs) { if ( !CFrameWnd::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 { CFrameWnd::AssertValid ( ) ; }
void CMainFrame::Dump ( CDumpContext& dc) const { CFrameWnd::Dump ( dc) ; }
#endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnNewURL ( void) { CString str; m_adressbar.GetLBText( m_adressbar.GetCurSel( ) , str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
}
void CMainFrame::OnNewURLEnter ( void) { CString str; m_adressbar.GetEditCtrl( ) ->GetWindowText ( str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
COMBOBOXEXITEM item;
item.mask = CBEIF_TEXT; item.iItem = -1 ; item.pszText = ( LPTSTR) ( LPCTSTR) str; m_adressbar.InsertItem( &item) ; } // mybrowser.cpp : Defines the class behaviors for the application. //
#include "stdafx.h" #include "mybrowser.h" #include "MainFrm.h"
#include "mybrowserDoc.h" #include "mybrowserView.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserApp
BEGIN_MESSAGE_MAP( CmybrowserApp, CWinApp) ON_COMMAND( ID_APP_ABOUT, OnAppAbout) // 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( ) // CmybrowserApp construction
CmybrowserApp::CmybrowserApp ( ) { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CmybrowserApp object
CmybrowserApp theApp; // This identifier was generated to be statistically unique for your app // You may change it if you prefer to choose a specific identifier
// {81412519-BCE7-4887-98F7-F034BC210111} static const CLSID clsid ={ 0x81412519, 0xBCE7, 0x4887, { 0x98, 0xF7, 0xF0, 0x34, 0xBC, 0x21, 0x1, 0x11 } } ;const GUID CDECL BASED_CODE _tlid = { 0xAE9746B8, 0x474, 0x4194, { 0xA1, 0xD5, 0x98, 0x38, 0x60, 0x1D, 0x1D, 0xE6 } } ; const WORD _wVerMajor = 1 ; const WORD _wVerMinor = 0 ; // CmybrowserApp initialization
BOOL CmybrowserApp::InitInstance ( ) { // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls( ) ;
CWinApp::InitInstance ( ) ;
if ( !AfxSocketInit( ) ) { AfxMessageBox( IDP_SOCKETS_INIT_FAILED) ; return FALSE ; }
// Initialize OLE libraries if ( !AfxOleInit( ) ) { AfxMessageBox( IDP_OLE_INIT_FAILED) ; return FALSE ; } 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 // 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( 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 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS( CmybrowserDoc) , RUNTIME_CLASS( CMainFrame) , // main SDI frame window RUNTIME_CLASS( CmybrowserView) ) ; if ( !pDocTemplate) return FALSE ; AddDocTemplate( pDocTemplate) ; // Connect the COleTemplateServer to the document template // The COleTemplateServer creates new documents on behalf // of requesting OLE containers by using information // specified in the document template m_server.ConnectTemplate( clsid, pDocTemplate, TRUE ) ; // Note: SDI applications register server objects only if /Embedding // or /Automation is present on the command line // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine( cmdInfo) ; // App was launched with /Embedding or /Automation switch. // Run app as automation server. if ( cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated) { // Register all OLE server factories as running. This enables the // OLE libraries to create objects from other applications COleTemplateServer::RegisterAll ( ) ;
// Don't show the main window return TRUE ; } // App was launched with /Unregserver or /Unregister switch. Unregister // typelibrary. Other unregistration occurs in ProcessShellCommand(). else if ( cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister ) { m_server.UpdateRegistry( OAT_DISPATCH_OBJECT, NULL , NULL , FALSE ) ; AfxOleUnregisterTypeLib( _tlid, _wVerMajor, _wVerMinor) ; } // App was launched standalone or with other switches (e.g. /Register // or /Regserver). Update registry entries, including typelibrary. else { m_server.UpdateRegistry( OAT_DISPATCH_OBJECT) ; COleObjectFactory::UpdateRegistryAll ( ) ; AfxOleRegisterTypeLib( AfxGetInstanceHandle( ) , _tlid) ; } // 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 one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow ( SW_SHOW) ; m_pMainWnd->UpdateWindow ( ) ; // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand 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 CmybrowserApp::OnAppAbout ( ) { CAboutDlg aboutDlg; aboutDlg.DoModal( ) ; } // CmybrowserApp message handlers
// mybrowser.idl : type library source for mybrowser.exe
// This file will be processed by the MIDL compiler to produce the // type library (mybrowser.tlb).
[ uuid( AE9746B8-0474 -4194 -A1D5-9838601D1DE6) , version( 1.0 ) ] library mybrowser { importlib( "stdole32.tlb" ) ; importlib( "stdole2.tlb" ) ;
// Primary dispatch interface for CmybrowserDoc [ uuid( F03379DB-AFCA-4A91-A713-EF317F96EA57) ] dispinterface Imybrowser { properties: methods: } ;
// Class information for CmybrowserDoc [ uuid( 81412519 -BCE7-4887 -98F7-F034BC210111) ] coclass CmybrowserDoc { [ default ] dispinterface Imybrowser; } ; } ;
// mybrowserDoc.cpp : implementation of the CmybrowserDoc class //
#include "stdafx.h" #include "mybrowser.h"
#include "mybrowserDoc.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserDoc
IMPLEMENT_DYNCREATE( CmybrowserDoc, CDocument)
BEGIN_MESSAGE_MAP( CmybrowserDoc, CDocument) END_MESSAGE_MAP( )
BEGIN_DISPATCH_MAP( CmybrowserDoc, CDocument) END_DISPATCH_MAP( )
// Note: we add support for IID_Imybrowser to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .IDL file.
// {F03379DB-AFCA-4A91-A713-EF317F96EA57} static const IID IID_Imybrowser ={ 0xF03379DB, 0xAFCA, 0x4A91, { 0xA7, 0x13, 0xEF, 0x31, 0x7F, 0x96, 0xEA, 0x57 } } ;
BEGIN_INTERFACE_MAP( CmybrowserDoc, CDocument) INTERFACE_PART( CmybrowserDoc, IID_Imybrowser, Dispatch) END_INTERFACE_MAP( ) // CmybrowserDoc construction/destruction
CmybrowserDoc::CmybrowserDoc ( ) : url( _T( "" ) ) { // TODO: add one-time construction code here
EnableAutomation( ) ;
AfxOleLockApp( ) ; }
CmybrowserDoc::~CmybrowserDoc( ) { AfxOleUnlockApp( ) ; }
BOOL CmybrowserDoc::OnNewDocument ( ) { if ( !CDocument::OnNewDocument ( ) ) return FALSE ;
// TODO: add reinitialization code here // (SDI documents will reuse this document)
return TRUE ; } // CmybrowserDoc serialization
void CmybrowserDoc::Serialize ( CArchive& ar) { if ( ar.IsStoring( ) ) { // TODO: add storing code here } else { // TODO: add loading code here } } // CmybrowserDoc diagnostics
#ifdef _DEBUG void CmybrowserDoc::AssertValid ( ) const { CDocument::AssertValid ( ) ; }
void CmybrowserDoc::Dump ( CDumpContext& dc) const { CDocument::Dump ( dc) ; } #endif //_DEBUG // CmybrowserDoc commands
// mybrowserView.cpp : implementation of the CmybrowserView class //
#include "stdafx.h" #include "mybrowser.h"
#include "mybrowserDoc.h" #include ".\mybrowserview.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserView
IMPLEMENT_DYNCREATE( CmybrowserView, CHtmlView)
BEGIN_MESSAGE_MAP( CmybrowserView, CHtmlView) // Standard printing commands ON_COMMAND( ID_FILE_PRINT, CHtmlView::OnFilePrint ) ON_COMMAND( ID_FORWARD, OnNavigationForward) ON_COMMAND( ID_BACK, OnNavigationBack) ON_COMMAND( ID_STOP, OnNavigationStop) ON_COMMAND( ID_REFRESH, OnNavigationReload) ON_COMMAND( ID_HOME, OnNavigationHome) ON_COMMAND( ID_SEARCH, OnNavigationSearch) ON_UPDATE_COMMAND_UI( ID_STOP, OnUpdateStop) ON_COMMAND( ID_FILE_OPEN, OnFileOpen) END_MESSAGE_MAP( )
// CmybrowserView construction/destruction
CmybrowserView::CmybrowserView ( ) {
}
CmybrowserView::~CmybrowserView( ) { }
BOOL CmybrowserView::PreCreateWindow ( CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs
return CHtmlView::PreCreateWindow ( cs) ; }
void CmybrowserView::OnInitialUpdate ( ) { CHtmlView::OnInitialUpdate ( ) ; Navigate2( _T( "about:blank" ) ,NULL ,NULL ) ; } // CmybrowserView printing
// CmybrowserView diagnostics
#ifdef _DEBUG void CmybrowserView::AssertValid ( ) const { CHtmlView::AssertValid ( ) ; }
void CmybrowserView::Dump ( CDumpContext& dc) const { CHtmlView::Dump ( dc) ; }
CmybrowserDoc* CmybrowserView::GetDocument ( ) const // non-debug version is inline { ASSERT ( m_pDocument->IsKindOf ( RUNTIME_CLASS( CmybrowserDoc) ) ) ; return ( CmybrowserDoc*) m_pDocument; } #endif //_DEBUG // CmybrowserView message handlers
void CmybrowserView::OnNavigationForward ( ) { GoForward( ) ; }
void CmybrowserView::OnNavigationBack ( ) { GoBack( ) ; }
void CmybrowserView::OnNavigationStop ( ) { Stop( ) ; }
void CmybrowserView::OnNavigationReload ( ) { Refresh( ) ; }
void CmybrowserView::OnNavigationHome ( ) { GoHome( ) ; }
void CmybrowserView::OnNavigationSearch ( ) { GoSearch( ) ; }
void CmybrowserView::OnDocumentComplete ( LPCTSTR lpszURL) {
CString title=" Web Browser" ; ( ( CMainFrame*) GetParentFrame( ) ) ->m_adressbar .SetWindowText( lpszURL) ;
AfxGetMainWnd( ) ->SetWindowText ( GetLocationName( ) + title) ;
( GetDocument( ) ) ->url =lpszURL;
CHtmlView::OnDocumentComplete ( lpszURL) ;
}
void CmybrowserView::OnUpdateStop ( CCmdUI *pCmdUI) { pCmdUI->Enable ( GetBusy( ) ) ; }
void CmybrowserView::OnFileOpen ( ) { static TCHAR BASED_CODE filter[ ] = _T( "HTML Files(*.htm)|*.htm|HTML Files(*.html)|*.html|All Files(*.*)|*.*||" ) ; CFileDialog dlg( TRUE ,_T( "html" ) ,NULL ,OFN_EXPLORER,filter,this) ; dlg.m_ofn.lpstrTitle=_T( "Open HTML file..." ) ; if ( dlg.DoModal( ) !=IDOK) { return ; } CString url( _T( "file://" ) ) ; url+=dlg.GetPathName( ) ; Navigate2( url,NULL ,NULL ) ; } // stdafx.cpp : source file that includes just the standard includes // mybrowser.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information
#include "stdafx.h" // MainFrm.h : interface of the CMainFrame class // #pragma once class CMainFrame : public CFrameWnd{ protected: // create from serialization only CMainFrame( ) ; DECLARE_DYNCREATE( CMainFrame)
// Attributes public:
// Operations public:
// Overrides public: virtual BOOL PreCreateWindow( CREATESTRUCT& cs) ;
// Implementation public: virtual ~CMainFrame( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected: // control bar embedded members CStatusBar m_wndStatusBar; //CToolBar m_wndToolBar; CToolBar m_toolbar; CReBar m_rebar; public: CComboBoxEx m_adressbar;
// Generated message map functions protected: afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct) ; DECLARE_MESSAGE_MAP( ) public: void OnNewURL( void) ; void OnNewURLEnter( void) ; } ;
// mybrowser.h : main header file for the mybrowser application // #pragma once
#ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif
#include "resource.h" // main symbols // CmybrowserApp: // See mybrowser.cpp for the implementation of this class //
class CmybrowserApp : public CWinApp { public: CmybrowserApp( ) ; // Overrides public: virtual BOOL InitInstance( ) ;
// Implementation COleTemplateServer m_server; // Server object for document creation afx_msg void OnAppAbout( ) ; DECLARE_MESSAGE_MAP( ) } ;
extern CmybrowserApp theApp;
// mybrowserDoc.h : interface of the CmybrowserDoc class // #pragma once
class CmybrowserDoc : public CDocument { protected: // create from serialization only CmybrowserDoc( ) ; DECLARE_DYNCREATE( CmybrowserDoc)
// Attributes public:
// Operations public:
// Overrides public: virtual BOOL OnNewDocument( ) ; virtual void Serialize ( CArchive& ar) ;
// Implementation public: virtual ~CmybrowserDoc( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected:
// Generated message map functions protected: DECLARE_MESSAGE_MAP( )
// Generated OLE dispatch map functions
DECLARE_DISPATCH_MAP( ) DECLARE_INTERFACE_MAP( ) public: CString url; } ;
// mybrowserView.h : interface of the CmybrowserView class // #pragma once class CmybrowserView : public CHtmlView{ protected: // create from serialization only CmybrowserView( ) ; DECLARE_DYNCREATE( CmybrowserView)
// Attributes public: CmybrowserDoc* GetDocument( ) const;
// Operations public:
// Overrides public: virtual BOOL PreCreateWindow( CREATESTRUCT& cs) ;protected: virtual void OnInitialUpdate( ) ; // called first time after construct
// Implementation public: virtual ~CmybrowserView( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected:
// Generated message map functions protected: DECLARE_MESSAGE_MAP( ) public: afx_msg void OnNavigationForward( ) ; afx_msg void OnNavigationBack( ) ; afx_msg void OnNavigationStop( ) ; afx_msg void OnNavigationReload( ) ; afx_msg void OnNavigationHome( ) ; afx_msg void OnNavigationSearch( ) ; virtual void OnDocumentComplete( LPCTSTR lpszURL) ; afx_msg void OnUpdateStop( CCmdUI *pCmdUI) ; afx_msg void OnFileOpen( ) ; } ;
#ifndef _DEBUG // debug version in mybrowserView.cpp inline CmybrowserDoc* CmybrowserView::GetDocument ( ) const { return reinterpret_cast<CmybrowserDoc*>( m_pDocument) ; } #endif //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by mybrowser.rc // #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDP_SOCKETS_INIT_FAILED 104 #define IDR_MAINFRAME 128 #define IDR_mybrowserTYPE 129 #define IDI_ICON1 130 #define IDB_HOT 131 #define IDB_COLD 132 #define ID_STOP 57608 #define ID_REFRESH 57609 #define ID_FORWARD 57610 #define ID_SEARCH 57611 #define ID_HOME 57612 #define ID_BACK 57613
// Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 133 #define _APS_NEXT_COMMAND_VALUE 32777 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently
#pragma once
#ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif
// Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. #define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif
#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif
#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. #define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
// turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxhtml.h> // MFC HTML view support #include <afxsock.h> // MFC socket extensions Как сделать простой собственный Web –браузер используя MFC. сем просто, как вы увидите. Далее я опишу процесс разработки пошагово. 9 . Для начала нужно создать новый проект. Выбираем File –New Project – MFC Application. Вводим имя приложения “mybrowser’. Далее идем в настройки проекта. Здесь ставим следующее: “Application Type – Single Type” , “Project style – Windows Explorer”, “Resource language - English”.( Китайский язык пусть оставят сами китайцы, если хотят) . Затем переходим «Generated Classes” и там выбираем «Base Class” – «CHtmlView». Это очень важно, потому что именно этот класс используется как базовый при создании нашего приложения. “CHtmlView” фактически и является основой «движка» нашего браузера. Жмем кнопку и переходим в проект.10 . Для начала компилируем проект, и смотрим что получилось. Мы видим, что загружается страница, ( если компьютер подключен к Интернете) по адресу «http://www.msdn.microsoft.com/visualc/". Нам конечно такой «браузер» не подходит. Теперь займемся нашим главным делом. 11 . Для начала сменим иконку приложения. Для этого перейдем в редактор ресурсов проекта и добавим в качестве нового ресурса новую иконку. Лично я нашел ее в Интернете, а кто хочет, тот может ее нарисовать вручную или взять уже имеющуюся готовую из тех, что есть в любом компьютере. Добавляем новую иконку в редактор ресурсов, используя опцию «Import». Затем вставим следующий код в файл «MainFrm.cpp» в метод «int CMainFrame::OnCreate ( LPCREATESTRUCT lpCreateStruct) »: SetIcon( LoadIcon( AfxGetInstanceHandle( ) ,( LPCTSTR) IDI_ICON1) ,false ) ; Этот код устанавливает новую иконку вместо исходной иконки. Затем мы редактируем метод « CmybrowserView»
void CmybrowserView::OnInitialUpdate ( ) { CHtmlView::OnInitialUpdate ( ) ; Navigate2( _T( "about:blank" ) ,NULL ,NULL ) ;//удаляем адрес Microsoft //и ставим «about:blank» в качестве стартовой страницы, //хотя можно ставить все что угодно. }
Далее нужно сделать новый toolbar для нашего браузера, чтобы он выглядел как в Internet Explorer. Для этого нужно сделать или где-то раздобыть 2 картинки разрабатываемого ресурса. Лично я опять обнаружил их в Сети. Они являются bitmap файлами и содержать точную копию toolbara копируемого нами браузера. Почему нужны 2 файла? Потому что при наведении курсора мыши, один bitmap файл заменяет другой. Получается красивый спецэффект, почти как в настоящем браузере. Файлы после операции импорта переименуем в IDB_HOT и IDB_COLD. Итак, мы импортировали оба эти 2 файла. Теперь нам нужно вернуться в файл «MainFrm.cpp» и сделать буквально следующие, - во-первых, скрыть старый toolbar и вместо него создать несколько новых контролов, а во-вторых, не совершить ошибок в этих действиях. Сперва мы закомментируем переменную «CToolBar m_wndToolBar» в файле «MainFrm.h». Затем там же мы создадим две новых переменных. «CToolBar m_toolbar» и «CReBar m_rebar». Эти переменный позволят нам создать наши новые контролы. Первая переменная создаст объект класса toolbar, а вторая как вы догадались – класса « ReBar». Последняя будет служить как бы новым фундаментом для нашего нового toolbara. Переходим в файл ресурсов mybrowser.rc и создаем там следующие новые идентификаторы: «ID_FORWARD», «ID_STOP», «ID_HOME», «ID_BACK» и «ID_SEARCH». В строке ставим эквиваленты для каждой кнопки. Как вы уже поняли, эти новые ресурсы – это идентификаторы кнопок на нашем новом toolbare. Кроме того, нам нужно еще добавить строку ввода веб адреса. Для этого мы создаем переменную класса «CComboBoxEx m_adressbar» типа «public»в файле MainFrm.h или делаем тоже самое с помощью вызова меню в дереве Project Explorer. Затем переключаемся в файл « MainFrm.cpp» во все тот же метод «int CMainFrame::OnCreate ( LPCREATESTRUCT lpCreateStruct) » и редактируем его таким образом:
int CMainFrame::OnCreate ( LPCREATESTRUCT lpCreateStruct) {
SetIcon( LoadIcon( AfxGetInstanceHandle( ) ,( LPCTSTR) IDI_ICON1) ,false ) ; CImageList img; //создаем переменную класса CImageList для создания кнопок if ( CFrameWnd::OnCreate ( lpCreateStruct) == -1 ) return -1 ;
m_rebar.Create( this) ; //создаем новый контрол Rebar m_toolbar.CreateEx( this) ; создаем новый контрол CToolbar
m_adressbar.Create( CBS_DROPDOWN | WS_CHILD, CRect( 0 , 0 , 200 , 120 ) , this, 101 ) ;// создаем новый контрол CComboBoxEx //создаем кнопки, задаем их число, устанавливаем стили и размещаем там, где необходимо m_toolbar.GetToolBarCtrl( ) .SetButtonWidth( 50 , 150 ) ; m_toolbar.GetToolBarCtrl( ) .SetExtendedStyle( TBSTYLE_EX_DRAWDDARROWS) ;
img.Create( IDB_HOT, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetHotImageList( &img) ; img.Detach( ) ;
img.Create( IDB_COLD, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetImageList( &img) ; img.Detach( ) ;
m_toolbar.ModifyStyle( 0 , TBSTYLE_FLAT | TBSTYLE_TRANSPARENT) ; m_toolbar.SetButtons( NULL , 6 ) ; m_toolbar.SetButtonInfo( 0 , ID_BACK, TBSTYLE_BUTTON, 0 ) ; m_toolbar.SetButtonText( 0 , "Back" ) ;
m_toolbar.SetButtonInfo( 1 , ID_FORWARD, TBSTYLE_BUTTON, 1 ) ; m_toolbar.SetButtonText( 1 , "Forward" ) ;
m_toolbar.SetButtonInfo( 2 , ID_STOP, TBSTYLE_BUTTON, 2 ) ; m_toolbar.SetButtonText( 2 , "Stop" ) ;
m_toolbar.SetButtonInfo( 3 , ID_REFRESH, TBSTYLE_BUTTON, 3 ) ; m_toolbar.SetButtonText( 3 , "Refresh" ) ;
m_toolbar.SetButtonInfo( 4 , ID_HOME, TBSTYLE_BUTTON, 4 ) ; m_toolbar.SetButtonText( 4 , "Home" ) ;
m_toolbar.SetButtonInfo( 5 , ID_SEARCH, TBSTYLE_BUTTON, 5 ) ; m_toolbar.SetButtonText( 5 , "Search" ) ;
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
CRect toolrect;//создаем объект класса CRect для размещаения созданных контролов
m_toolbar.GetItemRect( 0 , &toolrect) ; //размещаем там новый toolbar m_toolbar.SetSizes( toolrect.Size( ) , CSize( 30 ,20 ) ) ; m_rebar.AddBar( &m_toolbar) ;//помещаем объект СToolbar на объекте ReBar
m_rebar.AddBar( &m_adressbar, "address:" , NULL , RBBS_FIXEDBMP | RBBS_BREAK) ; //размещаем на контроле Rebar наш вновь созданный CComboBoxEx m_adressbar return 0 ; }
Компилируем и смотрим программу. Выглядит почти как настоящий, только ничего не работает. Кроме того, надо изменить меню приложения. Этим мы займемся в следующем шаге. 12 . Теперь снова переходим в редактор ресурсов. Открываем пункт «Menu» «IDR_MAINFRAME». Там удаляем полностью пункт меню «Edit», а вместо него создаемновый пункт «Navigation» с пунктами «Forward», «Back», «Stop», «Reload», «Home», «Search». У каждой строки в меню вводим в панели «Properties», в свойстве «Prompt» название пункта меню для отображение. Теперь очень важный момент. Когда мы создаем в новые пункты меню, то в свойстве «ID» пункта меню нужно использовать уже имеющийся идентификатор кнопки нашего toolbara. Такого рода «фокус» позволит нам создать одновременно работающее меню и toolbar. Компилируем программу и видим результат. Однако, из-за того, что мы не назначили никаких обработчиков команд для кнопок на новом toolbare и пунктам меню, то мы видим, что они не активны. ( Кто бы сомневался) . В следующем шаге займемся именно этим, - заставим браузер реально работать. 13 . Чтобы наш браузер начал исполнять команды нужно всего ничего. Открываем редакторресурсов, выбираем там « Menu» «IDR_MAINFRAME» и там в новом пункте меню «Navigation» выделяем пункт меню «Forward», затем щелкаем правой кнопкой мыши и в открывшемся меню находим пункт «Add Event Handler». Во вновь открывшемся окошке выбираем «Message Type:COMMAND» и там же в списке классов, к которому будет принадлежать обработчик «CmybrowserView». Далее жмем кнопку «Add and edit». После этого мы попадаем в файл «mybrowserView.cpp», прямо в новый обработчик . Теперь надо его отредактировать следующим образом:
void CmybrowserView::OnNavigationForward ( ) { GoForward( ) ; } Повторим аналогичные действия для остальных пунктов меню. После этого получаем такой код:
void CmybrowserView::OnNavigationBack ( ) { GoBack( ) ; }
void CmybrowserView::OnNavigationStop ( ) { Stop( ) ; }
void CmybrowserView::OnNavigationReload ( ) { Refresh( ) ; }
void CmybrowserView::OnNavigationHome ( ) { GoHome( ) ; }
void CmybrowserView::OnNavigationSearch ( ) { GoSearch( ) ; }
void CmybrowserView::OnUpdateStop ( CCmdUI *pCmdUI) { pCmdUI->Enable ( GetBusy( ) ) ; } Предпоследний обработчик отправляет пользователя на страницу установленной по умолчанию поисковой системы. У меня например, появился Google. Последний же обработчик мы добавляем к пункту меню «Stop», он активирует эту команду , используя обработчик «ON_UPDATE_COMMAND_UI». Снова все компилируем и смотрим, что получилось. Теперь меню «Navigation» работает. Кроме того, работает и toolbar. Что же касается самих методов, как GoHome( ) и прочие, то они изначально являются доступными для класса «CHtmlView» . То бишь, стоит заглянуть в MSDN и… Надеюсь, всем все понятно. У нас теперь здесь все работает замечательно. 14 . Теперь надо добавить еще одну очень важную вещь. Наш браузер пока что не делает самого главного, - собственно говоря, он ни нак какие адреса в Сети не ходит. Так что, сделаем так, чтобы можно было пользоваться строкой ввода веб адреса. Перейдем в файл «MainFrm.cpp». Добавим туда новый метод типа void – OnGoURL( void) ; void CMainFrame::OnNewURL ( void) { CString str; m_adressbar.GetLBText( m_adressbar.GetCurSel( ) , str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL } Но это еще не все. Нам нужен еще один метод OnNewURLEnter( void) . Он, собственно говоря и делает этот переход на новый веб адрес: void CMainFrame::OnNewURLEnter ( void) { CString str;
m_adressbar.GetEditCtrl( ) ->GetWindowText ( str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
COMBOBOXEXITEM item;
item.mask = CBEIF_TEXT; item.iItem = -1 ; item.pszText = ( LPTSTR) ( LPCTSTR) str; m_adressbar.InsertItem( &item) ; } На конец, нам нужно отредактировать вручную MESSAGE_MAP( ) все того же класса «CMainFrame» таким обарзом: BEGIN_MESSAGE_MAP( CMainFrame, CFrameWnd) ON_WM_CREATE( ) ON_COMMAND( IDOK, OnNewURLEnter) //Эту стоку мы вставляем вручную END_MESSAGE_MAP( ) Компилируем и смотрим. Вводим какой-нибудь адрес и видим, что новую страницу. Работает, и это хорошо. 15 . Если приглядеться, то каждый уважающий себя браузер отображает заголовок загруженной им веб страницы. Наш этого почему-то не делает. Надо исправить это поскорее. В класс “CmybrowserDoc” добавляем переменную типа строка - CString url. Затем переходим в класс «CmybrowserView» и находим в панели «Properties»/«Overrides”. Там выбираем метод «OnDocumentComplete( ) » и кликаем на нем мышью. Затем переходим в сам метод и редактируем его: void CmybrowserView::OnDocumentComplete ( LPCTSTR lpszURL) {
CString title=" Web Browser" ; ( ( CMainFrame*) GetParentFrame( ) ) ->m_adressbar .SetWindowText( lpszURL) ;
AfxGetMainWnd( ) ->SetWindowText ( GetLocationName( ) + title) ;
( GetDocument( ) ) ->url =lpszURL;
CHtmlView::OnDocumentComplete ( lpszURL) ;
}
16 . Теперь идем в редактор ресурсов и выбираем «Menu», там находим пункт «Open…» . Там добавляем обработчик событий, установив его к классу «CmybrowserView». Далее переходим в саму функцию и редактируем следующим обрзаом: void CmybrowserView::OnFileOpen ( ) { static TCHAR BASED_CODE filter[ ] = _T( "HTML Files(*.htm)|*.htm|HTML Files(*.html)|*.html|All Files(*.*)|*.*||" ) ; CFileDialog dlg( TRUE ,_T( "html" ) ,NULL ,OFN_EXPLORER,filter,this) ; dlg.m_ofn.lpstrTitle=_T( "Open HTML file..." ) ; if ( dlg.DoModal( ) !=IDOK) { return ; } CString url( _T( "file://" ) ) ; url+=dlg.GetPathName( ) ; Navigate2( url,NULL ,NULL ) ; }
Пробуем. Мы можем открыть HTML страницу для просмотра..На этом все. Запускаем программу и видим результат. Браузер очень простой, но вполне рабочий. Далее собственно исходный код программы. // MainFrm.cpp : implementation of the CMainFrame class //
#include "stdafx.h" #include "mybrowser.h" #include "mainfrm.h" #include "afxinet.h" #include "mybrowserDoc.h" #include "mybrowserView.h" #include ".\mainfrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame
IMPLEMENT_DYNCREATE( CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP( CMainFrame, CFrameWnd) ON_WM_CREATE( ) ON_COMMAND( IDOK, OnNewURLEnter) 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) {
SetIcon( LoadIcon( AfxGetInstanceHandle( ) ,( LPCTSTR) IDI_ICON1) ,false ) ; CImageList img; //CString str; if ( CFrameWnd::OnCreate ( lpCreateStruct) == -1 ) return -1 ;
m_rebar.Create( this) ; m_toolbar.CreateEx( this) ; m_adressbar.Create( CBS_DROPDOWN | WS_CHILD, CRect( 0 , 0 , 200 , 120 ) , this, 101 ) ;
m_toolbar.GetToolBarCtrl( ) .SetButtonWidth( 50 , 150 ) ; m_toolbar.GetToolBarCtrl( ) .SetExtendedStyle( TBSTYLE_EX_DRAWDDARROWS) ;
img.Create( IDB_HOT, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetHotImageList( &img) ; img.Detach( ) ;
img.Create( IDB_COLD, 22 , 0 , RGB( 255 , 0 , 255 ) ) ; m_toolbar.GetToolBarCtrl( ) .SetImageList( &img) ; img.Detach( ) ;
m_toolbar.ModifyStyle( 0 , TBSTYLE_FLAT | TBSTYLE_TRANSPARENT) ; m_toolbar.SetButtons( NULL , 6 ) ; m_toolbar.SetButtonInfo( 0 , ID_BACK, TBSTYLE_BUTTON, 0 ) ; m_toolbar.SetButtonText( 0 , "Back" ) ;
m_toolbar.SetButtonInfo( 1 , ID_FORWARD, TBSTYLE_BUTTON, 1 ) ; m_toolbar.SetButtonText( 1 , "Forward" ) ;
m_toolbar.SetButtonInfo( 2 , ID_STOP, TBSTYLE_BUTTON, 2 ) ; m_toolbar.SetButtonText( 2 , "Stop" ) ;
m_toolbar.SetButtonInfo( 3 , ID_REFRESH, TBSTYLE_BUTTON, 3 ) ; m_toolbar.SetButtonText( 3 , "Refresh" ) ;
m_toolbar.SetButtonInfo( 4 , ID_HOME, TBSTYLE_BUTTON, 4 ) ; m_toolbar.SetButtonText( 4 , "Home" ) ;
m_toolbar.SetButtonInfo( 5 , ID_SEARCH, TBSTYLE_BUTTON, 5 ) ; m_toolbar.SetButtonText( 5 , "Search" ) ;
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
CRect toolrect;
// set up toolbar button sizes m_toolbar.GetItemRect( 0 , &toolrect) ; m_toolbar.SetSizes( toolrect.Size( ) , CSize( 30 ,20 ) ) ; m_rebar.AddBar( &m_toolbar) ;
m_rebar.AddBar( &m_adressbar, "address:" , NULL , RBBS_FIXEDBMP | RBBS_BREAK) ; return 0 ; }
BOOL CMainFrame::PreCreateWindow ( CREATESTRUCT& cs) { if ( !CFrameWnd::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 { CFrameWnd::AssertValid ( ) ; }
void CMainFrame::Dump ( CDumpContext& dc) const { CFrameWnd::Dump ( dc) ; }
#endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnNewURL ( void) { CString str; m_adressbar.GetLBText( m_adressbar.GetCurSel( ) , str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
}
void CMainFrame::OnNewURLEnter ( void) { CString str; m_adressbar.GetEditCtrl( ) ->GetWindowText ( str) ; ( ( CmybrowserView*) GetActiveView( ) ) ->Navigate2 ( str, 0 , NULL ) ;
COMBOBOXEXITEM item;
item.mask = CBEIF_TEXT; item.iItem = -1 ; item.pszText = ( LPTSTR) ( LPCTSTR) str; m_adressbar.InsertItem( &item) ; } // mybrowser.cpp : Defines the class behaviors for the application. //
#include "stdafx.h" #include "mybrowser.h" #include "MainFrm.h"
#include "mybrowserDoc.h" #include "mybrowserView.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserApp
BEGIN_MESSAGE_MAP( CmybrowserApp, CWinApp) ON_COMMAND( ID_APP_ABOUT, OnAppAbout) // 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( ) // CmybrowserApp construction
CmybrowserApp::CmybrowserApp ( ) { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CmybrowserApp object
CmybrowserApp theApp; // This identifier was generated to be statistically unique for your app // You may change it if you prefer to choose a specific identifier
// {81412519-BCE7-4887-98F7-F034BC210111} static const CLSID clsid ={ 0x81412519, 0xBCE7, 0x4887, { 0x98, 0xF7, 0xF0, 0x34, 0xBC, 0x21, 0x1, 0x11 } } ;const GUID CDECL BASED_CODE _tlid = { 0xAE9746B8, 0x474, 0x4194, { 0xA1, 0xD5, 0x98, 0x38, 0x60, 0x1D, 0x1D, 0xE6 } } ; const WORD _wVerMajor = 1 ; const WORD _wVerMinor = 0 ; // CmybrowserApp initialization
BOOL CmybrowserApp::InitInstance ( ) { // InitCommonControls() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. InitCommonControls( ) ;
CWinApp::InitInstance ( ) ;
if ( !AfxSocketInit( ) ) { AfxMessageBox( IDP_SOCKETS_INIT_FAILED) ; return FALSE ; }
// Initialize OLE libraries if ( !AfxOleInit( ) ) { AfxMessageBox( IDP_OLE_INIT_FAILED) ; return FALSE ; } 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 // 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( 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 CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS( CmybrowserDoc) , RUNTIME_CLASS( CMainFrame) , // main SDI frame window RUNTIME_CLASS( CmybrowserView) ) ; if ( !pDocTemplate) return FALSE ; AddDocTemplate( pDocTemplate) ; // Connect the COleTemplateServer to the document template // The COleTemplateServer creates new documents on behalf // of requesting OLE containers by using information // specified in the document template m_server.ConnectTemplate( clsid, pDocTemplate, TRUE ) ; // Note: SDI applications register server objects only if /Embedding // or /Automation is present on the command line // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine( cmdInfo) ; // App was launched with /Embedding or /Automation switch. // Run app as automation server. if ( cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated) { // Register all OLE server factories as running. This enables the // OLE libraries to create objects from other applications COleTemplateServer::RegisterAll ( ) ;
// Don't show the main window return TRUE ; } // App was launched with /Unregserver or /Unregister switch. Unregister // typelibrary. Other unregistration occurs in ProcessShellCommand(). else if ( cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister ) { m_server.UpdateRegistry( OAT_DISPATCH_OBJECT, NULL , NULL , FALSE ) ; AfxOleUnregisterTypeLib( _tlid, _wVerMajor, _wVerMinor) ; } // App was launched standalone or with other switches (e.g. /Register // or /Regserver). Update registry entries, including typelibrary. else { m_server.UpdateRegistry( OAT_DISPATCH_OBJECT) ; COleObjectFactory::UpdateRegistryAll ( ) ; AfxOleRegisterTypeLib( AfxGetInstanceHandle( ) , _tlid) ; } // 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 one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow ( SW_SHOW) ; m_pMainWnd->UpdateWindow ( ) ; // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand 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 CmybrowserApp::OnAppAbout ( ) { CAboutDlg aboutDlg; aboutDlg.DoModal( ) ; } // CmybrowserApp message handlers
// mybrowser.idl : type library source for mybrowser.exe
// This file will be processed by the MIDL compiler to produce the // type library (mybrowser.tlb).
[ uuid( AE9746B8-0474 -4194 -A1D5-9838601D1DE6) , version( 1.0 ) ] library mybrowser { importlib( "stdole32.tlb" ) ; importlib( "stdole2.tlb" ) ;
// Primary dispatch interface for CmybrowserDoc [ uuid( F03379DB-AFCA-4A91-A713-EF317F96EA57) ] dispinterface Imybrowser { properties: methods: } ;
// Class information for CmybrowserDoc [ uuid( 81412519 -BCE7-4887 -98F7-F034BC210111) ] coclass CmybrowserDoc { [ default ] dispinterface Imybrowser; } ; } ;
// mybrowserDoc.cpp : implementation of the CmybrowserDoc class //
#include "stdafx.h" #include "mybrowser.h"
#include "mybrowserDoc.h"
#ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserDoc
IMPLEMENT_DYNCREATE( CmybrowserDoc, CDocument)
BEGIN_MESSAGE_MAP( CmybrowserDoc, CDocument) END_MESSAGE_MAP( )
BEGIN_DISPATCH_MAP( CmybrowserDoc, CDocument) END_DISPATCH_MAP( )
// Note: we add support for IID_Imybrowser to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .IDL file.
// {F03379DB-AFCA-4A91-A713-EF317F96EA57} static const IID IID_Imybrowser ={ 0xF03379DB, 0xAFCA, 0x4A91, { 0xA7, 0x13, 0xEF, 0x31, 0x7F, 0x96, 0xEA, 0x57 } } ;
BEGIN_INTERFACE_MAP( CmybrowserDoc, CDocument) INTERFACE_PART( CmybrowserDoc, IID_Imybrowser, Dispatch) END_INTERFACE_MAP( ) // CmybrowserDoc construction/destruction
CmybrowserDoc::CmybrowserDoc ( ) : url( _T( "" ) ) { // TODO: add one-time construction code here
EnableAutomation( ) ;
AfxOleLockApp( ) ; }
CmybrowserDoc::~CmybrowserDoc( ) { AfxOleUnlockApp( ) ; }
BOOL CmybrowserDoc::OnNewDocument ( ) { if ( !CDocument::OnNewDocument ( ) ) return FALSE ;
// TODO: add reinitialization code here // (SDI documents will reuse this document)
return TRUE ; } // CmybrowserDoc serialization
void CmybrowserDoc::Serialize ( CArchive& ar) { if ( ar.IsStoring( ) ) { // TODO: add storing code here } else { // TODO: add loading code here } } // CmybrowserDoc diagnostics
#ifdef _DEBUG void CmybrowserDoc::AssertValid ( ) const { CDocument::AssertValid ( ) ; }
void CmybrowserDoc::Dump ( CDumpContext& dc) const { CDocument::Dump ( dc) ; } #endif //_DEBUG // CmybrowserDoc commands
// mybrowserView.cpp : implementation of the CmybrowserView class //
#include "stdafx.h" #include "mybrowser.h"
#include "mybrowserDoc.h" #include ".\mybrowserview.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CmybrowserView
IMPLEMENT_DYNCREATE( CmybrowserView, CHtmlView)
BEGIN_MESSAGE_MAP( CmybrowserView, CHtmlView) // Standard printing commands ON_COMMAND( ID_FILE_PRINT, CHtmlView::OnFilePrint ) ON_COMMAND( ID_FORWARD, OnNavigationForward) ON_COMMAND( ID_BACK, OnNavigationBack) ON_COMMAND( ID_STOP, OnNavigationStop) ON_COMMAND( ID_REFRESH, OnNavigationReload) ON_COMMAND( ID_HOME, OnNavigationHome) ON_COMMAND( ID_SEARCH, OnNavigationSearch) ON_UPDATE_COMMAND_UI( ID_STOP, OnUpdateStop) ON_COMMAND( ID_FILE_OPEN, OnFileOpen) END_MESSAGE_MAP( )
// CmybrowserView construction/destruction
CmybrowserView::CmybrowserView ( ) {
}
CmybrowserView::~CmybrowserView( ) { }
BOOL CmybrowserView::PreCreateWindow ( CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs
return CHtmlView::PreCreateWindow ( cs) ; }
void CmybrowserView::OnInitialUpdate ( ) { CHtmlView::OnInitialUpdate ( ) ; Navigate2( _T( "about:blank" ) ,NULL ,NULL ) ; } // CmybrowserView printing
// CmybrowserView diagnostics
#ifdef _DEBUG void CmybrowserView::AssertValid ( ) const { CHtmlView::AssertValid ( ) ; }
void CmybrowserView::Dump ( CDumpContext& dc) const { CHtmlView::Dump ( dc) ; }
CmybrowserDoc* CmybrowserView::GetDocument ( ) const // non-debug version is inline { ASSERT ( m_pDocument->IsKindOf ( RUNTIME_CLASS( CmybrowserDoc) ) ) ; return ( CmybrowserDoc*) m_pDocument; } #endif //_DEBUG // CmybrowserView message handlers
void CmybrowserView::OnNavigationForward ( ) { GoForward( ) ; }
void CmybrowserView::OnNavigationBack ( ) { GoBack( ) ; }
void CmybrowserView::OnNavigationStop ( ) { Stop( ) ; }
void CmybrowserView::OnNavigationReload ( ) { Refresh( ) ; }
void CmybrowserView::OnNavigationHome ( ) { GoHome( ) ; }
void CmybrowserView::OnNavigationSearch ( ) { GoSearch( ) ; }
void CmybrowserView::OnDocumentComplete ( LPCTSTR lpszURL) {
CString title=" Web Browser" ; ( ( CMainFrame*) GetParentFrame( ) ) ->m_adressbar .SetWindowText( lpszURL) ;
AfxGetMainWnd( ) ->SetWindowText ( GetLocationName( ) + title) ;
( GetDocument( ) ) ->url =lpszURL;
CHtmlView::OnDocumentComplete ( lpszURL) ;
}
void CmybrowserView::OnUpdateStop ( CCmdUI *pCmdUI) { pCmdUI->Enable ( GetBusy( ) ) ; }
void CmybrowserView::OnFileOpen ( ) { static TCHAR BASED_CODE filter[ ] = _T( "HTML Files(*.htm)|*.htm|HTML Files(*.html)|*.html|All Files(*.*)|*.*||" ) ; CFileDialog dlg( TRUE ,_T( "html" ) ,NULL ,OFN_EXPLORER,filter,this) ; dlg.m_ofn.lpstrTitle=_T( "Open HTML file..." ) ; if ( dlg.DoModal( ) !=IDOK) { return ; } CString url( _T( "file://" ) ) ; url+=dlg.GetPathName( ) ; Navigate2( url,NULL ,NULL ) ; } // stdafx.cpp : source file that includes just the standard includes // mybrowser.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information
#include "stdafx.h" // MainFrm.h : interface of the CMainFrame class // #pragma once class CMainFrame : public CFrameWnd{ protected: // create from serialization only CMainFrame( ) ; DECLARE_DYNCREATE( CMainFrame)
// Attributes public:
// Operations public:
// Overrides public: virtual BOOL PreCreateWindow( CREATESTRUCT& cs) ;
// Implementation public: virtual ~CMainFrame( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected: // control bar embedded members CStatusBar m_wndStatusBar; //CToolBar m_wndToolBar; CToolBar m_toolbar; CReBar m_rebar; public: CComboBoxEx m_adressbar;
// Generated message map functions protected: afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct) ; DECLARE_MESSAGE_MAP( ) public: void OnNewURL( void) ; void OnNewURLEnter( void) ; } ;
// mybrowser.h : main header file for the mybrowser application // #pragma once
#ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif
#include "resource.h" // main symbols // CmybrowserApp: // See mybrowser.cpp for the implementation of this class //
class CmybrowserApp : public CWinApp { public: CmybrowserApp( ) ; // Overrides public: virtual BOOL InitInstance( ) ;
// Implementation COleTemplateServer m_server; // Server object for document creation afx_msg void OnAppAbout( ) ; DECLARE_MESSAGE_MAP( ) } ;
extern CmybrowserApp theApp;
// mybrowserDoc.h : interface of the CmybrowserDoc class // #pragma once
class CmybrowserDoc : public CDocument { protected: // create from serialization only CmybrowserDoc( ) ; DECLARE_DYNCREATE( CmybrowserDoc)
// Attributes public:
// Operations public:
// Overrides public: virtual BOOL OnNewDocument( ) ; virtual void Serialize ( CArchive& ar) ;
// Implementation public: virtual ~CmybrowserDoc( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected:
// Generated message map functions protected: DECLARE_MESSAGE_MAP( )
// Generated OLE dispatch map functions
DECLARE_DISPATCH_MAP( ) DECLARE_INTERFACE_MAP( ) public: CString url; } ;
// mybrowserView.h : interface of the CmybrowserView class // #pragma once class CmybrowserView : public CHtmlView{ protected: // create from serialization only CmybrowserView( ) ; DECLARE_DYNCREATE( CmybrowserView)
// Attributes public: CmybrowserDoc* GetDocument( ) const;
// Operations public:
// Overrides public: virtual BOOL PreCreateWindow( CREATESTRUCT& cs) ;protected: virtual void OnInitialUpdate( ) ; // called first time after construct
// Implementation public: virtual ~CmybrowserView( ) ; #ifdef _DEBUG virtual void AssertValid( ) const; virtual void Dump( CDumpContext& dc) const; #endif
protected:
// Generated message map functions protected: DECLARE_MESSAGE_MAP( ) public: afx_msg void OnNavigationForward( ) ; afx_msg void OnNavigationBack( ) ; afx_msg void OnNavigationStop( ) ; afx_msg void OnNavigationReload( ) ; afx_msg void OnNavigationHome( ) ; afx_msg void OnNavigationSearch( ) ; virtual void OnDocumentComplete( LPCTSTR lpszURL) ; afx_msg void OnUpdateStop( CCmdUI *pCmdUI) ; afx_msg void OnFileOpen( ) ; } ;
#ifndef _DEBUG // debug version in mybrowserView.cpp inline CmybrowserDoc* CmybrowserView::GetDocument ( ) const { return reinterpret_cast<CmybrowserDoc*>( m_pDocument) ; } #endif //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by mybrowser.rc // #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDP_SOCKETS_INIT_FAILED 104 #define IDR_MAINFRAME 128 #define IDR_mybrowserTYPE 129 #define IDI_ICON1 130 #define IDB_HOT 131 #define IDB_COLD 132 #define ID_STOP 57608 #define ID_REFRESH 57609 #define ID_FORWARD 57610 #define ID_SEARCH 57611 #define ID_HOME 57612 #define ID_BACK 57613
// Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 133 #define _APS_NEXT_COMMAND_VALUE 32777 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently
#pragma once
#ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif
// Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. #define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. #define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif
#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif
#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. #define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
// turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxhtml.h> // MFC HTML view support #include <afxsock.h> // MFC socket extensions