Sie sind auf Seite 1von 19

Chng 4: DRAWING GRAPHICS 1) Documents, Views v Frames

To ng dng SDI (Single Document Interface) Chn menu File -> New -> Xut hin ca s New, Ta chn th Projects, Sau thc hin y d ba bc sau: Bc 1: Chn MFC AppWizard(exe) Bc 2: Xc nh th mc cha ng dng trong mc Location Bc 3: t tn cho ng dng trong mc Project Name

-> Xut hin ca s MFC AppWizard cho php ta chn mt trong ba Kiu
giao din ca ng dng l Single Document, Multiple Documents v Dialog Based.

2) Drawing in Device contexts


Device Contexts l g? S dng lp CDC:

Mt s hm trong lp CDC Hm MoveTo(): Moves the current position to the point specified by x and y (or by point).
CPoint MoveTo( int x, int y ); CPoint MoveTo( POINT point );

Hm LineTo(): Draws a line from the current position up to, but not including, the point specified by x and y (or point).
BOOL LineTo( int x, int y ); BOOL LineTo( POINT point );

Hm Rectangle(): Draws a rectangle using the current pen.


BOOL Rectangle( int x1, int y1, int x2, int y2 ); BOOL Rectangle(

LPCRECT lpRect );

Hm Ellipse(): Draws an ellipse.


BOOL Ellipse( int x1, int y1, int x2, int y2 ); BOOL Ellipse( LPCRECT lpRect );

Mt s hm ca lp CWnd: Hm GetDC(): Retrieves a pointer to a common, class, or private device context for the client area depending on the class style specified for the CWnd.
CDC* GetDC( );

S dng lp CClientDC:

Hm to: Constructs a CClientDC object that accesses the client area of the CWnd pointed to by pWnd.
explicit CClientDC( CWnd* pWnd );

S dng lp CPaintDC:

Hm to: Constructs a CPaintDC object, prepares the application window for painting, and stores the PAINTSTRUCT structure in the m_ps member variable.
explicit CPaintDC( CWnd* pWnd );

A CPaintDC object can only be used when responding to a WM_PAINT message, usually in your OnPaint message-handler member function.

3) S kin x l Mouse
WM_LBUTTONUP : The framework calls this member function when the user releases the left mouse button.
afx_msg void OnLButtonUp( UINT nFlags, CPoint point );

WM_LBUTTONDOWN : The framework calls this member function when the user presses the left mouse button.
afx_msg void OnLButtonDown(

UINT nFlags, CPoint point );

Parameters nFlags Indicates whether various virtual keys are down. This parameter can be any combination of the following values:

MK_CONTROL Set if the CTRL key is down. MK_LBUTTON Set if the left mouse button is down. MK_MBUTTON Set if the middle mouse button is down. MK_RBUTTON Set if the right mouse button is down. MK_SHIFT Set if the SHIFT key is down.

point Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window. Mt s hm ca lp CWnd: Hm Invalidate(): Invalidates the entire client area of CWnd.
void Invalidate( BOOL bErase = TRUE );

Hm ca lp CView: Hm GetDocument(): Call this function to get a pointer to the view's document.
CDocument* GetDocument( ) const;

4) Saving and Loading Data


a) To mt i tng d liu Serialization B1: To mt lp d liu c dn xut t lp CObject B2: Trong File c phn m rng .h ca lp ta khai bo c s dng h tr Serialization.
DECLARE_SERIAL(class_name )

Parameter class_name The actual name of the class. B3: Trong File c phn m rng .cpp ca lp ta khai bo phn hin thc ca Serialization.
IMPLEMENT_SERIAL(class_name, base_class_name, wSchema )

Parameters class_name

