MFC drawing
The use of drawing objects,
CBitmap use
A compatible DC created at the current DC (same as in-memory data structures)
Selecting a bitmap into a compatible DC
Copy a bitmap from a compatible DC to the current DC
Select a bitmap from a compatible DC to restore the bitmap
Remove a compatible DC
Delete a Bitmap object
CRGN Complex areas
Creating a geometric region
Crgn::createxxx
The operation of two geometric regions can be performed multiple times
Crgn::combinergn
Fill Area
Cdc::fillrgn
Fill border
Cdc::framergn
Cwnd::setwindowrgn Creating irregular windows, buttons
CPalette palette, used to set the color, reduce
MFC collection Classes
Arrays Dynamic Array
Carrays template class
Lists linked list (doubly linked list)
CList template class
Maps maps
CMap template class
Template classes store data for custom types
Non-template classes store specific types of data
CArray
Use: Define
template< class TYPE, Class Arg_type > class Carray:public CObject
Type of the element to store
Arg_type parameter types for CArray member functions
Custom classes are required, dolls constructed, or have default parameters
The collection periodically calls the default construct
To estimate the number of elements to be stored, set the initial size of the array
CList
Define the same parameters as CArray
POSITION Find (Arg_type searchvalue, POSITION startafter = NULL) const;
Calling the Find function requires overloading the = = operator
template< class KEY, Class Arg_key, Class VALUE, Class Arg_value >
Class Cmap:public CObject
Find elements find values by key
Lookup
***************************
Key-->hashcode
Nindex=hashcode%nsize
*****************************************
Template<class KEY, Class Arg_key, Class VALUE, class arg_value>
Class Cmap:public CObject
{
Protected
Association
struct CASSOC
{
cassoc* Pnext; Linked list
UINT Nhashvalue; Needed for efficient iteration
Key key;
Value value;
};
Public
Construction
CMap (int nblocksize = 10);
Attributes
Number of elements
int GetCount () const;
BOOL IsEmpty () const;
Lookup
BOOL Lookup (Arg_key KEY, value& rValue) const;
Operations
Lookup and add if not there
value& operator[] (Arg_key KEY);
Add a new (key, value) pair
void SetAt (Arg_key KEY, Arg_value newvalue);
Removing existing (key,?) pair
BOOL RemoveKey (Arg_key KEY);
void RemoveAll ();
Iterating all (key, value) pairs
POSITION getstartposition () const;
void GetNextAssoc (position& rnextposition, key& Rkey, value& rValue) const;
Advanced features for derived classes
UINT gethashtablesize () const;
void InitHashTable (UINT hashsize, BOOL ballocnow = TRUE);
Implementation
Protected
cassoc** m_phashtable;
UINT m_nhashtablesize;
int m_ncount;
cassoc* m_pfreelist;
struct cplex* m_pblocks;
int m_nblocksize;
cassoc* Newassoc ();
void Freeassoc (cassoc*);
cassoc* Getassocat (Arg_key, uint&) const;
Public
~cmap ();
void Serialize (carchive&);
#ifdef _DEBUG
void Dump (cdumpcontext&) const;
void AssertValid () const;
#endif
};
Source
MainFrm.cpp:implementation of the CMainFrame class//#include "stdafx.h" #include "MFCDraw.h" #include "MainFrm.h" # ifdef _debug#define New Debug_new#undef this_filestatic char this_file[] = __file__; #endif//////////////////////////// Cmainframeimplement_dyncreate (CMainFrame, CFrameWnd) begin_ Message_map (CMainFrame, CFrameWnd)//{{afx_msg_map (CMainFrame)//Note-the ClassWizard would add and remove mapping macros here.//do not EDIT the what you see in these blocks of generated code! On_wm_create ()//}}afx_msg_mapend_message_map () static UINT indicators[] ={id_separator,//Status line Indicatori d_indicator_caps,id_indicator_num,id_indicator_scrl,};//////////////////////////////////////////////////////// CMainFrame Construction/destructioncmainframe::cmainframe () {//Todo:add member Initialization code Here}cmainframe::~cmainframe () {}int cmainframe::oncreate (lpcreatestruct LPCREATESTRUCT) {if ( Cframewnd::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//is Dockablem_wndtoolbar.enabledock ING (cbrs_align_any); EnableDocking (Cbrs_align_any);D Ockcontrolbar (&m_wndtoolbar); return 0;} BOOL CMainFrame::P Recreatewindow (createstruct& cs) {if (! CFrameWnd::P Recreatewindow (CS)) return false;//todo:modify the Window class or styles here by modifying//the CREATESTR UCT Csreturn TRUE;} CMainFrame Diagnostics#ifdef _ DebugvoiD cmainframe::assertvalid () Const{cframewnd::assertvalid ();} void CMainFrame::D UMP (cdumpcontext& DC) Const{cframewnd::D UMP (DC);} #endif//_debug///////////////////////////////////////////////////////////////////////////////CMainFrame Message Handlers
MFCDraw.cpp:Defines the class behaviors for the application.//#include "stdafx.h" #include "MFCDraw.h" #include "mainfr M.h "#include" MFCDrawDoc.h "#include" MFCDrawView.h "#ifdef _debug#define new debug_new#undef this_filestatic Char This_ File[] = __file__; #endif/////////////////////////////////////////////////////////////////////////////// Cmfcdrawappbegin_message_map (Cmfcdrawapp, CWinApp)//{{afx_msg_map (Cmfcdrawapp) on_command (ID_APP_ABOUT, Onappabout)//Note-the ClassWizard would add and remove mapping macros here.//do not EDIT "What if see in these block" S of generated code!//}}afx_msg_map//standard file based document Commandson_command (Id_file_new, CWinApp::OnFileNew) On_command (Id_file_open, Cwinapp::onfileopen)//Standard Print Setup Commandon_command (Id_file_print_setup, CWinApp: : OnFilePrintSetup) End_message_map ()/////////////////////////////////////////////////////////////////////////// Cmfcdrawapp Constructioncmfcdrawapp::cmfcdrawapp () {//Todo:add Construction Codehere,//Place all significant initialization in initinstance}/////////////////////////////////////////////////////// The one and only Cmfcdrawapp Objectcmfcdrawapp theapp;////////////////////////////////////// Cmfcdrawapp Initializationbool cmfcdrawapp::initinstance () { AfxEnableControlContainer ();//Standard initialization//If is not a using these features and wish to reduce the size// of your final executable, you should remove from the following//the specific initialization routines don't do need.# Ifdef _afxdllenable3dcontrols ();//Call this if using MFC in a shared dll#elseenable3dcontrolsstatic (); Linking to MFC statically#endif//change the registry key under which our settings is stored.//todo:you should modify This string to is 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 (CMFCDRAWDOC), Runtime_class (CMainFrame),//main SDI frame Windowruntime_class (Cmfcdrawview)); AddDocTemplate (pdoctemplate);//Parse command line to standard shell commands, DDE, file Openccommandlineinfo cmdinfo; ParseCommandLine (cmdinfo);//Dispatch commands specified on the command Lineif (! ProcessShellCommand (Cmdinfo)) return false;//the one and only window have been initialized, so show and update It.m_pmainwn D->showwindow (sw_show); M_pmainwnd->updatewindow (); return TRUE;} CAboutDlg dialog used for APP Aboutclass 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//implementationprotected://{{afx_msg (caboutdlg) AFX_MSG void OnDcCpen (); AFX_MSG void Ondcgdibrush (); afx_msg void Ondcgdifont (); afx_msg void Ondcgdipen ();//}}afx_msgdeclare_message_map ()}; Caboutdlg::caboutdlg (): CDialog (Caboutdlg::idd) {//{{afx_data_init (CAboutDlg)//}}afx_data_init}void CABOUTDLG::D Odataexchange (cdataexchange* pdx) {CDialog::D odataexchange (PDX);//{{afx_data_map (CAboutDlg)//}}afx_data_map} Begin_message_map (CAboutDlg, CDialog)//{{afx_msg_map (CAboutDlg)//on_command (Id_dc_cpen, Ondccpen)//ON_COMMAND (ID _dc_gdibrush, Ondcgdibrush)//on_command (Id_dc_gdifont, Ondcgdifont)//on_command (Id_dc_gdipen, OnDcGdipen)//}}AFX_ Msg_mapend_message_map ()//APP command to run the Dialogvoid cmfcdrawapp::onappabout () {CAboutDlg aboutdlg; Aboutdlg.domodal ();} ///////////////////////////////////////////////Cmfcdrawapp message handlersvoid Caboutdlg::ondccpen () {//Todo:add your command Handler Code here}void Caboutdlg::ondcgdibrush () {//Todo:add your command handler code here}void Caboutdlg::ondcgdifont ( ) {//Todo:add your command handler code here}void Caboutdlg::ondcgdipen () {//Todo:add your command handler code here}
MFCDrawDoc.cpp:implementation of the Cmfcdrawdoc class//#include "stdafx.h" #include "MFCDraw.h" #include "Mfcdrawdoc . h "#ifdef _debug#define new Debug_new#undef this_filestatic char this_file[] = __file__; #endif//////////////////////// Cmfcdrawdocimplement_dyncreate (Cmfcdrawdoc, CDocument) Begin_message_map (Cmfcdrawdoc, CDocument)//{{afx_msg_map (Cmfcdrawdoc)//Note-the ClassWizard would add and remove Mapping macros here.//do don't EDIT what are see in these blocks of generated code!//}}afx_msg_mapend_message_map ()///// Cmfcdrawdoc construction/ Destructioncmfcdrawdoc::cmfcdrawdoc () {//Todo:add one-time Construction Code Here}cmfcdrawdoc::~cmfcdrawdoc () {}BOOL Cmfcdrawdoc::onnewdocument () {if (! Cdocument::onnewdocument ()) return false;//todo:add reinitialization code here//(SDI documents would reuse this document) return TRUE;} /////////////////////////////Cmfcdrawdoc serializationvoid cmfcdrawdoc::serialize (CArchive & AR) {if (AR. IsStoring ()) {//Todo:add storing code here}else{//todo:add loading code here}}/////////////////////////////////////// Cmfcdrawdoc diagnostics#ifdef _debugvoid cmfcdrawdoc::assertvalid () const{ Cdocument::assertvalid ();} void Cmfcdrawdoc::D UMP (cdumpcontext& DC) Const{cdocument::D UMP (DC);} #endif//_debug///////////////////////////////////////////////////////////////////////////////CMFCDrawDoc Commands
MFCDrawView.cpp:implementation of the Cmfcdrawview class//#include "stdafx.h" #include "MFCDraw.h" #include " MFCDrawDoc.h "#include" MFCDrawView.h "#ifdef _debug#define new Debug_new#undef this_filestatic char this_file[] = __file __; #endif///////////////////////////////////////////////////////////////////////////////CMFCDrawViewIMPLEMENT_ Dyncreate (Cmfcdrawview, CView) begin_message_map (Cmfcdrawview, CView)//{{afx_msg_map (Cmfcdrawview) ON_COMMAND (ID_ Dc_cpen, Ondccpen) on_command (Id_dc_gdibrush, Ondcgdibrush) on_command (Id_dc_gdifont, Ondcgdifont) ON_COMMAND (ID_DC_ Gdipen, Ondcgdipen) on_command (id_gdi_bmp, Ongdibmp) on_command (Id_gdi_rgn, Ongdirgn) on_command (ID_GDI_LINE, Ongdiline) On_command (Id_gdi_ellipse, Ongdiellipse) on_command (Id_gdi_rect, Ongdirect) ON_WM_LBUTTONUP () ON_WM_ Lbuttondown ()//}}afx_msg_map//standard printing Commandson_command (Id_file_print, Cview::onfileprint) ON_COMMAND ( Id_file_print_direct, Cview::onfileprint) on_command (Id_file_print_preview, Cview::onfileprintpreview) END_MESsage_map ()///////////////////////////////////////////////////////////////////////////////CMFCDrawView Construction/destructioncmfcdrawview::cmfcdrawview () {//Todo:add Construction code here//m_ptbegin;m_ndrawtype=0;} Cmfcdrawview::~cmfcdrawview () {}bool Cmfcdrawview::P Recreatewindow (createstruct& cs) {//Todo:modify the Window class or Styles here by modifying//the createstruct csreturn CView::P Recreatewindow (CS);} Cmfcdrawview drawingvoid Cmfcdrawview::ondraw (cdc* pDC) {cmfcdrawdoc* PDoc = GetDocument (); Assert_valid (PDOC);//Todo:add Draw code for native data here}/////////////////////////////////////////////////////// Cmfcdrawview printingbool cmfcdrawview::onprepareprinting (cprintinfo* pInfo) {//default Preparationreturn doprepareprinting (pInfo);} void Cmfcdrawview::onbeginprinting (cdc*/*pdc*/, cprintinfo*/*pinfo*/) {//Todo:add extra initialization before Printing}void CMFCdrawview::onendprinting (cdc*/*pdc*/, cprintinfo*/*pinfo*/) {//Todo:add cleanup after printing}//////////////////// Cmfcdrawview diagnostics#ifdef _debugvoid Cmfcdrawview :: AssertValid () Const{cview::assertvalid ();} void Cmfcdrawview::D UMP (cdumpcontext& DC) Const{cview::D UMP (DC);} cmfcdrawdoc* cmfcdrawview::getdocument ()//Non-debug version is Inline{assert (M_pdocument->iskindof (RUNTIME_ CLASS (Cmfcdrawdoc)); return (cmfcdrawdoc*) m_pdocument;} #endif//_debug///////////////////////////////////////////////////////////////////////////////CMFCDrawView Message handlersvoid Cmfcdrawview::ondccpen () {//Todo:add your command handler code HERECCLIENTDC DC (this); CPen Pen (Ps_solid,5,rgb (255,0,0)); CPen *POLDPEN=DC. SelectObject (&pen);d C. Rectangle (50,50,150,200);d C. SelectObject (poldpen);p en. DeleteObject ();} void Cmfcdrawview::ondcgdibrush () {//Todo:add your command handler code HERECCLIENTDC DC (this); CBitmap bitmap;bitmap.loadbItmap (IDB_BITMAP1);//cbrush Brush (Hs_bdiagonal,rgb (0,255,0)); CBrush Brush (&BITMAP); CBrush *POLDBRUSH=DC. SelectObject (&brush); RECT rect={100,100,250,200};d c. FillRect (&rect,&brush);d C. SelectObject (&poldbrush); brush. DeleteObject ();} void Cmfcdrawview::ondcgdifont () {//Todo:add your command handler code HERECCLIENTDC DC (this); CFont Font;font. CreatePointFont (500, "blackbody"); CFont *POLDFONT=DC. SelectObject (&font);d C. TextOut (100,100, "Hello CFont");d C. SelectObject (poldfont); font. DeleteObject ();} void Cmfcdrawview::ondcgdipen () {//Todo:add your command handler code here}void cmfcdrawview::ongdibmp () {//Todo:add y We command handler code HERECCLIENTDC DC (this);//cannot directly select the bitmap into the DC, the bitmap size is not fixed. CBitmap bmp;bmp. LoadBitmap (IDB_BITMAP2);//Create Compatible DCCDC DCBMP;DCBMP.CREATECOMPATIBLEDC (&DC);//select bitmap into compatible dccbitmap*poldbmp= Dcbmp.selectobject (&bmp);//Copy the bitmap from a compatible DC to the current DC/*DC. BitBlt (0,0,253,200,&dcbmp,0,0,srccopy); */crect rcclient; GetClientRect (&rcclient);d C. StretchBlt (0,0,rcclient.width (), RcCLient. Height (), &dcbmp,0,0,253,200,srccopy);d cbmp.selectobject (poldbmp);d Cbmp.deletedc (), BMP. DeleteObject ();} void Cmfcdrawview::ongdirgn () {//Todo:add your command handler code HERECCLIENTDC DC (this); CBrush Brush (RGB (255,0,0)); cbrush* POLDBRUSH=DC. SelectObject (&brush); CRgn rgn1,rgn2,rgn3;rgn1. CreateRectRgn (100,100,300,200); rgn2. CreateEllipticRgn (150,150,300,250); Rgn2.combinergn (&rgn1,&rgn2,rgn_diff);d C. Fillrgn (&rgn2,&brush);d C. SelectObject (Poldbrush); brush. DeleteObject (); AfxGetMainWnd ()->setwindowrgn (rgn1,true);//Make Irregular window button//cwnd::setwindowrgn}void cmfcdrawview::ongdiline () {// Todo:add your command handler code herem_ndrawtype=0;m_ptbegin=0;m_ptend=0;} void Cmfcdrawview::ongdiellipse () {//Todo:add your command handler code herem_ndrawtype=2;} void Cmfcdrawview::ongdirect () {//Todo:add your command handler code herem_ndrawtype=1;} void Cmfcdrawview::onlbuttonup (UINT nflags, CPoint point) {//Todo:add your message handler code here and/or call default M_pteNd=point; CCLIENTDC DC (this), switch (m_ndrawtype) {case 0:{DC. MoveTo (M_PTBEGIN.X,M_PTBEGIN.Y);d C. LineTo (M_PTEND.X,M_PTEND.Y); }case 1:{DC. Rectangle (M_PTBEGIN.X,M_PTBEGIN.Y,M_PTEND.X,M_PTEND.Y); }case 2:{DC. Ellipse (M_PTBEGIN.X,M_PTBEGIN.Y,M_PTEND.X,M_PTEND.Y); }}cview::onlbuttonup (nflags, point);} void Cmfcdrawview::onlbuttondown (UINT nflags, CPoint point) {//Todo:add your message handler code here and/or call Defau Ltm_ptbegin=point; Cview::onlbuttondown (nflags, point);}
MFC eighth Day