The actual name of the class. base_class_name The name of the base class. wSchema A UINT "version number" that will be encoded in the archive to enable a deserializing program to identify and handle data created by earlier program versions. The class schema number must not be 1. b) Khai bo d liu trong Document Khai bo i tng thuc lp CObArray trong lp Document cha mt danh sch d liu. c) Serializing i tng d liu Trong File c phn m rng .cpp ca lp ta Add vo phng thc Serialize(CArchive& ar) v vit cc cu lnh dung Save v Load d liu. Trong file c phn m rng .cpp ca lp Document ta Add vo phng thc Serialize(CArchive& ar) v trong phng thc ny ta dng phng thc Serialize() ca lp CObArray Save v Load d liu. Lp CArchive: Remarks CArchive does not have a base class. The CArchive class allows you to save a complex network of objects in a permanent binary form (usually disk storage) that persists after those objects are deleted. Later you can load the objects from persistent storage, reconstituting them in memory. This process of making data persistent is called "serialization." You can think of an archive object as a kind of binary stream. Like an input/output stream, an archive is associated with a file and permits the buffered writing and reading of data to and from storage. An input/output stream processes sequences of ASCII characters, but an archive processes binary object data in an efficient, nonredundant format. You must create a CFile object before you can create a CArchive object. In addition, you must ensure that the archive's load/store status is compatible with the file's open mode. You are limited to one active archive per file. When you construct a CArchive object, you attach it to an object of class CFile (or a derived class) that represents an open file. You also specify whether the archive will be used for loading or storing. A CArchive object can process not only primitive types but also objects of CObject-derived classes designed for serialization. A serializable class usually has a Serialize member function, and it usually uses the DECLARE_SERIAL and IMPLEMENT_SERIAL macros, as described under class CObject.

The overloaded extraction (>>) and insertion (<<) operators are convenient archive programming interfaces that support both primitive types and CObject-derived classes. CArchive also supports programming with the MFC Windows Sockets classes CSocket and CSocketFile. The IsBufferEmpty member function supports that usage. For more information on CArchive, see the articles Serialization and Windows Sockets: Using Sockets with Archives. Requirements Header: afx.h Hm to CArchive: Constructs a CArchive object and specifies whether it will be used for loading or storing objects.
CArchive( CFile* pFile, UINT nMode, int nBufSize = 4096, void* lpBuf = NULL );

Parameters pFile A pointer to the CFile object that is the ultimate source or destination of the persistent data. nMode A flag that specifies whether objects will be loaded from or stored to the archive. The nMode parameter must have one of the following values:

CArchive::load Loads data from the archive. Requires only CFile read permission. CArchive::store Saves data to the archive. Requires CFile write permission. CArchive::bNoFlushOnDelete Prevents the archive from automatically calling Flush when the archive destructor is called. If you set this flag, you are responsible for explicitly calling Close before the destructor is called. If you do not, your data will be corrupted.

nBufSize An integer that specifies the size of the internal file buffer, in bytes. Note that the default buffer size is 4,096 bytes. If you routinely archive large objects, you will improve performance if you use a larger buffer size that is a multiple of the file buffer size. lpBuf An optional pointer to a user-supplied buffer of size nBufSize. If you do not specify this parameter, the archive allocates a buffer from the local heap and frees it when the object is destroyed. The archive does not free a user-supplied buffer.

Phng thc Close(): Flushes any data remaining in the buffer, closes the archive, and disconnects the archive from the file.
void Close( );

V d: To ng dng sau:

Mt s hm ca lp CDocument: Hm OnNewDocument(): Called by the framework as part of the File New command.
virtual BOOL OnNewDocument( );

Hm OnOpenDocument(): Called by the framework as part of the File Open command.


virtual BOOL OnOpenDocument( LPCTSTR lpszPathName );

Parameters lpszPathName Points to the path of the document to be opened. Hm OnSaveDocument(): Called by the framework as part of the File Save or File Save As command.

virtual BOOL OnSaveDocument( LPCTSTR lpszPathName );

Parameters lpszPathName Points to the fully qualified path to which the file should be saved.

5) ToolBars
Thm 1 Button vo ToolBar: To ToolBar: B1: To ToolBar t ResourceView B2: Khai bo mt i tng thuc lp CToolBar B3: Dng hm Create() ca lp CToolBar to ca s ToolBar v gn kt thanh ToolBar vi i tng B4: Dng hm LoadToolBar() ca lp CToolBar load thanh ToolBar. n v hin ToolBar: dng hm ShowControlBar() ca lp CFrameWnd
void ShowControlBar( CControlBar* pBar, BOOL bShow, BOOL bDelay );

6) Pens
Lp CPen: Hm to CPen(): Constructs a CPen object.
CPen( ); CPen( int nPenStyle, int nWidth, COLORREF crColor ); CPen( int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL );

nPenStyle Specifies the pen style. This parameter in the first version of the constructor can be one of the following values: PS_SOLID Creates a solid pen. PS_DASH Creates a dashed pen. Valid only when the pen width is 1 or less, in device units.

PS_DOT Creates a dotted pen. Valid only when the pen width is 1 or less, in device units. PS_DASHDOT Creates a pen with alternating dashes and dots. Valid only when the pen width is 1 or less, in device units. PS_DASHDOTDOT Creates a pen with alternating dashes and double dots. Valid only when the pen width is 1 or less, in device units. PS_NULL Creates a null pen. Hm CreatePen(): Creates a logical cosmetic or geometric pen with the specified style, width, and brush attributes, and attaches it to the CPen object.
BOOL CreatePen( int nPenStyle, int nWidth, COLORREF crColor ); BOOL CreatePen( int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL );

Lp CDC: Hm SelectObject(): Selects an object into the device context.


CPen* SelectObject( CPen* pPen ); CBrush* SelectObject( CBrush* pBrush ); virtual CFont* SelectObject( CFont* pFont ); CBitmap* SelectObject( CBitmap* pBitmap ); int SelectObject( CRgn* pRgn ); CGdiObject* SelectObject( CGdiObject* pObject );

Lp CGdiObject: Hm DeleteObject(): Deletes the attached Windows GDI object from memory by freeing all system storage associated with the Windows GDI object.
BOOL DeleteObject( );

Hm CreateStockObject(): Retrieves a handle to one of the predefined stock Windows GDI pens, brushes, or fonts, and attaches the GDI object to the CGdiObject object.
BOOL CreateStockObject( int nIndex ); nIndex: Specifies the type of stock object. This parameter can be one of the following values.

BLACK_PEN DC_PEN

WHITE_PEN

Black pen. Windows 2000/XP: Solid pen color. The default color is white. The color can be changed by using the SetDCPenColor function. For more information, see the Remarks section. White pen.

Lp CColorDialog: Hm to: Constructs a CColorDialog object.


CColorDialog( COLORREF clrInit = 0, DWORD dwFlags = 0, CWnd* pParentWnd = NULL );

Hm DoModal(): Call this function to display the Windows common color dialog box and allow the user to select a color.
virtual INT_PTR DoModal( );

Hm GetColor(): Call this function after calling DoModal to retrieve the information about the color the user selected.
COLORREF GetColor( ) const;

V d: To ng dng sau

Lp CWnd: Hm GetClientRect(): Copies the client coordinates of the CWnd client area into the structure pointed to by lpRect.
void GetClientRect( LPRECT lpRect ) const;

7) Brushes:
Lp CBrush: Hm to: Constructs a CBrush object.
CBrush( ); CBrush( COLORREF crColor ); CBrush( int nIndex, COLORREF crColor ); explicit CBrush( CBitmap* pBitmap );

Parameters crColor Specifies the foreground color of the brush as an RGB color. If the brush is hatched, this parameter specifies the color of the hatching. nIndex Specifies the hatch style of the brush. It can be any one of the following values: HS_BDIAGONAL Downward hatch (left to right) at 45 degrees HS_CROSS Horizontal and vertical crosshatch HS_DIAGCROSS Crosshatch at 45 degrees HS_FDIAGONAL Upward hatch (left to right) at 45 degrees HS_HORIZONTAL Horizontal hatch HS_VERTICAL Vertical hatch pBitmap

Points to a CBitmap object that specifies a bitmap with which the brush paints. Hm CreateSolidBrush(): Initializes a brush with a specified solid color.
BOOL CreateSolidBrush( COLORREF crColor );

Hm CreateHatchBrush(): Initializes a brush with the specified hatched pattern and color.
BOOL CreateHatchBrush( int nIndex, COLORREF crColor );

Hm CreatePatternBrush(): Initializes a brush with a pattern specified by a bitmap.


BOOL CreatePatternBrush( CBitmap* pBitmap );

Hm CreateBrushIndirect(): Initializes a brush with a style, color, and pattern specified in a LOGBRUSH structure.
BOOL CreateBrushIndirect( const LOGBRUSH* lpLogBrush );

Parameters lpLogBrush Points to a LOGBRUSH structure that contains information about the brush. Lp CDC: Hm SelectObject(): Selects an object into the device context.
CBrush* SelectObject( CBrush* pBrush );

Hm FillRect(): Call this member function to fill a given rectangle using the specified brush.
void FillRect( LPCRECT lpRect, CBrush* pBrush );

Lp CGdiObject:

Hm DeleteObject(): Deletes the attached Windows GDI object from memory by freeing all system storage associated with the Windows GDI object. BOOL DeleteObject( ); Lp CWnd: Hm OnEraseBkgnd() ca thng ip WM_ERASEBKGND : The framework calls this member function when the CWnd object background needs erasing (for example, when resized).
afx_msg BOOL OnEraseBkgnd( CDC* pDC );

Hm OnCtlColor() ca thng ip WM_CTLCOLOR: The framework calls this member function when a child control is about to be drawn.
afx_msg HBRUSH OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor );

Parameters pDC Contains a pointer to the display context for the child window. May be temporary. pWnd Contains a pointer to the control asking for the color. May be temporary. nCtlColor Contains one of the following values, specifying the type of control: CTLCOLOR_BTN Button control CTLCOLOR_DLG Dialog box CTLCOLOR_EDIT Edit control CTLCOLOR_LISTBOX List-box control CTLCOLOR_MSGBOX Message box CTLCOLOR_SCROLLBAR Scroll-bar control CTLCOLOR_STATIC Static control Hm GetClientRect(): Copies the client coordinates of the CWnd client area into the structure pointed to by lpRect.
void GetClientRect( LPRECT lpRect ) const;

V d: to ng dng sau

8) Fonts:
Lp CFont: Hm to: Constructs a CFont object.
CFont( );

Hm CreatePointFont(): This function provides a simple way to create a font of a specified typeface and point size.
BOOL CreatePointFont( int nPointSize, LPCTSTR lpszFaceName, CDC* pDC = NULL );

Parameters nPointSize Requested font height in tenths of a point. (For instance, pass 120 to request a 12-point font.) lpszFaceName A CString or pointer to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 30 characters. The Windows EnumFontFamilies function can be used to enumerate all currently available fonts. If lpszFaceName is NULL, the GDI uses a device-independent typeface. pDC Pointer to the CDC object to be used to convert the height in nPointSize to logical units. If NULL, a screen device context is used for the conversion. Hm CreateFontIndirect(): Initializes a CFont object with the characteristics given in a LOGFONT structure pointed to by lpLogFont.

BOOL CreateFontIndirect( const LOGFONT* lpLogFont );

Parameters lpLogFont Points to a LOGFONT structure that defines the characteristics of the logical font The LOGFONT structure defines the attributes of a font.
typedef struct tagLOGFONT { LONG lfHeight; LONG lfWidth; LONG lfEscapement; LONG lfOrientation; LONG lfWeight; BYTE lfItalic; BYTE lfUnderline; BYTE lfStrikeOut; BYTE lfCharSet; BYTE lfOutPrecision; BYTE lfClipPrecision; BYTE lfQuality; BYTE lfPitchAndFamily; TCHAR lfFaceName[LF_FACESIZE]; } LOGFONT, *PLOGFONT;

Hm CreateFont(): Initializes a CFont object with the specified characteristics.


BOOL CreateFont( int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename );

Hm GetLogFont(): Call this function to retrieve a copy of the LOGFONT structure for CFont.
int GetLogFont( LOGFONT * pLogFont );

Lp CDC:

Hm SetTextAlign(): Sets the text-alignment flags.


UINT SetTextAlign( UINT nFlags );

Parameters nFlags Specifies text-alignment flags. The flags specify the relationship between a point and a rectangle that bounds the text. The point can be either the current position or coordinates specified by a text-output function. The rectangle that bounds the text is defined by the adjacent character cells in the text string. The nFlags parameter can be one or more flags from the following three categories. Choose only one flag from each category. The first category affects text alignment in the x-direction: TA_CENTER Aligns the point with the horizontal center of the bounding rectangle. TA_LEFT Aligns the point with the left side of the bounding rectangle. This is the default setting. TA_RIGHT Aligns the point with the right side of the bounding rectangle. The second category affects text alignment in the y-direction: TA_BASELINE Aligns the point with the base line of the chosen font. TA_BOTTOM Aligns the point with the bottom of the bounding rectangle. TA_TOP Aligns the point with the top of the bounding rectangle. This is the default setting. The third category determines whether the current position is updated when text is written: TA_NOUPDATECP Does not update the current position after each call to a text-output function. This is the default setting. TA_UPDATECP Updates the current x-position after each call to a text-output function. The new position is at the right side of the bounding rectangle for the text. When this flag is set, the coordinates specified in calls to the TextOut member function are ignored. Hm TextOut(): Writes a character string at the specified location using the currently selected font.
virtual BOOL TextOut( int x, int y, LPCTSTR lpszString, int nCount ); BOOL TextOut(

int x, int y, const CString& str );

Hm DrawText(): Call this member function to format text in the given rectangle. To specify additional formatting options, use CDC::DrawTextEx.
virtual int DrawText( LPCTSTR lpszString, int nCount, LPRECT lpRect, UINT nFormat ); int DrawText( const CString& str, LPRECT lpRect, UINT nFormat );

uFormat [in] Specifies the method of formatting the text. This parameter can be one or more of the following values. Hm SetTextColor(): Sets the text color to the specified color.
virtual COLORREF SetTextColor( COLORREF crColor );

Hm SetBkColor(): Sets the current background color to the specified color.


virtual COLORREF SetBkColor( COLORREF crColor );

Hm SetBkMode(): Sets the background mode.


int SetBkMode( int nBkMode );

Parameters nBkMode Specifies the mode to be set. This parameter can be either of the following values: OPAQUE Background is filled with the current background color before the text, hatched brush, or pen is drawn. This is the default background mode. TRANSPARENT Background is not changed before drawing. Lp CFontDialog:

Hm to: Constructs a CFontDialog object.


CFontDialog( LPLOGFONT lplfInitial = NULL, DWORD dwFlags = CF_EFFECTS | CF_SCREENFONTS, CDC* pdcPrinter = NULL, CWnd* pParentWnd = NULL ); CFontDialog( const CHARFORMAT& charformat, DWORD dwFlags = CF_SCREENFONTS, CDC* pdcPrinter = NULL, CWnd* pParentWnd = NULL );

Hm DoModal(): Call this function to display the Windows common font dialog box and allow the user to choose a font.
virtual INT_PTR DoModal( );

Hm GetCurrentFont(): Call this function to assign the characteristics of the currently selected font to the members of a LOGFONT structure.
void GetCurrentFont( LPLOGFONT lplf );

Hm GetFaceName(): Call this function to retrieve the face name of the selected font.
CString GetFaceName( ) const;

Hm GetSize(): Call this function to retrieve the size of the selected font.
int GetSize( ) const;

Call this function to retrieve the selected font color.


COLORREF GetColor( ) const;

Lp CDC: Hm GetTextMetrics(): Retrieves the metrics for the current font using the attribute device context.
BOOL GetTextMetrics( LPTEXTMETRIC lpMetrics ) const;

The TEXTMETRIC structure contains basic information about a physical font. All sizes are specified in logical units; that is, they depend on the current mapping mode of the display context.
typedef struct tagTEXTMETRIC { LONG tmHeight;

LONG tmAscent; LONG tmDescent; LONG tmInternalLeading; LONG tmExternalLeading; LONG tmAveCharWidth; LONG tmMaxCharWidth; LONG tmWeight; LONG tmOverhang; LONG tmDigitizedAspectX; LONG tmDigitizedAspectY; TCHAR tmFirstChar; TCHAR tmLastChar; TCHAR tmDefaultChar; TCHAR tmBreakChar; BYTE tmItalic; BYTE tmUnderlined; BYTE tmStruckOut; BYTE tmPitchAndFamily; BYTE tmCharSet; } TEXTMETRIC, *PTEXTMETRIC;

V d: to ng dng sau

9) Scrolling Windows
To mt ng dng dng Single Document bng AppWizard. Trong bc to th 6 (step 6 of 6) ta chn lp c s ca lp View l lp CScrollView.

10) Xc nh v tr v kch thc ca ca s


Lp CWnd: Hm GetClientRect(): Copies the client coordinates of the CWnd client area into the structure pointed to by lpRect.
void GetClientRect( LPRECT lpRect ) const;

Hm GetWindowPlacement(): Retrieves the show state and the normal (restored), minimized, and maximized positions of a window.
BOOL GetWindowPlacement( WINDOWPLACEMENT* lpwndpl ) const;

Parameters lpwndpl Points to the WINDOWPLACEMENT structure that receives the show state and position information. The WINDOWPLACEMENT structure contains information about the placement of a window on the screen.
typedef struct tagWINDOWPLACEMENT { UINT length; UINT flags; UINT showCmd; POINT ptMinPosition; POINT ptMaxPosition; RECT rcNormalPosition; } WINDOWPLACEMENT; /* wndpl */

Hm MoveWindow(): Changes the position and dimensions.


void MoveWindow( int x, int y, int nWidth, int nHeight, BOOL bRepaint = TRUE ); void MoveWindow( LPCRECT lpRect, BOOL bRepaint = TRUE );

Das könnte Ihnen auch gefallen