LoadBitmap(const char FAR *)与LoadBitmap(UINT)的区别

lumg 2000-09-13 11:46:00
本人欲设置一对话框的背景图案,采用如下方式:
CBitmap cBitmap;
CBrush m_brush;
cBitmap.LoadBitmap(lpString);
m_brush.CreatePatternBrush(&cBitmap);
...
结果是对话框除各个控件外是透明的,我又尝试cBitmap.LoadBitmap(UINT)形式,结果运行成功可以显示。 难道这两个重载函数对CBitmap会产生不同效果吗?但是采用前一种又如何显示背景呢?
...全文
473 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Wingsun 2000-09-13
  • 打赏
  • 举报
回复
LoadBimap(UNIT)是从资源中加载位图。LoadBitmap(const char Far * )是从一个位图文件中加载。使用LoadBitmap(Unit)你必须在你的资源中加入一个位图,参数是该位图资源的ID
lumg_2000 2000-09-13
  • 打赏
  • 举报
回复
areslee,你误解了LoadBitmap(),有2种形式,一种可以装载bmp文件,一种可以装载资源中的位图。但它们之间的区别呢,为何一个能显示一个不能?
Areslee 2000-09-13
  • 打赏
  • 举报
回复
LoadBitmap(lpString);应该是用来读BMP文件,而不是资源中的位图。
lumg 2000-09-13
  • 打赏
  • 举报
回复
谢谢Holly,谢谢各位,我终于成功了。
Holly 2000-09-13
  • 打赏
  • 举报
回复
cBitmap.LoadBitmap(cBitmap.Attach((HBITMAP)LoadImage(...))) ???!!!
不用这样调用,你用
cBitmap.Attach((HBITMAP)LoadImage(...));
就已经把位图放到cBitmap中了,为何你还用LoadBitmap来处理Attach的返回值!?
lumg_2000 2000-09-13
  • 打赏
  • 举报
回复
楼上的各位网兄的热切关注,lumg表示万分的感谢。还得向各位指导一下,lumg按照上述要点上机操作了一下,果真可以实现Load Image in the dialog,但运行时仍有报错,系统提示Attach
有错。现将代码呈上:
CBitmap cBitmap;
char lpString[256];
cBitmap.LoadBitmap(cBitmap.Attach((HBITMAP)LoadImage(NULL,lpString,IMAGE_BITMAP,0,0,LR_LOADFROMFILE )));
不知哪个参数有误,请指示。
Holly 2000-09-13
  • 打赏
  • 举报
回复
总之只要是LoadBitmap函数就不可以读文件,不管类成员还是全局!
Holly 2000-09-13
  • 打赏
  • 举报
回复
to ad:
你怎么还没开窍!
::LoadBitmap()也是一样的!
::LoadImage()要读文件的话,需要将参数fuLoad设置LR_LOADFROMFILE标记!
programCat 2000-09-13
  • 打赏
  • 举报
回复
Holly说的对极了

LoadBitmap只能装资源,而不能读文件的。
要读文件话,要用LoadImage这个API函数。
得到HBITMAP句柄后,用Cbitmap类的Attach.
ad 2000-09-13
  • 打赏
  • 举报
回复
真实的情况是这样的,CBitmap的LoadBitmap函数的两种形式都是针对资源的,一个资源可以用字符串名字标志,也可以用整数ID表示,比如你可以定义位图的ID为IDB_BITMAP1,也可以定义位图的名称为"BITMAP1", 效果一样,只是对于不同的定义法要用LoadBitmap的不同形式。全局函数LoadBitmap的参数才是指文件名.
Holly 2000-09-13
  • 打赏
  • 举报
回复
大错特错!
LoadBitmap的参数不论那种类型都是针对资源而言,CBitmap是不提供直接从文件中读取位图的功能的!
使用的形式无非是:
cBitmap.LoadBitmap(IDB_MYBMP);
cBitmap.LoadBitmap(MAKEINTRESOURCE(IDB_MYBMP));
两种的效果一样,都是对资源而言!
所谓的LPCTSTR和UINT类型参数,只是类型强制转换达到的!请看:
#define MAKEINTRESOURCEA(i) (LPSTR)((DWORD)((WORD)(i)))
#define MAKEINTRESOURCEW(i) (LPWSTR)((DWORD)((WORD)(i)))

#ifdef UNICODE
#define MAKEINTRESOURCE MAKEINTRESOURCEW
#else
#define MAKEINTRESOURCE MAKEINTRESOURCEA
#endif // !UNICODE
也许MS为了以后的资源可以变为32位,才提供的LPCTSTR类型的转换!
onion 2000-09-13
  • 打赏
  • 举报
回复
效果是一样的,一定是该函数根据文件名却找不到该文件。路径对否?
stdafx.h的代码// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1998 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #ifndef __AFXWIN_H__ #ifndef RC_INVOKED #define __AFXWIN_H__ ///////////////////////////////////////////////////////////////////////////// // Make sure 'afx.h' is included first #ifndef __AFX_H__ #include #endif // Note: WINDOWS.H already included from AFXV_W32.H #ifndef _INC_SHELLAPI #include #endif #ifndef __AFXRES_H__ #include // standard resource IDs #endif #ifndef __AFXCOLL_H__ #include // standard collections #endif #ifdef _AFX_MINREBUILD #pragma component(minrebuild, off) #endif #ifndef _AFX_FULLTYPEINFO #pragma component(mintypeinfo, on) #endif #ifndef _AFX_NOFORCE_LIBS #pragma comment(lib, "uuid.lib") #endif #ifdef _INC_WINDOWSX // The following names from WINDOWSX.H collide with names in this header #undef SubclassWindow #undef CopyRgn #endif #ifdef _AFX_PACKING #pragma pack(push, _AFX_PACKING) #endif ///////////////////////////////////////////////////////////////////////////// // Classes declared in this file class CSize; class CPoint; class CRect; //CObject //CException //CSimpleException class CResourceException;// Win resource failure exception class CUserException; // Message Box alert and stop operation class CGdiObject; // CDC drawing tool class CPen; // a pen / HPEN wrapper class CBrush; // a brush / HBRUSH wrapper class CFont; // a font / HFONT wrapper class CBitmap; // a bitmap / HBITMAP wrapper class CPalette; // a palette / HPALLETE wrapper class CRgn; // a region / HRGN wrapper class CDC; // a Display Context / HDC wrapper class CClientDC; // CDC for client of window class CWindowDC; // CDC for entire window class CPaintDC; // embeddable BeginPaint struct helper class CMenu; // a menu / HMENU wrapper class CCmdTarget; // a target for user commands class CWnd; // a window / HWND wrapper class CDialog; // a dialog // standard windows controls class CStatic; // Static control class CButton; // Button control class CListBox; // ListBox control class CCheckListBox;// special listbox with checks class CComboBox; // ComboBox control class CEdit; // Edit control class CScrollBar; // ScrollBar control // frame windows class CFrameWnd; // standard SDI frame class CMDIFrameWnd; // standard MDI frame class CMDIChildWnd; // standard MDI child class CMiniFrameWnd;// half-height caption frame wnd // views on a document class CView; // a view on a document class CScrollView; // a scrolling view class CWinThread; // thread base class class CWinApp; // application base class class CDocTemplate; // template for document creation class CSingleDocTemplate;// SDI support class CMultiDocTemplate; // MDI support class CDocument; // main document abstraction // Helper classes class CCmdUI; // Menu/button enabling class CDataExchange; // Data exchange and validation context class CCommandLineInfo; // CommandLine parsing helper class CDocManager; // CDocTemplate manager object ///////////////////////////////////////////////////////////////////////////// // Type modifier for message handlers #ifndef afx_msg #define afx_msg // intentional placeholder #endif #undef AFX_DATA #define AFX_DATA AFX_CORE_DATA ///////////////////////////////////////////////////////////////////////////// // CSize - An extent, similar to Windows SIZE structure. class CSize : public tagSIZE { public: // Constructors // construct an uninitialized size CSize(); // create from two integers CSize(int initCX, int initCY); // create from another size CSize(SIZE initSize); // create from a point CSize(POINT initPt); // create from a DWORD: cx = LOWORD(dw) cy = HIWORD(dw) CSize(DWORD dwSize); // Operations BOOL operator==(SIZE size) const; BOOL operator!=(SIZE size) const; void operator+=(SIZE size); void operator-=(SIZE size); // Operators returning CSize values CSize operator+(SIZE size) const; CSize operator-(SIZE size) const; CSize operator-() const; // Operators returning CPoint values CPoint operator+(POINT point) const; CPoint operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CPoint - A 2-D point, similar to Windows POINT structure. class CPoint : public tagPOINT { public: // Constructors // create an uninitialized point CPoint(); // create from two integers CPoint(int initX, int initY); // create from another point CPoint(POINT initPt); // create from a size CPoint(SIZE initSize); // create from a dword: x = LOWORD(dw) y = HIWORD(dw) CPoint(DWORD dwPoint); // Operations // translate the point void Offset(int xOffset, int yOffset); void Offset(POINT point); void Offset(SIZE size); BOOL operator==(POINT point) const; BOOL operator!=(POINT point) const; void operator+=(SIZE size); void operator-=(SIZE size); void operator+=(POINT point); void operator-=(POINT point); // Operators returning CPoint values CPoint operator+(SIZE size) const; CPoint operator-(SIZE size) const; CPoint operator-() const; CPoint operator+(POINT point) const; // Operators returning CSize values CSize operator-(POINT point) const; // Operators returning CRect values CRect operator+(const RECT* lpRect) const; CRect operator-(const RECT* lpRect) const; }; ///////////////////////////////////////////////////////////////////////////// // CRect - A 2-D rectangle, similar to Windows RECT structure. typedef const RECT* LPCRECT; // pointer to read/only RECT class CRect : public tagRECT { public: // Constructors // uninitialized rectangle CRect(); // from left, top, right, and bottom CRect(int l, int t, int r, int b); // copy constructor CRect(const RECT& srcRect); // from a pointer to another rect CRect(LPCRECT lpSrcRect); // from a point and size CRect(POINT point, SIZE size); // from two points CRect(POINT topLeft, POINT bottomRight); // Attributes (in addition to RECT members) // retrieves the width int Width() const; // returns the height int Height() const; // returns the size CSize Size() const; // reference to the top-left point CPoint& TopLeft(); // reference to the bottom-right point CPoint& BottomRight(); // const reference to the top-left point const CPoint& TopLeft() const; // const reference to the bottom-right point const CPoint& BottomRight() const; // the geometric center point of the rectangle CPoint CenterPoint() const; // swap the left and right void SwapLeftRight(); static void SwapLeftRight(LPRECT lpRect); // convert between CRect and LPRECT/LPCRECT (no need for &) operator LPRECT(); operator LPCRECT() const; // returns TRUE if rectangle has no area BOOL IsRectEmpty() const; // returns TRUE if rectangle is at (0,0) and has no area BOOL IsRectNull() const; // returns TRUE if point is within rectangle BOOL PtInRect(POINT point) const; // Operations // set rectangle from left, top, right, and bottom void SetRect(int x1, int y1, int x2, int y2); void SetRect(POINT topLeft, POINT bottomRight); // empty the rectangle void SetRectEmpty(); // copy from another rectangle void CopyRect(LPCRECT lpSrcRect); // TRUE if exactly the same as another rectangle BOOL EqualRect(LPCRECT lpRect) const; // inflate rectangle's width and height without // moving its top or left void InflateRect(int x, int y); void InflateRect(SIZE size); void InflateRect(LPCRECT lpRect); void InflateRect(int l, int t, int r, int b); // deflate the rectangle's width and height without // moving its top or left void DeflateRect(int x, int y); void DeflateRect(SIZE size); void DeflateRect(LPCRECT lpRect); void DeflateRect(int l, int t, int r, int b); // translate the rectangle by moving its top and left void OffsetRect(int x, int y); void OffsetRect(SIZE size); void OffsetRect(POINT point); void NormalizeRect(); // set this rectangle to intersection of two others BOOL IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2); // set this rectangle to bounding union of two others BOOL UnionRect(LPCRECT lpRect1, LPCRECT lpRect2); // set this rectangle to minimum of two others BOOL SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2); // Additional Operations void operator=(const RECT& srcRect); BOOL operator==(const RECT& rect) const; BOOL operator!=(const RECT& rect) const; void operator+=(POINT point); void operator+=(SIZE size); void operator+=(LPCRECT lpRect); void operator-=(POINT point); void operator-=(SIZE size); void operator-=(LPCRECT lpRect); void operator&=(const RECT& rect); void operator|=(const RECT& rect); // Operators returning CRect values CRect operator+(POINT point) const; CRect operator-(POINT point) const; CRect operator+(LPCRECT lpRect) const; CRect operator+(SIZE size) const; CRect operator-(SIZE size) const; CRect operator-(LPCRECT lpRect) const; CRect operator&(const RECT& rect2) const; CRect operator|(const RECT& rect2) const; CRect MulDiv(int nMultiplier, int nDivisor) const; }; #ifdef _DEBUG // Diagnostic Output CDumpContext& AFXAPI operator<<(CDumpContext& dc, SIZE size); CDumpContext& AFXAPI operator<<(CDumpContext& dc, POINT point); CDumpContext& AFXAPI operator<<(CDumpContext& dc, const RECT& rect); #endif //_DEBUG // Serialization CArchive& AFXAPI operator<<(CArchive& ar, SIZE size); CArchive& AFXAPI operator<<(CArchive& ar, POINT point); CArchive& AFXAPI operator<>(CArchive& ar, SIZE& size); CArchive& AFXAPI operator>>(CArchive& ar, POINT& point); CArchive& AFXAPI operator>>(CArchive& ar, RECT& rect); ///////////////////////////////////////////////////////////////////////////// // Standard exceptions class CResourceException : public CSimpleException // resource failure { DECLARE_DYNAMIC(CResourceException) public: CResourceException(); // Implementation public: CResourceException(BOOL bAutoDelete); CResourceException(BOOL bAutoDelete, UINT nResourceID); virtual ~CResourceException(); }; class CUserException : public CSimpleException // general user visible alert { DECLARE_DYNAMIC(CUserException) public: CUserException(); // Implementation public: CUserException(BOOL bAutoDelete); CUserException(BOOL bAutoDelete, UINT nResourceID); virtual ~CUserException(); }; void AFXAPI AfxThrowResourceException(); void AFXAPI AfxThrowUserException(); ///////////////////////////////////////////////////////////////////////////// // CGdiObject abstract class for CDC SelectObject class CGdiObject : public CObject { DECLARE_DYNCREATE(CGdiObject) public: // Attributes HGDIOBJ m_hObject; // must be first data member operator HGDIOBJ() const; HGDIOBJ GetSafeHandle() const; static CGdiObject* PASCAL FromHandle(HGDIOBJ hObject); static void PASCAL DeleteTempMap(); BOOL Attach(HGDIOBJ hObject); HGDIOBJ Detach(); // Constructors CGdiObject(); // must Create a derived class object BOOL DeleteObject(); // Operations int GetObject(int nCount, LPVOID lpObject) const; UINT GetObjectType() const; BOOL CreateStockObject(int nIndex); BOOL UnrealizeObject(); BOOL operator==(const CGdiObject& obj) const; BOOL operator!=(const CGdiObject& obj) const; // Implementation public: virtual ~CGdiObject(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; virtual void AssertValid() const; #endif }; ///////////////////////////////////////////////////////////////////////////// // CGdiObject subclasses (drawing tools) class CPen : public CGdiObject { DECLARE_DYNAMIC(CPen) public: static CPen* PASCAL FromHandle(HPEN hPen); // Constructors CPen(); CPen(int nPenStyle, int nWidth, COLORREF crColor); CPen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL); BOOL CreatePen(int nPenStyle, int nWidth, COLORREF crColor); BOOL CreatePen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL); BOOL CreatePenIndirect(LPLOGPEN lpLogPen); // Attributes operator HPEN() const; int GetLogPen(LOGPEN* pLogPen); int GetExtLogPen(EXTLOGPEN* pLogPen); // Implementation public: virtual ~CPen(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CBrush : public CGdiObject { DECLARE_DYNAMIC(CBrush) public: static CBrush* PASCAL FromHandle(HBRUSH hBrush); // Constructors CBrush(); CBrush(COLORREF crColor); // CreateSolidBrush CBrush(int nIndex, COLORREF crColor); // CreateHatchBrush CBrush(CBitmap* pBitmap); // CreatePatternBrush BOOL CreateSolidBrush(COLORREF crColor); BOOL CreateHatchBrush(int nIndex, COLORREF crColor); BOOL CreateBrushIndirect(const LOGBRUSH* lpLogBrush); BOOL CreatePatternBrush(CBitmap* pBitmap); BOOL CreateDIBPatternBrush(HGLOBAL hPackedDIB, UINT nUsage); BOOL CreateDIBPatternBrush(const void* lpPackedDIB, UINT nUsage); BOOL CreateSysColorBrush(int nIndex); // Attributes operator HBRUSH() const; int GetLogBrush(LOGBRUSH* pLogBrush); // Implementation public: virtual ~CBrush(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CFont : public CGdiObject { DECLARE_DYNAMIC(CFont) public: static CFont* PASCAL FromHandle(HFONT hFont); // Constructors CFont(); BOOL CreateFontIndirect(const LOGFONT* lpLogFont); 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); BOOL CreatePointFont(int nPointSize, LPCTSTR lpszFaceName, CDC* pDC = NULL); BOOL CreatePointFontIndirect(const LOGFONT* lpLogFont, CDC* pDC = NULL); // Attributes operator HFONT() const; int GetLogFont(LOGFONT* pLogFont); // Implementation public: virtual ~CFont(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CBitmap : public CGdiObject { DECLARE_DYNAMIC(CBitmap) public: static CBitmap* PASCAL FromHandle(HBITMAP hBitmap); // Constructors CBitmap(); BOOL LoadBitmap(LPCTSTR lpszResourceName); BOOL LoadBitmap(UINT nIDResource); BOOL LoadOEMBitmap(UINT nIDBitmap); // for OBM_/OCR_/OIC_ BOOL LoadMappedBitmap(UINT nIDBitmap, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0); BOOL CreateBitmap(int nWidth, int nHeight, UINT nPlanes, UINT nBitcount, const void* lpBits); BOOL CreateBitmapIndirect(LPBITMAP lpBitmap); BOOL CreateCompatibleBitmap(CDC* pDC, int nWidth, int nHeight); BOOL CreateDiscardableBitmap(CDC* pDC, int nWidth, int nHeight); // Attributes operator HBITMAP() const; int GetBitmap(BITMAP* pBitMap); // Operations DWORD SetBitmapBits(DWORD dwCount, const void* lpBits); DWORD GetBitmapBits(DWORD dwCount, LPVOID lpBits) const; CSize SetBitmapDimension(int nWidth, int nHeight); CSize GetBitmapDimension() const; // Implementation public: virtual ~CBitmap(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; #endif }; class CPalette : public CGdiObject { DECLARE_DYNAMIC(CPalette) public: static CPalette* PASCAL FromHandle(HPALETTE hPalette); // Constructors CPalette(); BOOL CreatePalette(LPLOGPALETTE lpLogPalette); BOOL CreateHalftonePalette(CDC* pDC); // Attributes operator HPALETTE() const; int GetEntryCount(); UINT GetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors) const; UINT SetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors); // Operations void AnimatePalette(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors); UINT GetNearestPaletteIndex(COLORREF crColor) const; BOOL ResizePalette(UINT nNumEntries); // Implementation virtual ~CPalette(); }; class CRgn : public CGdiObject { DECLARE_DYNAMIC(CRgn) public: static CRgn* PASCAL FromHandle(HRGN hRgn); operator HRGN() const; // Constructors CRgn(); BOOL CreateRectRgn(int x1, int y1, int x2, int y2); BOOL CreateRectRgnIndirect(LPCRECT lpRect); BOOL CreateEllipticRgn(int x1, int y1, int x2, int y2); BOOL CreateEllipticRgnIndirect(LPCRECT lpRect); BOOL CreatePolygonRgn(LPPOINT lpPoints, int nCount, int nMode); BOOL CreatePolyPolygonRgn(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount, int nPolyFillMode); BOOL CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3); BOOL CreateFromPath(CDC* pDC); BOOL CreateFromData(const XFORM* lpXForm, int nCount, const RGNDATA* pRgnData); // Operations void SetRectRgn(int x1, int y1, int x2, int y2); void SetRectRgn(LPCRECT lpRect); int CombineRgn(CRgn* pRgn1, CRgn* pRgn2, int nCombineMode); int CopyRgn(CRgn* pRgnSrc); BOOL EqualRgn(CRgn* pRgn) const; int OffsetRgn(int x, int y); int OffsetRgn(POINT point); int GetRgnBox(LPRECT lpRect) const; BOOL PtInRegion(int x, int y) const; BOOL PtInRegion(POINT point) const; BOOL RectInRegion(LPCRECT lpRect) const; int GetRegionData(LPRGNDATA lpRgnData, int nCount) const; // Implementation virtual ~CRgn(); }; ///////////////////////////////////////////////////////////////////////////// // The device context class CDC : public CObject { DECLARE_DYNCREATE(CDC) public: // Attributes HDC m_hDC; // The output DC (must be first data member) HDC m_hAttribDC; // The Attribute DC operator HDC() const; HDC GetSafeHdc() const; // Always returns the Output DC CWnd* GetWindow() const; static CDC* PASCAL FromHandle(HDC hDC); static void PASCAL DeleteTempMap(); BOOL Attach(HDC hDC); // Attach/Detach affects only the Output DC HDC Detach(); virtual void SetAttribDC(HDC hDC); // Set the Attribute DC virtual void SetOutputDC(HDC hDC); // Set the Output DC virtual void ReleaseAttribDC(); // Release the Attribute DC virtual void ReleaseOutputDC(); // Release the Output DC BOOL IsPrinting() const; // TRUE if being used for printing CPen* GetCurrentPen() const; CBrush* GetCurrentBrush() const; CPalette* GetCurrentPalette() const; CFont* GetCurrentFont() const; CBitmap* GetCurrentBitmap() const; // for bidi and mirrored localization DWORD GetLayout() const; DWORD SetLayout(DWORD dwLayout); // Constructors CDC(); BOOL CreateDC(LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData); BOOL CreateIC(LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const void* lpInitData); BOOL CreateCompatibleDC(CDC* pDC); BOOL DeleteDC(); // Device-Context Functions virtual int SaveDC(); virtual BOOL RestoreDC(int nSavedDC); int GetDeviceCaps(int nIndex) const; UINT SetBoundsRect(LPCRECT lpRectBounds, UINT flags); UINT GetBoundsRect(LPRECT lpRectBounds, UINT flags); BOOL ResetDC(const DEVMODE* lpDevMode); // Drawing-Tool Functions CPoint GetBrushOrg() const; CPoint SetBrushOrg(int x, int y); CPoint SetBrushOrg(POINT point); int EnumObjects(int nObjectType, int (CALLBACK* lpfn)(LPVOID, LPARAM), LPARAM lpData); // Type-safe selection helpers public: virtual CGdiObject* SelectStockObject(int nIndex); CPen* SelectObject(CPen* pPen); CBrush* SelectObject(CBrush* pBrush); virtual CFont* SelectObject(CFont* pFont); CBitmap* SelectObject(CBitmap* pBitmap); int SelectObject(CRgn* pRgn); // special return for regions CGdiObject* SelectObject(CGdiObject* pObject); // CGdiObject* provided so compiler doesn't use SelectObject(HGDIOBJ) // Color and Color Palette Functions COLORREF GetNearestColor(COLORREF crColor) const; CPalette* SelectPalette(CPalette* pPalette, BOOL bForceBackground); UINT RealizePalette(); void UpdateColors(); // Drawing-Attribute Functions COLORREF GetBkColor() const; int GetBkMode() const; int GetPolyFillMode() const; int GetROP2() const; int GetStretchBltMode() const; COLORREF GetTextColor() const; virtual COLORREF SetBkColor(COLORREF crColor); int SetBkMode(int nBkMode); int SetPolyFillMode(int nPolyFillMode); int SetROP2(int nDrawMode); int SetStretchBltMode(int nStretchMode); virtual COLORREF SetTextColor(COLORREF crColor); BOOL GetColorAdjustment(LPCOLORADJUSTMENT lpColorAdjust) const; BOOL SetColorAdjustment(const COLORADJUSTMENT* lpColorAdjust); // Mapping Functions int GetMapMode() const; CPoint GetViewportOrg() const; virtual int SetMapMode(int nMapMode); // Viewport Origin virtual CPoint SetViewportOrg(int x, int y); CPoint SetViewportOrg(POINT point); virtual CPoint OffsetViewportOrg(int nWidth, int nHeight); // Viewport Extent CSize GetViewportExt() const; virtual CSize SetViewportExt(int cx, int cy); CSize SetViewportExt(SIZE size); virtual CSize ScaleViewportExt(int xNum, int xDenom, int yNum, int yDenom); // Window Origin CPoint GetWindowOrg() const; CPoint SetWindowOrg(int x, int y); CPoint SetWindowOrg(POINT point); CPoint OffsetWindowOrg(int nWidth, int nHeight); // Window extent CSize GetWindowExt() const; virtual CSize SetWindowExt(int cx, int cy); CSize SetWindowExt(SIZE size); virtual CSize ScaleWindowExt(int xNum, int xDenom, int yNum, int yDenom); // Coordinate Functions void DPtoLP(LPPOINT lpPoints, int nCount = 1) const; void DPtoLP(LPRECT lpRect) const; void DPtoLP(LPSIZE lpSize) const; void LPtoDP(LPPOINT lpPoints, int nCount = 1) const; void LPtoDP(LPRECT lpRect) const; void LPtoDP(LPSIZE lpSize) const; // Special Coordinate Functions (useful for dealing with metafiles and OLE) void DPtoHIMETRIC(LPSIZE lpSize) const; void LPtoHIMETRIC(LPSIZE lpSize) const; void HIMETRICtoDP(LPSIZE lpSize) const; void HIMETRICtoLP(LPSIZE lpSize) const; // Region Functions BOOL FillRgn(CRgn* pRgn, CBrush* pBrush); BOOL FrameRgn(CRgn* pRgn, CBrush* pBrush, int nWidth, int nHeight); BOOL InvertRgn(CRgn* pRgn); BOOL PaintRgn(CRgn* pRgn); // Clipping Functions virtual int GetClipBox(LPRECT lpRect) const; virtual BOOL PtVisible(int x, int y) const; BOOL PtVisible(POINT point) const; virtual BOOL RectVisible(LPCRECT lpRect) const; int SelectClipRgn(CRgn* pRgn); int ExcludeClipRect(int x1, int y1, int x2, int y2); int ExcludeClipRect(LPCRECT lpRect); int ExcludeUpdateRgn(CWnd* pWnd); int IntersectClipRect(int x1, int y1, int x2, int y2); int IntersectClipRect(LPCRECT lpRect); int OffsetClipRgn(int x, int y); int OffsetClipRgn(SIZE size); int SelectClipRgn(CRgn* pRgn, int nMode); // Line-Output Functions CPoint GetCurrentPosition() const; CPoint MoveTo(int x, int y); CPoint MoveTo(POINT point); BOOL LineTo(int x, int y); BOOL LineTo(POINT point); BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Arc(LPCRECT lpRect, POINT ptStart, POINT ptEnd); BOOL Polyline(LPPOINT lpPoints, int nCount); BOOL AngleArc(int x, int y, int nRadius, float fStartAngle, float fSweepAngle); BOOL ArcTo(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL ArcTo(LPCRECT lpRect, POINT ptStart, POINT ptEnd); int GetArcDirection() const; int SetArcDirection(int nArcDirection); BOOL PolyDraw(const POINT* lpPoints, const BYTE* lpTypes, int nCount); BOOL PolylineTo(const POINT* lpPoints, int nCount); BOOL PolyPolyline(const POINT* lpPoints, const DWORD* lpPolyPoints, int nCount); BOOL PolyBezier(const POINT* lpPoints, int nCount); BOOL PolyBezierTo(const POINT* lpPoints, int nCount); // Simple Drawing Functions void FillRect(LPCRECT lpRect, CBrush* pBrush); void FrameRect(LPCRECT lpRect, CBrush* pBrush); void InvertRect(LPCRECT lpRect); BOOL DrawIcon(int x, int y, HICON hIcon); BOOL DrawIcon(POINT point, HICON hIcon); #if (WINVER >= 0x400) BOOL DrawState(CPoint pt, CSize size, HBITMAP hBitmap, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, CBitmap* pBitmap, UINT nFlags, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, HICON hIcon, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, HICON hIcon, UINT nFlags, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, CBrush* pBrush = NULL); BOOL DrawState(CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, HBRUSH hBrush = NULL); BOOL DrawState(CPoint pt, CSize size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, CBrush* pBrush = NULL); #endif // Ellipse and Polygon Functions BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Chord(LPCRECT lpRect, POINT ptStart, POINT ptEnd); void DrawFocusRect(LPCRECT lpRect); BOOL Ellipse(int x1, int y1, int x2, int y2); BOOL Ellipse(LPCRECT lpRect); BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4); BOOL Pie(LPCRECT lpRect, POINT ptStart, POINT ptEnd); BOOL Polygon(LPPOINT lpPoints, int nCount); BOOL PolyPolygon(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount); BOOL Rectangle(int x1, int y1, int x2, int y2); BOOL Rectangle(LPCRECT lpRect); BOOL RoundRect(int x1, int y1, int x2, int y2, int x3, int y3); BOOL RoundRect(LPCRECT lpRect, POINT point); // Bitmap Functions BOOL PatBlt(int x, int y, int nWidth, int nHeight, DWORD dwRop); BOOL BitBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop); BOOL StretchBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop); COLORREF GetPixel(int x, int y) const; COLORREF GetPixel(POINT point) const; COLORREF SetPixel(int x, int y, COLORREF crColor); COLORREF SetPixel(POINT point, COLORREF crColor); BOOL FloodFill(int x, int y, COLORREF crColor); BOOL ExtFloodFill(int x, int y, COLORREF crColor, UINT nFillType); BOOL MaskBlt(int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, CBitmap& maskBitmap, int xMask, int yMask, DWORD dwRop); BOOL PlgBlt(LPPOINT lpPoint, CDC* pSrcDC, int xSrc, int ySrc, int nWidth, int nHeight, CBitmap& maskBitmap, int xMask, int yMask); BOOL SetPixelV(int x, int y, COLORREF crColor); BOOL SetPixelV(POINT point, COLORREF crColor); // Text Functions virtual BOOL TextOut(int x, int y, LPCTSTR lpszString, int nCount); BOOL TextOut(int x, int y, const CString& str); virtual BOOL ExtTextOut(int x, int y, UINT nOptions, LPCRECT lpRect, LPCTSTR lpszString, UINT nCount, LPINT lpDxWidths); BOOL ExtTextOut(int x, int y, UINT nOptions, LPCRECT lpRect, const CString& str, LPINT lpDxWidths); virtual CSize TabbedTextOut(int x, int y, LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin); CSize TabbedTextOut(int x, int y, const CString& str, int nTabPositions, LPINT lpnTabStopPositions, int nTabOrigin); virtual int DrawText(LPCTSTR lpszString, int nCount, LPRECT lpRect, UINT nFormat); int DrawText(const CString& str, LPRECT lpRect, UINT nFormat); CSize GetTextExtent(LPCTSTR lpszString, int nCount) const; CSize GetTextExtent(const CString& str) const; CSize GetOutputTextExtent(LPCTSTR lpszString, int nCount) const; CSize GetOutputTextExtent(const CString& str) const; CSize GetTabbedTextExtent(LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetTabbedTextExtent(const CString& str, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetOutputTabbedTextExtent(LPCTSTR lpszString, int nCount, int nTabPositions, LPINT lpnTabStopPositions) const; CSize GetOutputTabbedTextExtent(const CString& str, int nTabPositions, LPINT lpnTabStopPositions) const; virtual BOOL GrayString(CBrush* pBrush, BOOL (CALLBACK* lpfnOutput)(HDC, LPARAM, int), LPARAM lpData, int nCount, int x, int y, int nWidth, int nHeight); UINT GetTextAlign() const; UINT SetTextAlign(UINT nFlags); int GetTextFace(int nCount, LPTSTR lpszFacename) const; int GetTextFace(CString& rString) const; BOOL GetTextMetrics(LPTEXTMETRIC lpMetrics) const; BOOL GetOutputTextMetrics(LPTEXTMETRIC lpMetrics) const; int SetTextJustification(int nBreakExtra, int nBreakCount); int GetTextCharacterExtra() const; int SetTextCharacterExtra(int nCharExtra); // Advanced Drawing #if (WINVER >= 0x400) BOOL DrawEdge(LPRECT lpRect, UINT nEdge, UINT nFlags); BOOL DrawFrameControl(LPRECT lpRect, UINT nType, UINT nState); #endif // Scrolling Functions BOOL ScrollDC(int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, CRgn* pRgnUpdate, LPRECT lpRectUpdate); // Font Functions BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const; BOOL GetOutputCharWidth(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const; DWORD SetMapperFlags(DWORD dwFlag); CSize GetAspectRatioFilter() const; BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABC lpabc) const; DWORD GetFontData(DWORD dwTable, DWORD dwOffset, LPVOID lpData, DWORD cbData) const; int GetKerningPairs(int nPairs, LPKERNINGPAIR lpkrnpair) const; UINT GetOutlineTextMetrics(UINT cbData, LPOUTLINETEXTMETRIC lpotm) const; DWORD GetGlyphOutline(UINT nChar, UINT nFormat, LPGLYPHMETRICS lpgm, DWORD cbBuffer, LPVOID lpBuffer, const MAT2* lpmat2) const; BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABCFLOAT lpABCF) const; BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, float* lpFloatBuffer) const; // Printer/Device Escape Functions virtual int Escape(int nEscape, int nCount, LPCSTR lpszInData, LPVOID lpOutData); int Escape(int nEscape, int nInputSize, LPCSTR lpszInputData, int nOutputSize, LPSTR lpszOutputData); int DrawEscape(int nEscape, int nInputSize, LPCSTR lpszInputData); // Escape helpers int StartDoc(LPCTSTR lpszDocName); // old Win3.0 version int StartDoc(LPDOCINFO lpDocInfo); int StartPage(); int EndPage(); int SetAbortProc(BOOL (CALLBACK* lpfn)(HDC, int)); int AbortDoc(); int EndDoc(); // MetaFile Functions BOOL PlayMetaFile(HMETAFILE hMF); BOOL PlayMetaFile(HENHMETAFILE hEnhMetaFile, LPCRECT lpBounds); BOOL AddMetaFileComment(UINT nDataSize, const BYTE* pCommentData); // can be used for enhanced metafiles only // Path Functions BOOL AbortPath(); BOOL BeginPath(); BOOL CloseFigure(); BOOL EndPath(); BOOL FillPath(); BOOL FlattenPath(); BOOL StrokeAndFillPath(); BOOL StrokePath(); BOOL WidenPath(); float GetMiterLimit() const; BOOL SetMiterLimit(float fMiterLimit); int GetPath(LPPOINT lpPoints, LPBYTE lpTypes, int nCount) const; BOOL SelectClipPath(int nMode); // Misc Helper Functions static CBrush* PASCAL GetHalftoneBrush(); void DrawDragRect(LPCRECT lpRect, SIZE size, LPCRECT lpRectLast, SIZE sizeLast, CBrush* pBrush = NULL, CBrush* pBrushLast = NULL); void FillSolidRect(LPCRECT lpRect, COLORREF clr); void FillSolidRect(int x, int y, int cx, int cy, COLORREF clr); void Draw3dRect(LPCRECT lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight); void Draw3dRect(int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight); // Implementation public: virtual ~CDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // advanced use and implementation BOOL m_bPrinting; HGDIOBJ SelectObject(HGDIOBJ); // do not use for regions protected: // used for implementation of non-virtual SelectObject calls static CGdiObject* PASCAL SelectGdiObject(HDC hDC, HGDIOBJ h); }; ///////////////////////////////////////////////////////////////////////////// // CDC Helpers class CPaintDC : public CDC { DECLARE_DYNAMIC(CPaintDC) // Constructors public: CPaintDC(CWnd* pWnd); // BeginPaint // Attributes protected: HWND m_hWnd; public: PAINTSTRUCT m_ps; // actual paint struct! // Implementation public: virtual ~CPaintDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; class CClientDC : public CDC { DECLARE_DYNAMIC(CClientDC) // Constructors public: CClientDC(CWnd* pWnd); // Attributes protected: HWND m_hWnd; // Implementation public: virtual ~CClientDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; class CWindowDC : public CDC { DECLARE_DYNAMIC(CWindowDC) // Constructors public: CWindowDC(CWnd* pWnd); // Attributes protected: HWND m_hWnd; // Implementation public: virtual ~CWindowDC(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif }; ///////////////////////////////////////////////////////////////////////////// // CMenu class CMenu : public CObject { DECLARE_DYNCREATE(CMenu) public: // Constructors CMenu(); BOOL CreateMenu(); BOOL CreatePopupMenu(); BOOL LoadMenu(LPCTSTR lpszResourceName); BOOL LoadMenu(UINT nIDResource); BOOL LoadMenuIndirect(const void* lpMenuTemplate); BOOL DestroyMenu(); // Attributes HMENU m_hMenu; // must be first data member HMENU GetSafeHmenu() const; operator HMENU() const; static CMenu* PASCAL FromHandle(HMENU hMenu); static void PASCAL DeleteTempMap(); BOOL Attach(HMENU hMenu); HMENU Detach(); // CMenu Operations BOOL DeleteMenu(UINT nPosition, UINT nFlags); BOOL TrackPopupMenu(UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = 0); BOOL operator==(const CMenu& menu) const; BOOL operator!=(const CMenu& menu) const; // CMenuItem Operations BOOL AppendMenu(UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL AppendMenu(UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); UINT CheckMenuItem(UINT nIDCheckItem, UINT nCheck); UINT EnableMenuItem(UINT nIDEnableItem, UINT nEnable); UINT GetMenuItemCount() const; UINT GetMenuItemID(int nPos) const; UINT GetMenuState(UINT nID, UINT nFlags) const; int GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags) const; int GetMenuString(UINT nIDItem, CString& rString, UINT nFlags) const; BOOL GetMenuItemInfo(UINT nIDItem, LPMENUITEMINFO lpMenuItemInfo, BOOL fByPos = FALSE); CMenu* GetSubMenu(int nPos) const; BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL); BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp); BOOL RemoveMenu(UINT nPosition, UINT nFlags); BOOL SetMenuItemBitmaps(UINT nPosition, UINT nFlags, const CBitmap* pBmpUnchecked, const CBitmap* pBmpChecked); BOOL CheckMenuRadioItem(UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags); BOOL SetDefaultItem(UINT uItem, BOOL fByPos = FALSE); UINT GetDefaultItem(UINT gmdiFlags, BOOL fByPos = FALSE); // Context Help Functions BOOL SetMenuContextHelpId(DWORD dwContextHelpId); DWORD GetMenuContextHelpId() const; // Overridables (must override draw and measure for owner-draw menu items) virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); // Implementation public: virtual ~CMenu(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif static CMenu* PASCAL CMenu::FromHandlePermanent(HMENU hMenu); }; ///////////////////////////////////////////////////////////////////////////// // Window message map handling struct AFX_MSGMAP_ENTRY; // declared below after CWnd struct AFX_MSGMAP { #ifdef _AFXDLL const AFX_MSGMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_MSGMAP* pBaseMap; #endif const AFX_MSGMAP_ENTRY* lpEntries; }; #ifdef _AFXDLL #define DECLARE_MESSAGE_MAP() \ private: \ static const AFX_MSGMAP_ENTRY _messageEntries[]; \ protected: \ static AFX_DATA const AFX_MSGMAP messageMap; \ static const AFX_MSGMAP* PASCAL _GetBaseMessageMap(); \ virtual const AFX_MSGMAP* GetMessageMap() const; \ #else #define DECLARE_MESSAGE_MAP() \ private: \ static const AFX_MSGMAP_ENTRY _messageEntries[]; \ protected: \ static AFX_DATA const AFX_MSGMAP messageMap; \ virtual const AFX_MSGMAP* GetMessageMap() const; \ #endif #ifdef _AFXDLL #define BEGIN_MESSAGE_MAP(theClass, baseClass) \ const AFX_MSGMAP* PASCAL theClass::_GetBaseMessageMap() \ { return &baseClass;::messageMap; } \ const AFX_MSGMAP* theClass::GetMessageMap() const \ { return &theClass;::messageMap; } \ AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = \ { &theClass;::_GetBaseMessageMap, &theClass;::_messageEntries[0] }; \ AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = \ { \ #else #define BEGIN_MESSAGE_MAP(theClass, baseClass) \ const AFX_MSGMAP* theClass::GetMessageMap() const \ { return &theClass;::messageMap; } \ AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = \ { &baseClass;::messageMap, &theClass;::_messageEntries[0] }; \ AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = \ { \ #endif #define END_MESSAGE_MAP() \ {0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 } \ }; \ // Message map signature values and macros in separate header #include ///////////////////////////////////////////////////////////////////////////// // Dialog data exchange (DDX_) and validation (DDV_) // CDataExchange - for data exchange and validation class CDataExchange { // Attributes public: BOOL m_bSaveAndValidate; // TRUE => save and validate data CWnd* m_pDlgWnd; // container usually a dialog // Operations (for implementors of DDX and DDV procs) HWND PrepareCtrl(int nIDC); // return HWND of control HWND PrepareEditCtrl(int nIDC); // return HWND of control void Fail(); // will throw exception #ifndef _AFX_NO_OCC_SUPPORT CWnd* PrepareOleCtrl(int nIDC); // for OLE controls in dialog #endif // Implementation CDataExchange(CWnd* pDlgWnd, BOOL bSaveAndValidate); HWND m_hWndLastControl; // last control used (for validation) BOOL m_bEditLastControl; // last control was an edit item }; #include // standard DDX_ and DDV_ routines ///////////////////////////////////////////////////////////////////////////// // OLE types typedef LONG HRESULT; struct IUnknown; typedef IUnknown* LPUNKNOWN; struct IDispatch; typedef IDispatch* LPDISPATCH; struct IConnectionPoint; typedef IConnectionPoint* LPCONNECTIONPOINT; struct IEnumOLEVERB; typedef IEnumOLEVERB* LPENUMOLEVERB; typedef struct _GUID GUID; typedef GUID IID; typedef GUID CLSID; #ifndef _REFCLSID_DEFINED #define REFCLSID const CLSID & #endif typedef long DISPID; typedef unsigned short VARTYPE; typedef long SCODE; #if defined(WIN32) && !defined(OLE2ANSI) typedef WCHAR OLECHAR; #else typedef char OLECHAR; #endif typedef OLECHAR* BSTR; struct tagDISPPARAMS; typedef tagDISPPARAMS DISPPARAMS; struct tagVARIANT; typedef tagVARIANT VARIANT; struct ITypeInfo; typedef ITypeInfo* LPTYPEINFO; struct ITypeLib; typedef ITypeLib* LPTYPELIB; ///////////////////////////////////////////////////////////////////////////// // CCmdTarget // private structures struct AFX_CMDHANDLERINFO; // info about where the command is handled struct AFX_EVENT; // info about an event class CTypeLibCache; // cache for OLE type libraries ///////////////////////////////////////////////////////////////////////////// // OLE interface map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_INTERFACEMAP_ENTRY { const void* piid; // the interface id (IID) (NULL for aggregate) size_t nOffset; // offset of the interface vtable from m_unknown }; struct AFX_INTERFACEMAP { #ifdef _AFXDLL const AFX_INTERFACEMAP* (PASCAL* pfnGetBaseMap)(); // NULL is root class #else const AFX_INTERFACEMAP* pBaseMap; #endif const AFX_INTERFACEMAP_ENTRY* pEntry; // map for this class }; #ifdef _AFXDLL #define DECLARE_INTERFACE_MAP() \ private: \ static const AFX_INTERFACEMAP_ENTRY _interfaceEntries[]; \ protected: \ static AFX_DATA const AFX_INTERFACEMAP interfaceMap; \ static const AFX_INTERFACEMAP* PASCAL _GetBaseInterfaceMap(); \ virtual const AFX_INTERFACEMAP* GetInterfaceMap() const; \ #else #define DECLARE_INTERFACE_MAP() \ private: \ static const AFX_INTERFACEMAP_ENTRY _interfaceEntries[]; \ protected: \ static AFX_DATA const AFX_INTERFACEMAP interfaceMap; \ virtual const AFX_INTERFACEMAP* GetInterfaceMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE dispatch map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_DISPMAP_ENTRY; struct AFX_DISPMAP { #ifdef _AFXDLL const AFX_DISPMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_DISPMAP* pBaseMap; #endif const AFX_DISPMAP_ENTRY* lpEntries; UINT* lpEntryCount; DWORD* lpStockPropMask; }; #ifdef _AFXDLL #define DECLARE_DISPATCH_MAP() \ private: \ static const AFX_DISPMAP_ENTRY _dispatchEntries[]; \ static UINT _dispatchEntryCount; \ static DWORD _dwStockPropMask; \ protected: \ static AFX_DATA const AFX_DISPMAP dispatchMap; \ static const AFX_DISPMAP* PASCAL _GetBaseDispatchMap(); \ virtual const AFX_DISPMAP* GetDispatchMap() const; \ #else #define DECLARE_DISPATCH_MAP() \ private: \ static const AFX_DISPMAP_ENTRY _dispatchEntries[]; \ static UINT _dispatchEntryCount; \ static DWORD _dwStockPropMask; \ protected: \ static AFX_DATA const AFX_DISPMAP dispatchMap; \ virtual const AFX_DISPMAP* GetDispatchMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE Document Object command target handling #ifndef _AFX_NO_DOCOBJECT_SUPPORT struct AFX_OLECMDMAP_ENTRY { const GUID* pguid; // id of the command group ULONG cmdID; // OLECMD ID UINT nID; // corresponding WM_COMMAND message ID }; struct AFX_OLECMDMAP { #ifdef _AFXDLL const AFX_OLECMDMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_OLECMDMAP* pBaseMap; #endif const AFX_OLECMDMAP_ENTRY* lpEntries; }; #ifdef _AFXDLL #define DECLARE_OLECMD_MAP() \ private: \ static const AFX_OLECMDMAP_ENTRY _commandEntries[]; \ protected: \ static AFX_DATA const AFX_OLECMDMAP commandMap; \ static const AFX_OLECMDMAP* PASCAL _GetBaseCommandMap(); \ virtual const AFX_OLECMDMAP* GetCommandMap() const; \ #else #define DECLARE_OLECMD_MAP() \ private: \ static const AFX_OLECMDMAP_ENTRY _commandEntries[]; \ protected: \ static AFX_DATA const AFX_OLECMDMAP commandMap; \ virtual const AFX_OLECMDMAP* GetCommandMap() const; \ #endif #ifdef _AFXDLL #define BEGIN_OLECMD_MAP(theClass, baseClass) \ const AFX_OLECMDMAP* PASCAL theClass::_GetBaseCommandMap() \ { return &baseClass;::commandMap; } \ const AFX_OLECMDMAP* theClass::GetCommandMap() const \ { return &theClass;::commandMap; } \ AFX_COMDAT AFX_DATADEF const AFX_OLECMDMAP theClass::commandMap = \ { &theClass;::_GetBaseCommandMap, &theClass;::_commandEntries[0] }; \ AFX_COMDAT const AFX_OLECMDMAP_ENTRY theClass::_commandEntries[] = \ { \ #else #define BEGIN_OLECMD_MAP(theClass, baseClass) \ const AFX_OLECMDMAP* theClass::GetCommandMap() const \ { return &theClass;::commandMap; } \ AFX_COMDAT AFX_DATADEF const AFX_OLECMDMAP theClass::commandMap = \ { &baseClass;::commandMap, &theClass;::_commandEntries[0] }; \ AFX_COMDAT const AFX_OLECMDMAP_ENTRY theClass::_commandEntries[] = \ { \ #endif #define END_OLECMD_MAP() \ {NULL, 0, 0} \ }; \ class COleCmdUI; #endif //!_AFX_NO_DOCOBJECT_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE event sink map handling (more in AFXDISP.H) #ifndef _AFX_NO_OCC_SUPPORT struct AFX_EVENTSINKMAP_ENTRY; struct AFX_EVENTSINKMAP { #ifdef _AFXDLL const AFX_EVENTSINKMAP* (PASCAL* pfnGetBaseMap)(); #else const AFX_EVENTSINKMAP* pBaseMap; #endif const AFX_EVENTSINKMAP_ENTRY* lpEntries; UINT* lpEntryCount; }; #ifdef _AFXDLL #define DECLARE_EVENTSINK_MAP() \ private: \ static const AFX_EVENTSINKMAP_ENTRY _eventsinkEntries[]; \ static UINT _eventsinkEntryCount; \ protected: \ static AFX_DATA const AFX_EVENTSINKMAP eventsinkMap; \ static const AFX_EVENTSINKMAP* PASCAL _GetBaseEventSinkMap(); \ virtual const AFX_EVENTSINKMAP* GetEventSinkMap() const; \ #else #define DECLARE_EVENTSINK_MAP() \ private: \ static const AFX_EVENTSINKMAP_ENTRY _eventsinkEntries[]; \ static UINT _eventsinkEntryCount; \ protected: \ static AFX_DATA const AFX_EVENTSINKMAP eventsinkMap; \ virtual const AFX_EVENTSINKMAP* GetEventSinkMap() const; \ #endif #endif //!_AFX_NO_OCC_SUPPORT ///////////////////////////////////////////////////////////////////////////// // OLE connection map handling (more in AFXDISP.H) #ifndef _AFX_NO_OLE_SUPPORT struct AFX_CONNECTIONMAP_ENTRY { const void* piid; // the interface id (IID) size_t nOffset; // offset of the interface vtable from m_unknown }; struct AFX_CONNECTIONMAP { #ifdef _AFXDLL const AFX_CONNECTIONMAP* (PASCAL* pfnGetBaseMap)(); // NULL is root class #else const AFX_CONNECTIONMAP* pBaseMap; #endif const AFX_CONNECTIONMAP_ENTRY* pEntry; // map for this class }; #ifdef _AFXDLL #define DECLARE_CONNECTION_MAP() \ private: \ static const AFX_CONNECTIONMAP_ENTRY _connectionEntries[]; \ protected: \ static AFX_DATA const AFX_CONNECTIONMAP connectionMap; \ static const AFX_CONNECTIONMAP* PASCAL _GetBaseConnectionMap(); \ virtual const AFX_CONNECTIONMAP* GetConnectionMap() const; \ #else #define DECLARE_CONNECTION_MAP() \ private: \ static const AFX_CONNECTIONMAP_ENTRY _connectionEntries[]; \ protected: \ static AFX_DATA const AFX_CONNECTIONMAP connectionMap; \ virtual const AFX_CONNECTIONMAP* GetConnectionMap() const; \ #endif #endif //!_AFX_NO_OLE_SUPPORT ///////////////////////////////////////////////////////////////////////////// // CCmdTarget proper #ifndef _AFX_NO_OCC_SUPPORT class COccManager; // forward reference (see ..\src\occimpl.h) #endif #ifdef _AFXDLL class CCmdTarget : public CObject #else class AFX_NOVTABLE CCmdTarget : public CObject #endif { DECLARE_DYNAMIC(CCmdTarget) protected: public: // Constructors CCmdTarget(); // Attributes LPDISPATCH GetIDispatch(BOOL bAddRef); // retrieve IDispatch part of CCmdTarget static CCmdTarget* PASCAL FromIDispatch(LPDISPATCH lpDispatch); // map LPDISPATCH back to CCmdTarget* (inverse of GetIDispatch) BOOL IsResultExpected(); // returns TRUE if automation function should return a value // Operations void EnableAutomation(); // call in constructor to wire up IDispatch void EnableConnections(); // call in constructor to wire up IConnectionPointContainer void BeginWaitCursor(); void EndWaitCursor(); void RestoreWaitCursor(); // call after messagebox #ifndef _AFX_NO_OLE_SUPPORT // dispatch OLE verbs through the message map BOOL EnumOleVerbs(LPENUMOLEVERB* ppenumOleVerb); BOOL DoOleVerb(LONG iVerb, LPMSG lpMsg, HWND hWndParent, LPCRECT lpRect); #endif // Overridables // route and dispatch standard command message types // (more sophisticated than OnCommand) virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); #ifndef _AFX_NO_OLE_SUPPORT // called when last OLE reference is released virtual void OnFinalRelease(); #endif #ifndef _AFX_NO_OLE_SUPPORT // called before dispatching to an automation handler function virtual BOOL IsInvokeAllowed(DISPID dispid); #endif #ifndef _AFX_NO_OLE_SUPPORT // support for OLE type libraries void EnableTypeLib(); HRESULT GetTypeInfoOfGuid(LCID lcid, const GUID& guid, LPTYPEINFO* ppTypeInfo); virtual BOOL GetDispatchIID(IID* pIID); virtual UINT GetTypeInfoCount(); virtual CTypeLibCache* GetTypeLibCache(); virtual HRESULT GetTypeLib(LCID lcid, LPTYPELIB* ppTypeLib); #endif // Implementation public: virtual ~CCmdTarget(); #ifdef _DEBUG virtual void Dump(CDumpContext& dc) const; virtual void AssertValid() const; #endif #ifndef _AFX_NO_OLE_SUPPORT void GetNotSupported(); void SetNotSupported(); #endif protected: friend class CView; CView* GetRoutingView(); CFrameWnd* GetRoutingFrame(); static CView* PASCAL GetRoutingView_(); static CFrameWnd* PASCAL GetRoutingFrame_(); DECLARE_MESSAGE_MAP() // base class - no {{ }} macros #ifndef _AFX_NO_DOCOBJECT_SUPPORT DECLARE_OLECMD_MAP() friend class COleCmdUI; #endif #ifndef _AFX_NO_OLE_SUPPORT DECLARE_DISPATCH_MAP() DECLARE_CONNECTION_MAP() DECLARE_INTERFACE_MAP() #ifndef _AFX_NO_OCC_SUPPORT DECLARE_EVENTSINK_MAP() #endif // !_AFX_NO_OCC_SUPPORT // OLE interface map implementation public: // data used when CCmdTarget is made OLE aware long m_dwRef; LPUNKNOWN m_pOuterUnknown; // external controlling unknown if != NULL DWORD m_xInnerUnknown; // place-holder for inner controlling unknown public: // advanced operations void EnableAggregation(); // call to enable aggregation void ExternalDisconnect(); // forcibly disconnect LPUNKNOWN GetControllingUnknown(); // get controlling IUnknown for aggregate creation // these versions do not delegate to m_pOuterUnknown DWORD InternalQueryInterface(const void*, LPVOID* ppvObj); DWORD InternalAddRef(); DWORD InternalRelease(); // these versions delegate to m_pOuterUnknown DWORD ExternalQueryInterface(const void*, LPVOID* ppvObj); DWORD ExternalAddRef(); DWORD ExternalRelease(); // implementation helpers LPUNKNOWN GetInterface(const void*); LPUNKNOWN QueryAggregates(const void*); // advanced overrideables for implementation virtual BOOL OnCreateAggregates(); virtual LPUNKNOWN GetInterfaceHook(const void*); // OLE automation implementation protected: struct XDispatch { DWORD m_vtbl; // place-holder for IDispatch vtable #ifndef _AFX_NO_NESTED_DERIVATION size_t m_nOffset; #endif } m_xDispatch; BOOL m_bResultExpected; // member variable-based properties void GetStandardProp(const AFX_DISPMAP_ENTRY* pEntry, VARIANT* pvarResult, UINT* puArgErr); SCODE SetStandardProp(const AFX_DISPMAP_ENTRY* pEntry, DISPPARAMS* pDispParams, UINT* puArgErr); // DISPID to dispatch map lookup static UINT PASCAL GetEntryCount(const AFX_DISPMAP* pDispMap); const AFX_DISPMAP_ENTRY* PASCAL GetDispEntry(LONG memid); static LONG PASCAL MemberIDFromName(const AFX_DISPMAP* pDispMap, LPCTSTR lpszName); // helpers for member function calling implementation static UINT PASCAL GetStackSize(const BYTE* pbParams, VARTYPE vtResult); #ifdef _PPC_ SCODE PushStackArgs(BYTE* pStack, const BYTE* pbParams, void* pResult, VARTYPE vtResult, DISPPARAMS* pDispParams, UINT* puArgErr, VARIANT* rgTempVars, UINT nSizeArgs); #else SCODE PushStackArgs(BYTE* pStack, const BYTE* pbParams, void* pResult, VARTYPE vtResult, DISPPARAMS* pDispParams, UINT* puArgErr, VARIANT* rgTempVars); #endif SCODE CallMemberFunc(const AFX_DISPMAP_ENTRY* pEntry, WORD wFlags, VARIANT* pvarResult, DISPPARAMS* pDispParams, UINT* puArgErr); friend class COleDispatchImpl; #ifndef _AFX_NO_OCC_SUPPORT public: // OLE event sink implementation BOOL OnEvent(UINT idCtrl, AFX_EVENT* pEvent, AFX_CMDHANDLERINFO* pHandlerInfo); protected: const AFX_EVENTSINKMAP_ENTRY* PASCAL GetEventSinkEntry(UINT idCtrl, AFX_EVENT* pEvent); #endif // !_AFX_NO_OCC_SUPPORT // OLE connection implementation struct XConnPtContainer { DWORD m_vtbl; // place-holder for IConnectionPointContainer vtable #ifndef _AFX_NO_NESTED_DERIVATION size_t m_nOffset; #endif } m_xConnPtContainer; #ifdef _AFXDLL AFX_MODULE_STATE* m_pModuleState; friend class CInnerUnknown; friend UINT APIENTRY _AfxThreadEntry(void* pParam); #endif virtual BOOL GetExtraConnectionPoints(CPtrArray* pConnPoints); virtual LPCONNECTIONPOINT GetConnectionHook(const IID& iid); friend class COleConnPtContainer; #endif //!_AFX_NO_OLE_SUPPORT }; class CCmdUI // simple helper class { public: // Attributes UINT m_nID; UINT m_nIndex; // menu item or other index // if a menu item CMenu* m_pMenu; // NULL if not a menu CMenu* m_pSubMenu; // sub containing menu item // if a popup sub menu - ID is for first in popup // if from some other window CWnd* m_pOther; // NULL if a menu or not a CWnd // Operations to do in ON_UPDATE_COMMAND_UI virtual void Enable(BOOL bOn = TRUE); virtual void SetCheck(int nCheck = 1); // 0, 1 or 2 (indeterminate) virtual void SetRadio(BOOL bOn = TRUE); virtual void SetText(LPCTSTR lpszText); // Advanced operation void ContinueRouting(); // Implementation CCmdUI(); BOOL m_bEnableChanged; BOOL m_bContinueRouting; UINT m_nIndexMax; // last + 1 for iterating m_nIndex CMenu* m_pParentMenu; // NULL if parent menu not easily determined // (probably a secondary popup menu) BOOL DoUpdate(CCmdTarget* pTarget, BOOL bDisableIfNoHndler); }; // special CCmdUI derived classes are used for other UI paradigms // like toolbar buttons and status indicators // pointer to afx_msg member function #ifndef AFX_MSG_CALL #define AFX_MSG_CALL #endif typedef void (AFX_MSG_CALL CCmdTarget::*AFX_PMSG)(void); enum AFX_DISPMAP_FLAGS { afxDispCustom = 0, afxDispStock = 1 }; struct AFX_DISPMAP_ENTRY { LPCTSTR lpszName; // member/property name long lDispID; // DISPID (may be DISPID_UNKNOWN) LPCSTR lpszParams; // member parameter description WORD vt; // return value type / or type of property AFX_PMSG pfn; // normal member On or, OnGet AFX_PMSG pfnSet; // special member for OnSet size_t nPropOffset; // property offset AFX_DISPMAP_FLAGS flags;// flags (e.g. stock/custom) }; struct AFX_EVENTSINKMAP_ENTRY { AFX_DISPMAP_ENTRY dispEntry; UINT nCtrlIDFirst; UINT nCtrlIDLast; }; // DSC Sink state/reason codes passed to MFC user event handlers enum DSCSTATE { dscNoState = 0, dscOKToDo, dscCancelled, dscSyncBefore, dscAboutToDo, dscFailedToDo, dscSyncAfter, dscDidEvent }; enum DSCREASON { dscNoReason = 0, dscClose, dscCommit, dscDelete, dscEdit, dscInsert, dscModify, dscMove }; ///////////////////////////////////////////////////////////////////////////// // CWnd implementation // structures (see afxext.h) struct CCreateContext; // context for creating things struct CPrintInfo; // print preview customization info struct AFX_MSGMAP_ENTRY { UINT nMessage; // windows message UINT nCode; // control code or WM_NOTIFY code UINT nID; // control ID (or 0 for windows messages) UINT nLastID; // used for entries specifying a range of control id's UINT nSig; // signature type (action) or pointer to message # AFX_PMSG pfn; // routine to call (or special value) }; ///////////////////////////////////////////////////////////////////////////// // CWnd - a Microsoft Windows application window class COleDropTarget; // for more information see AFXOLE.H class COleControlContainer; class COleControlSite; // CWnd::m_nFlags (generic to CWnd) #define WF_TOOLTIPS 0x0001 // window is enabled for tooltips #define WF_TEMPHIDE 0x0002 // window is temporarily hidden #define WF_STAYDISABLED 0x0004 // window should stay disabled #define WF_MODALLOOP 0x0008 // currently in modal loop #define WF_CONTINUEMODAL 0x0010 // modal loop should continue running #define WF_OLECTLCONTAINER 0x0100 // some descendant is an OLE control #define WF_TRACKINGTOOLTIPS 0x0400 // window is enabled for tracking tooltips // CWnd::m_nFlags (specific to CFrameWnd) #define WF_STAYACTIVE 0x0020 // look active even though not active #define WF_NOPOPMSG 0x0040 // ignore WM_POPMESSAGESTRING calls #define WF_MODALDISABLE 0x0080 // window is disabled #define WF_KEEPMINIACTIVE 0x0200 // stay activate even though you are deactivated // flags for CWnd::RunModalLoop #define ML
Visual C++MFC入门教程 目录 +-- 第一章 VC入门 |------ 1.1 如何学好VC |------ 1.2 理解Windows消息机制 |------ 1.3 利用Visual C++/MFC开发Windows程序的优势 |------ 1.4 利用MFC进行开发的通用方法介绍 |------ 1.5 MFC中常用类,宏,函数介绍 +-- 第二章 图形输出 |------ 2.1 和GUI有关的各种对象 |------ 2.2 在窗口中输出文字 |------ 2.3 使用点,刷子,笔进行绘图 |------ 2.4 在窗口中绘制设备相关位图,图标,设备无关位图 |------ 2.5 使用各种映射方式 |------ 2.6 多边形和剪贴区域 +-- 第三章 文档视结构 |------ 3.1 文档 视图 框架窗口间的关系和消息传送规律 |------ 3.2 接收用户输入 |------ 3.3 使用菜单 |------ 3.4 文档,视,框架之间相互作用 |------ 3.5 利用序列化进行文件读写 |------ 3.6 MFC中所提供的各种视类介绍 +-- 第四章 窗口控件 |------ 4.1 Button |------ 4.2 Static Box |------ 4.3 Edit Box |------ 4.4 Scroll Bar |------ 4.5 List Box/Check List Box |------ 4.6 Combo Box/Combo Box Ex |------ 4.7 Tree Ctrl |------ 4.8 List Ctrl |------ 4.9 Tab Ctrl |------ 4.A Tool Bar |------ 4.B Status Bar |------ 4.C Dialog Bar |------ 4.D 利用AppWizard创建并使用ToolBar StatusBar Dialog Bar |------ 4.E General Window |------ 4.F 关于WM_NOTIFY的使用方法 +-- 第五章 对话框 |------ 5.1 使用资源编辑器编辑对话框 |------ 5.2 创建有模式对话框 |------ 5.3 创建无模式对话框 |------ 5.4 在对话框中进行消息映射 |------ 5.5 在对话框中进行数据交换和数据检查 |------ 5.6 使用属性对话框 |------ 5.7 使用通用对话框 |------ 5.8 建立以对话框为基础的应用 |------ 5.9 使用对话框作为子窗口 +-- 第六章 网络通信开发 |------ 6.1 WinSock介绍 |------ 6.2 利用WinSock进行无连接的通信 +------ 6.3 利用WinSock建立有连接的通信   第一章 VC入门 1.1 如何学好VC 这个问题很多朋友都问过我,当然流汗是必须的,但同时如果按照某种思路进行有计划的学习就会起到更好的效果。万事开头难,为了帮助朋友们更快的掌握VC开发,下面我将自己的一点体会讲一下: 1、需要有好的C/C++基础。正所谓“磨刀不误砍柴工”,最开始接触VC时不要急于开始Windows程序开发,而是应该进行一些字符界面程序的编写。这样做的目的主要是增加对语言的熟悉程度,同时也训练自己的思维和熟悉一些在编程中常犯的错误。更重要的是理解并能运用C++的各种特性,这些在以后的开发中都会有很大的帮助,特别是利用MFC进行开发的朋友对C++一定要能熟练运用。 2、理解Windows的消息机制,窗口句柄和其他GUI句柄的含义和用途。了解和MFC各个类功能相近的API函数。 3、一定要理解MFC中消息映射的作用。 4、训练自己在编写代码时不使用参考书而是使用Help Online。 5、记住一些常用的消息名称和参数的意义。 6、学会看别人的代码。 7、多看书,少买书,买书前一定要慎重。 8、闲下来的时候就看参考书。 9、多来我的主页。^O^ 后面几条是我个人的一点意见,你可以根据需要和自身的情况选用适用于自己的方法。 此外我将一些我在选择参考书时的原则: 对于初学者:应该选择一些内容比较全面的书籍,并且书籍中的内容应该以合理的方式安排,在使用该书时可以达到循序渐进的效果,书中的代码要有详细的讲解。尽量买翻译的书,因为这些书一般都比较易懂,而且语言比较轻松。买书前一定要慎重如果买到不好用的书可能会对自己的学习积极性产生击。 对于已经掌握了VC的朋友:这种程度的开发者应该加深自己对系统原理,技术要点的认识。需要选择一些对原理讲解的比较透彻的书籍,这样一来才会对新技术有更多的了解,最好书中对技术的应用有一定的阐述。尽量选择示范代码必较精简的书,可以节约银子。 此外最好涉猎一些辅助性的书籍。 1.2 理解Windows消息机制 Windows系统是一个消息驱动的OS,什么是消息呢?我很难说得清楚,也很难下一个定义(谁在嘘我),我下面从不同的几个方面讲解一下,希望大家看了后有一点了解。 1、消息的组成:一个消息由一个消息名称(UINT),和两个参数(WPARAM,LPARAM)。当用户进行了输入或是窗口的状态发生改变时系统都会发送消息到某一个窗口。例如当菜单转中之后会有WM_COMMAND消息发送,WPARAM的高字中(HIWORD(wParam))是命令的ID号,对菜单来讲就是菜单ID。当然用户也可以定义自己的消息名称,也可以利用自定义消息来发送通知和传送数据。 2、谁将收到消息:一个消息必须由一个窗口接收。在窗口的过程(WNDPROC)中可以对消息进行分析,对自己感兴趣的消息进行处理。例如你希望对菜单选择进行处理那么你可以定义对WM_COMMAND进行处理的代码,如果希望在窗口中进行图形输出就必须对WM_PAINT进行处理。 3、未处理的消息到那里去了:M$为窗口编写了默认的窗口过程,这个窗口过程将负责处理那些你不处理消息。正因为有了这个默认窗口过程我们才可以利用Windows的窗口进行开发而不必过多关注窗口各种消息的处理。例如窗口在被拖动时会有很多消息发送,而我们都可以不予理睬让系统自己去处理。 4、窗口句柄:说到消息就不能不说窗口句柄,系统通过窗口句柄来在整个系统中唯一标识一个窗口,发送一个消息时必须指定一个窗口句柄表明该消息由那个窗口接收。而每个窗口都会有自己的窗口过程,所以用户的输入就会被正确的处理。例如有两个窗口共用一个窗口过程代码,你在窗口一上按下鼠标时消息就会通过窗口一的句柄被发送到窗口一而不是窗口二。 5、示例:下面有一段伪代码演示如何在窗口过程中处理消息 LONG yourWndProc(HWND hWnd,UINT uMessageType,WPARAM wP,LPARAM) { switch(uMessageType) { //使用SWITCH语句将各种消息分开 case(WM_PAINT): doYourWindow(...);//在窗口需要重新绘制时进行输出 break; case(WM_LBUTTONDOWN): doYourWork(...);//在鼠标左键被按下时进行处理 break; default: callDefaultWndProc(...);//对于其它情况就让系统自己处理 break; } } 接下来谈谈什么是消息机制:系统将会维护一个或多个消息队列,所有产生的消息都回被放入或是插入队列中。系统会在队列中取出每一条消息,根据消息的接收句柄而将该消息发送给拥有该窗口的程序的消息循环。每一个运行的程序都有自己的消息循环,在循环中得到属于自己的消息并根据接收窗口的句柄调用相应的窗口过程。而在没有消息时消息循环就将控制权交给系统所以Windows可以同时进行多个任务。下面的伪代码演示了消息循环的用法: while(1) { id=getMessage(...); if(id == quit) break; translateMessage(...); } 当该程序没有消息通知时getMessage就不会返回,也就不会占用系统的CPU时间。 下图为消息投递模式 在16位的系统中系统中只有一个消息队列,所以系统必须等待当前任务处理消息后才可以发送下一消息到相应程序,如果一个程序陷如死循环或是耗时操作时系统就会得不到控制权。这种多任务系统也就称为协同式的多任务系统。Windows3.X就是这种系统。而32位的系统中每一运行的程序都会有一个消息队列,所以系统可以在多个消息队列中转换而不必等待当前程序完成消息处理就可以得到控制权。这种多任务系统就称为抢先式的多任务系统。Windows95/NT就是这种系统。 1.3 利用Visual C++/MFC开发Windows程序的优势 MFC借助C++的优势为Windows开发开辟了一片新天地,同时也借助ApplicationWizzard使开发者摆脱离了那些每次都必写基本代码,借助ClassWizard和消息映射使开发者摆脱了定义消息处理时那种混乱和冗长的代码段。更令人兴奋的是利用C++的封装功能使开发者摆脱Windows中各种句柄的困扰,只需要面对C++中的对象,这样一来使开发更接近开发语言而远离系统。(但我个人认为了解系统原理对开发很有帮助) 正因为MFC是建立在C++的基础上,所以我强调C/C++语言基础对开发的重要性。利用C++的封装性开发者可以更容易理解和操作各种窗口对象;利用C++的派生性开发者可以减少开发自定义窗口的时间和创造出可重用的代码;利用虚拟性可以在必要时更好的控制窗口的活动。而且C++本身所具备的超越C语言的特性都可以使开发者编写出更易用,更灵活的代码。 在MFC中对消息的处理利用了消息映射的方法,该方法的基础是宏定义实现,通过宏定义将消息分派到不同的成员函数进行处理。下面简单讲述一下这种方法的实现方法: 代码如下 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() //}}AFX_MSG_MAP ON_COMMAND(ID_FONT_DROPDOWN, DoNothing) END_MESSAGE_MAP() 经过编译后,代码被替换为如下形式(这只是作讲解,实际情况比这复杂得多): //BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) CMainFrame::newWndProc(...) { switch(...) { //{{AFX_MSG_MAP(CMainFrame) // ON_WM_CREATE() case(WM_CREATE): OnCreate(...); break; //}}AFX_MSG_MAP // ON_COMMAND(ID_FONT_DROPDOWN, DoNothing) case(WM_COMMAND): if(HIWORD(wP)==ID_FONT_DROPDOWN) { DoNothing(...); } break; //END_MESSAGE_MAP() } } newWndProc就是窗口过程只要是该类的实例生成的窗口都使用该窗口过程。 所以了解了Windows的消息机制在加上对消息映射的理解就很容易了解MFC开发的基本思路了。 1.4 利用MFC进行开发的通用方法介绍 以下是我在最初学习VC时所常用的开发思路和方法,希望能对初学VC的朋友有所帮助和启发。 1、开发需要读写文件的应用程序并且有简单的输入和输出可以利用单文档视结构。 2、开发注重交互的简单应用程序可以使用对话框为基础的窗口,如果文件读写简单这可利用CFile进行。 3、开发注重交互并且文件读写复杂的的简单应用程序可以利用以CFormView为基础视的单文档视结构。 4、利用对话框得到用户输入的数据,在等级提高后可使用就地输入。 5、在对多文档要求不强烈时尽量避免多文档视结构,可以利用分隔条产生单文档多视结构。 6、在要求在多个文档间传递数据时使用多文档视结构。 7、学会利用子窗口,并在自定义的子窗口包含多个控件达到封装功能的目的。 8、尽量避免使用多文档多视结构。 9、不要使用多重继承并尽量减少一个类中封装过多的功能。 1.5 MFC中常用类,宏,函数介绍 常用类 CRect:用来表示矩形的类,拥有四个成员变量:top left bottom right。分别表是左上角和右下角的坐标。可以通过以下的方法构造: CRect( int l, int t, int r, int b ); 指明四个坐标 CRect( const RECT& srcRect ); 由RECT结构构造 CRect( LPCRECT lpSrcRect ); 由RECT结构构造 CRect( POINT point, SIZE size ); 有左上角坐标和尺寸构造 CRect( POINT topLeft, POINT bottomRight ); 有两点坐标构造 下面介绍几个成员函数: int Width( ) const; 得到宽度 int Height( ) const; 得到高度 CSize Size( ) const; 得到尺寸 CPoint& TopLeft( ); 得到左上角坐标 CPoint& BottomRight( ); 得到右下角坐标 CPoint CenterPoint( ) const; 得当中心坐标 此外矩形可以和点(CPoint)相加进行位移,和另一个矩形相加得到“并”操作后的矩形。 CPoint:用来表示一个点的坐标,有两个成员变量:x y。 可以和另一个点相加。 CString:用来表示可变长度的字符串。使用CString可不指明内存大小,CString会根据需要自行分配。下面介绍几个成员函数: GetLength 得到字符串长度 GetAt 得到指定位置处的字符 operator + 相当于strcat void Format( LPCTSTR lpszFormat, ... ); 相当于sprintf Find 查找指定字符,字符串 Compare 比较 CompareNoCase 不区分大小写比较 MakeUpper 改为小写 MakeLower 改为大写 CStringArray:用来表示可变长度的字符串数组。数组中每一个元素为CString对象的实例。下面介绍几个成员函数: Add 增加CString RemoveAt 删除指定位置CString对象 RemoveAll 删除数组中所有CString对象 GetAt 得到指定位置的CString对象 SetAt 修改指定位置的CString对象 InsertAt 在某一位置插入CString对象 常用宏 RGB TRACE ASSERT VERIFY 常用函数 CWindApp* AfxGetApp(); HINSTANCE AfxGetInstanceHandle( ); HINSTANCE AfxGetResourceHandle( ); int AfxMessageBox( LPCTSTR lpszText, UINT nType = MB_OK, UINT nIDHelp = 0 );用于弹出一个消息框 第二章 图形输出 2.1 和GUI有关的各种对象 在Windows中有各种GUI对象(不要和C++对象混淆),当你在进行绘图就需要利用这些对象。而各种对象都拥有各种属性,下面分别讲述各种GUI对象和拥有的属性。 字体对象CFont用于输出文字时选用不同风格和大小的字体。可选择的风格包括:是否为斜体,是否为粗体,字体名称,是否有下划线等。颜色和背景色不属于字体的属性。关于如何创建和使用字体在2.2 在窗口中输出文字中会详细讲解。 刷子CBrush对象决定填充区域时所采用的颜色或模板。对于一个固定色的刷子来讲它的属性为颜色,是否采用网格和网格的类型如水平的,垂直的,交叉的等。你也可以利用8*8的位图来创建一个自定义模板的刷子,在使用这种刷子填充时系统会利用位图逐步填充区域。关于如何创建和使用刷子在2.3 使用刷子,笔进行绘图中会详细讲解。 画笔CPen对象在画点和画线时有用。它的属性包括颜色,宽度,线的风格,如虚线,实线,点划线等。关于如何创建和使用画笔在2.3 使用刷子,笔进行绘图中会详细讲解。 位图CBitmap对象可以包含一幅图像,可以保存在资源中。关于如何使用位图在2.4 在窗口中绘制设备相关位图,图标,设备无关位图中会详细讲解。 还有一种特殊的GUI对象是多边形,利用多边形可以很好的限制作图区域或是改变窗口外型。关于如何创建和使用多边形在2.6 多边形和剪贴区域中会详细讲解。 在Windows中使用GUI对象必须遵守一定的规则。首先需要创建一个合法的对象,不同的对象创建方法不同。然后需要将该GUI对象选入DC中,同时保存DC中原来的GUI对象。如果选入一个非法的对象将会引起异常。在使用完后应该恢复原来的对象,这一点特别重要,如果保存一个临时对象在DC中,而在临时对象被销毁后可能引起异常。有一点必须注意,每一个对象在重新创建前必须销毁,下面的代码演示了这一种安全的使用方法: OnDraw(CDC* pDC) { CPen pen1,pen2; pen1.CreatePen(PS_SOLID,2,RGB(128,128,128));//创建对象 pen2.CreatePen(PS_SOLID,2,RGB(128,128,0));//创建对象 CPen* pPenOld=(CPen*)pDC->SelectObject(&pen1);//选择对象进DC drawWithPen1... (CPen*)pDC->SelectObject(&pen2);//选择对象进DC drawWithPen2... pen1.DeleteObject();//再次创建前先销毁 pen1.CreatePen(PS_SOLID,2,RGB(0,0,0));//再次创建对象 (CPen*)pDC->SelectObject(&pen1);//选择对象进DC drawWithPen1... pDC->SelectObject(pOldPen);//恢复 } 此外系统中还拥有一些库存GUI对象,你可以利用CDC::SelectStockObject(SelectStockObject( int nIndex )选入这些对象,它们包括一些固定颜色的刷子,画笔和一些基本字体。 • BLACK_BRUSH Black brush. • DKGRAY_BRUSH Dark gray brush. • GRAY_BRUSH Gray brush. • HOLLOW_BRUSH Hollow brush. • LTGRAY_BRUSH Light gray brush. • NULL_BRUSH Null brush. • WHITE_BRUSH White brush. • BLACK_PEN Black pen. • NULL_PEN Null pen. • WHITE_PEN White pen. • ANSI_FIXED_FONT ANSI fixed system font. • ANSI_VAR_FONT ANSI variable system font. • DEVICE_DEFAULT_FONT Device-dependent font. • OEM_FIXED_FONT OEM-dependent fixed font. • SYSTEM_FONT The system font. By default, Windows uses the system font to draw menus, dialog-box controls, and other text. In Windows versions 3.0 and later, the system font is proportional width; earlier versions of Windows use a fixed-width system font. • SYSTEM_FIXED_FONT The fixed-width system font used in Windows prior to version 3.0. This object is available for compatibility with earlier versions of Windows. • DEFAULT_PALETTE Default color palette. This palette consists of the 20 static colors in the system palette. 这些对象留在DC中是安全的,所以你可以利用选入库存对象来作为恢复DC中GUI对象。 大家可能都注意到了绘图时都需要一个DC对象,DC(Device Context设备环境)对象是一个抽象的作图环境,可能是对应屏幕,也可能是对应打印机或其它。这个环境是设备无关的,所以你在对不同的设备输出时只需要使用不同的设备环境就行了,而作图方式可以完全不变。这也就是Windows耀眼的一点设备无关性。如同你将对一幅画使用照相机或复印机将会产生不同的输出,而不需要对画进行任何调整。DC的使用会穿插在本章中进行介绍。 2.2 在窗口中输出文字 在这里我假定读者已经利用ApplicationWizard生成了一个SDI界面的程序代码。接下来的你只需要在CView派生类的OnDraw成员函数中加入绘图代码就可以了。在这里我需要解释一下OnDraw函数的作用,OnDraw函数会在窗口需要重绘时自动被调用,传入的参数CDC* pDC对应的就是DC环境。使用OnDraw的优点就在于在你使用打印功能的时候传入OnDraw的DC环境将会是打印机绘图环境,使用打印预览时传入的是一个称为CPreviewDC的绘图环境,所以你只需要一份代码就可以完成窗口/打印预览/打印机绘图三重功能。利用Windows的设备无关性和M$为打印预览所编写的上千行代码你可以很容易的完成一个具有所见即所得的软件。 输出文字一般使用CDC::BOOL TextOut( int x, int y, const CString& str )和CDC::int DrawText( const CString& str, LPRECT lpRect, UINT nFormat )两个函数,对TextOut来讲只能输出单行的文字,而DrawText可以指定在一个矩形中输出单行或多行文字,并且可以规定对齐方式和使用何种风格。nFormat可以是多种以下标记的组合(利用位或操作)以达到选择输出风格的目的。 • DT_BOTTOM底部对齐 Specifies bottom-justified text. This value must be combined with DT_SINGLELINE. • DT_CALCRECT计算指定文字时所需要矩形尺寸 Determines the width and height of the rectangle. If there are multiple lines of text, DrawText will use the width of the rectangle pointed to by lpRect and extend the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText will modify the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text, but does not draw the text. • DT_CENTER中部对齐 Centers text horizontally. • DT_END_ELLIPSIS or DT_PATH_ELLIPSIS Replaces part of the given string with ellipses, if necessary, so that the result fits in the specified rectangle. The given string is not modified unless the DT_MODIFYSTRING flag is specified. You can specify DT_END_ELLIPSIS to replace characters at the end of the string, or DT_PATH_ELLIPSIS to replace characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash. • DT_EXPANDTABS Expands tab characters. The default number of characters per tab is eight. • DT_EXTERNALLEADING Includes the font抯 external leading in the line height. Normally, external leading is not included in the height of a line of text. • DT_LEFT左对齐 Aligns text flush-left. • DT_MODIFYSTRING Modifies the given string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified. Note Some uFormat flag combinations can cause the passed string to be modified. Using DT_MODIFYSTRING with either DT_END_ELLIPSIS or DT_PATH_ELLIPSIS may cause the string to be modified, causing an assertion in the CString override. • DT_NOCLIP Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used. • DT_NOPREFIX禁止使用&前缀 Turns off processing of prefix characters. Normally, DrawText interprets the ampersand (&) mnemonic-prefix character as a directive to underscore the character that follows, and the two-ampersand (&&) mnemonic-prefix characters as a directive to print a single ampersand. By specifying DT_NOPREFIX, this processing is turned off. • DT_PATH_ELLIPSIS • DT_RIGHT右对齐 Aligns text flush-right. • DT_SINGLELINE单行输出 Specifies single line only. Carriage returns and linefeeds do not break the line. • DT_TABSTOP设置TAB字符所占宽度 Sets tab stops. The high-order byte of nFormat is the number of characters for each tab. The default number of characters per tab is eight. • DT_TOP定部对齐 Specifies top-justified text (single line only). • DT_VCENTER中部对齐 Specifies vertically centered text (single line only). • DT_WORDBREAK每行只在单词间被折行 Specifies word-breaking. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by lpRect. A carriage return杔inefeed sequence will also break the line. 在输出文字时如果希望改变文字的颜色,你可以利用CDC::SetTextColor( COLORREF crColor )进行设置,如果你希望改变背景色就利用CDC::SetBkColor( COLORREF crColor ),很多时候你可能需要透明的背景色你可以利用CDC::SetBkMode( int nBkMode )设置,可接受的参数有 • 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. 接下来讲讲如何创建字体,你可以创建的字体有两种:库存字体CDC::CreateStockObject( int nIndex )和自定义字体。 在创建非库存字体时需要填充一个LOGFONT结构并使用CFont::CreateFontIndirect(const LOGFONT* lpLogFont ),或使用CFont::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 )其中的参数和LOGFONT中的分量有一定的对应关系。下面分别讲解参数的意义: nHeight 字体高度(逻辑单位)等于零为缺省高度,否则取绝对值并和可用的字体高度进行匹配。 nWidth 宽度(逻辑单位)如果为零则使用可用的横纵比进行匹配。 nEscapement 出口矢量与X轴间的角度 nOrientation 字体基线与X轴间的角度 nWeight 字体粗细,可取以下值 Constant Value FW_DONTCARE 0 FW_THIN 100 FW_EXTRALIGHT 200 FW_ULTRALIGHT 200 FW_LIGHT 300 FW_NORMAL 400 FW_REGULAR 400 FW_MEDIUM 500 FW_SEMIBOLD 600 FW_DEMIBOLD 600 FW_BOLD 700 FW_EXTRABOLD 800 FW_ULTRABOLD 800 FW_BLACK 900 FW_HEAVY 900 bItalic 是否为斜体 bUnderline 是否有下划线 cStrikeOut 是否带删除线 nCharSet 指定字符集合,可取以下值 Constant Value ANSI_CHARSET 0 DEFAULT_CHARSET 1 SYMBOL_CHARSET 2 SHIFTJIS_CHARSET 128 OEM_CHARSET 255 nOutPrecision 输出精度 OUT_CHARACTER_PRECIS OUT_STRING_PRECIS OUT_DEFAULT_PRECIS OUT_STROKE_PRECIS OUT_DEVICE_PRECIS OUT_TT_PRECIS OUT_RASTER_PRECIS nClipPrecision 剪辑精度,可取以下值 CLIP_CHARACTER_PRECIS CLIP_MASK CLIP_DEFAULT_PRECIS CLIP_STROKE_PRECIS CLIP_ENCAPSULATE CLIP_TT_ALWAYS CLIP_LH_ANGLES nQuality 输出质量,可取以下值 • DEFAULT_QUALITY Appearance of the font does not matter. • DRAFT_QUALITY Appearance of the font is less important than when PROOF_QUALITY is used. For GDI raster fonts, scaling is enabled. Bold, italic, underline, and strikeout fonts are synthesized if necessary. • PROOF_QUALITY Character quality of the font is more important than exact matching of the logical-font attributes. For GDI raster fonts, scaling is disabled and the font closest in size is chosen. Bold, italic, underline, and strikeout fonts are synthesized if necessary. nPitchAndFamily 字体间的间距 lpszFacename 指定字体名称,为了得到系统所拥有的字体可以利用EmunFontFamiliesEx。 此外可以利用CFontDialog来得到用户选择的字体的LOGFONT数据。 最后我讲一下文本坐标的计算,利用CDC::GetTextExtent( const CString& str )可以得到字符串的在输出时所占用的宽度和高度,这样就可以在手工输出多行文字时使用正确的行距。另外如果需要更精确的对字体高度和宽度进行计算就需要使用CDC::GetTextMetrics( LPTEXTMETRIC lpMetrics ) 该函数将会填充TEXTMETRIC结构,该结构中的分量可以非常精确的描述字体的各种属性。 2.3 使用点,刷子,笔进行绘图 在Windows中画点的方法很简单,只需要调用COLORREF CDC::SetPixel( int x, int y, COLORREF crColor )就可以在指定点画上指定颜色,同时返回原来的颜色。COLORREF CDC::GetPixel( int x, int y)可以得到指定点的颜色。在Windows中应该少使用画点的函数,因为这样做的执行效率比较低。 刷子和画笔在Windows作图中是使用最多的GUI对象,本节在讲解刷子和画笔使用方法的同时也讲述一写基本作图函数。 在画点或画线时系统使用当前DC中的画笔,所以在创建画笔后必须将其选入DC才会在绘图时产生效果。画笔可以通过CPen对象来产生,通过调用CPen::CreatePen( int nPenStyle, int nWidth, COLORREF crColor )来创建。其中nPenStyle指名画笔的风格,可取如下值: • 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. • PS_ENDCAP_ROUND 结束处为圆形 End caps are round. • PS_ENDCAP_SQUARE 结束处为方形 End caps are square. nWidth和crColor为线的宽度和颜色。 刷子是在画封闭曲线时用来填充的颜色,例如当你画圆形或方形时系统会用当前的刷子对内部进行填充。刷子可利用CBrush对象产生。通过以下几种函数创建刷子: • BOOL CreateSolidBrush( COLORREF crColor ); 创建一种固定颜色的刷子 • BOOL CreateHatchBrush( int nIndex, COLORREF crColor ); 创建指定颜色和网格的刷子,nIndex可取以下值: • 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 • BOOL CreatePatternBrush( CBitmap* pBitmap ); 创建以8*8位图为模板的刷子 在选择了画笔和刷子后就可以利用Windows的作图函数进行作图了,基本的画线函数有以下几种 • CDC::MoveTo( int x, int y ); 改变当前点的位置 • CDC::LineTo( int x, int y ); 画一条由当前点到参数指定点的线 • CDC::BOOL Arc( LPCRECT lpRect, POINT ptStart, POINT ptEnd ); 画弧线 • CDC::BOOL Polyline( LPPOINT lpPoints, int nCount ); 将多条线依次序连接 基本的作图函数有以下几种: • CDC::BOOL Rectangle( LPCRECT lpRect ); 矩形 • CDC::RoundRect( LPCRECT lpRect, POINT point ); 圆角矩形 • CDC::Draw3dRect( int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight ); 3D边框 • CDC::Chord( LPCRECT lpRect, POINT ptStart, POINT ptEnd ); 扇形 • CDC::Ellipse( LPCRECT lpRect ); 椭圆形 • CDC::Pie( LPCRECT lpRect, POINT ptStart, POINT ptEnd ); • CDC::Polygon( LPPOINT lpPoints, int nCount ); 多边形 对于矩形,圆形或类似的封闭曲线,系统会使用画笔绘制边缘,使用刷子填充内部。如果你不希望填充或是画出边缘,你可以选入空刷子(NULL_PEN)或是(NULL_BRUSH)空笔。 下面的代码创建一条两象素宽的实线并选入DC。并进行简单的作图: { ... CPen pen; pen.CreatePen(PS_SOLID,2,RGB(128,128,128)); CPen* pOldPen=(CPen*)dc.SelectObject(&pen); dc.SelectStockObject(NULL_BRUSH);//选入空刷子 dc.Rectangle(CRect(0,0,20,20));//画矩形 ... } 2.4 在窗口中绘制设备相关位图,图标,设备无关位图 在Windows中可以将预先准备好的图像复制到显示区域中,这种内存拷贝执行起来是非常快的。在Windows中提供了两种使用图形拷贝的方法:通过设备相关位图(DDB)和设备无关位图(DIB)。 DDB可以用MFC中的CBitmap来表示,而DDB一般是存储在资源文件中,在加载时只需要通过资源ID号就可以将图形装入。BOOL CBitmap::LoadBitmap( UINT nIDResource )可以装入指定DDB,但是在绘制时必须借助另一个和当前绘图DC兼容的内存DC来进行。通过CDC::BitBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop )绘制图形,同时指定光栅操作的类型。BitBlt可以将源DC中位图复制到目的DC中,其中前四个参数为目的区域的坐标,接下来是源DC指针,然后是源DC中的起始坐标,由于BitBlt为等比例复制,所以不需要再次指定长宽,(StretchBlt可以进行缩放)最后一个参数为光栅操作的类型,可取以下值: • BLACKNESS 输出区域为黑色 Turns all output black. • DSTINVERT 反色输出区域 Inverts the destination bitmap. • MERGECOPY 在源和目的间使用AND操作 Combines the pattern and the source bitmap using the Boolean AND operator. • MERGEPAINT 在反色后的目的和源间使用OR操作 Combines the inverted source bitmap with the destination bitmap using the Boolean OR operator. • NOTSRCCOPY 将反色后的源拷贝到目的区 Copies the inverted source bitmap to the destination. • PATINVERT 源和目的间进行XOR操作 Combines the destination bitmap with the pattern using the Boolean XOR operator. • SRCAND 源和目的间进行AND操作 Combines pixels of the destination and source bitmaps using the Boolean AND operator. • SRCCOPY 复制源到目的区 Copies the source bitmap to the destination bitmap. • SRCINVERT 源和目的间进行XOR操作 Combines pixels of the destination and source bitmaps using the Boolean XOR operator. • SRCPAINT 源和目的间进行OR操作 Combines pixels of the destination and source bitmaps using the Boolean OR operator. • WHITENESS 输出区域为白色 Turns all output white. 下面用代码演示这种方法: CYourView::OnDraw(CDC* pDC) { CDC memDC;//定义一个兼容DC memDC.CreateCompatibleDC(pDC);//创建DC CBitmap bmpDraw; bmpDraw.LoadBitmap(ID_BMP) ;//装入DDB CBitmap* pbmpOld=memDC.SelectObject(&bmpDraw) ; //保存原有DDB,并选入新DDB入DC pDC->BitBlt(0,0,20,20,&memDC,0,0,SRCCOPY) ; //将源DC中(0,0,20,20)复制到目的DC(0,0,20,20) pDC->BitBlt(20,20,40,40,&memDC,0,0,SRCAND); //将源DC中(0,0,20,20)和目的DC(20,20,40,40)中区域进行AND操作 memDC.SelectObject(pbmpOld) ;//选入原DDB } (图标并不是一个GDI对象,所以不需要选入DC)在MFC中没有一个专门的图标类,因为图标的操作比较简单,使用HICON CWinApp::LoadIcon( UINT nIDResource )或是HICON CWinApp::LoadStandardIcon( LPCTSTR lpszIconName ) 装入后就可以利用BOOL CDC::DrawIcon( int x, int y, HICON hIcon )绘制。由于在图标中可以指定透明区域,所以在某些需要使用非规则图形而且面积不大的时候使用图标会比较简单。下面给出简单的代码: OnDraw(CDC* pDC) { HICON hIcon1=AfxGetApp()->LoadIcon(IDI_I1); HICON hIcon2=AfxGetApp()->LoadIcon(IDI_I2); pDC->DrawIcon(0,0,hIcon1); pDC->DrawIcon(0,40,hIcon2); DestroyIcon(hIcon1); DestroyIcon(hIcon2); } 同样在MFC也没有提供一个DIB的类,所以在使用DIB位图时我们需要自己读取位图文件中的头信息,并读入数据,并利用API函数StretchDIBits绘制。位图文件以BITMAPFILEHEADER结构开始,然后是BITMAPINFOHEADER结构和调色版信息和数据,其实位图格式是图形格式中最简单的一种,而且也是Windows可以理解的一种。我不详细讲解DIB位图的结构,提供一个CDib类供大家使用,这个类包含了基本的功能如:Load,Save,Draw。DownLoad CDib 4K 2.5 使用各种映射方式 所谓的映射方式简单点讲就是坐标的安排方式,系统默认的映射方式为MM_TEXT即X坐标向右增加,Y坐标向下增加,(0,0)在屏幕左上方,DC中的每一点就是屏幕上的一个象素。也许你会认为这种方式下是最好理解的,但是一个点和象素对应的关系在屏幕上看来是正常的,但到了打印机上就会很不正常。因为我们作图是以点为单位并且打印机的分辨率远远比显示器高(800DPI 800点每英寸)所以在打印机上图形看起来就会很小。这样就需要为打印另做一套代码而加大了工作量。如果每个点对应0.1毫米那么在屏幕上的图形就会和打印出来的图形一样大小。 通过int CDC::SetMapMode( int nMapMode )可以指定映射方式,可用的有以下几种: • MM_HIENGLISH 每点对应0.001英寸 Each logical unit is converted to 0.001 inch. Positive x is to the right; positive y is up. • MM_HIMETRIC 每点对应0.001毫米 Each logical unit is converted to 0.01 millimeter. Positive x is to the right; positive y is up. • MM_LOENGLISH 每点对应0.01英寸 Each logical unit is converted to 0.01 inch. Positive x is to the right; positive y is up. • MM_LOMETRIC 每点对应0.001毫米 Each logical unit is converted to 0.1 millimeter. Positive x is to the right; positive y is up. • MM_TEXT 象素对应 Each logical unit is converted to 1 device pixel. Positive x is to the right; positive y is down. 以上几种映射默认的原点在屏幕左上方。除MM_TEXT外都为X坐标向右增加,Y坐标向上增加,和自然坐标是一致的。所以在作图是要注意什么时候应该使用负坐标。而且以上的映射都是X-Y等比例的,即相同的长度在X,Y轴上显示的长度都是相同的。 DownLoad Sample 另外的一种映射方式为MM_ANISOTROPIC,这种方式可以规定不同的长宽比例。在设置这中映射方式后必须调用CSize CDC::SetWindowExt( SIZE size )和CSize CDC::SetViewportExt( SIZE size )来设定长宽比例。系统会根据两次设定的长宽的比值来确定长宽比例。下面给出一段代码比较映射前后的长宽比例: OnDraw(CDC* pDC) { CRect rcC1(200,0,400,200); pDC->FillSolidRect(rcC1,RGB(0,0,255)); pDC->SetMapMode(MM_ANISOTROPIC ); CSize sizeO; sizeO=pDC->SetWindowExt(5,5); TRACE("winExt %d %d\n",sizeO.cx,sizeO.cy); sizeO=pDC->SetViewportExt(5,10); TRACE("ViewExt %d %d\n",sizeO.cx,sizeO.cy); CRect rcC(0,0,200,200); pDC->FillSolidRect(rcC,RGB(0,128,0)); } 上面代码在映射后画出的图形将是一个长方形。 DownLoad Sample 最后讲讲视原点(viewport origin),你可以通过调用CPoint CDC::SetViewportOrg( POINT point )重新设置原点的位置,这就相对于对坐标进行了位移。例如你将原点设置在(20,20)那么原来的(0,0)就变成了(-20,-20)。 2.6 多边形和剪贴区域 多边形也是一个GDI对象,同样遵守其他GDI对象的规则,只是通常都不将其选入DC中。在MFC中多边形有CRgn表示。多边形用来表示一个不同与矩形的区域,和矩形具有相似的操作。如:检测某点是否在内部,并操作等。此外还得到一个包含此多边形的最小矩形。下面介绍一下多边形类的成员函数: • CreateRectRgn 由矩形创建一个多边形 • CreateEllipticRgn 由椭圆创建一个多边形 • CreatePolygonRgn 创建一个有多个点围成的多边形 • PtInRegion 某点是否在内部 • CombineRgn 两个多边形相并 • EqualRgn 两个多边形是否相等 在本节中讲演多边形的意义在于重新在窗口中作图时提高效率。因为引发窗口重绘的原因是某个区域失效,而失效的区域用多边形来表示。假设窗口大小为500*400当上方的另一个窗口从(0,0,10,10)移动到(20,20,30,30)这时(0,0,10,10)区域就失效了,而你只需要重绘这部分区域而不是所有区域,这样你程序的执行效率就会提高。 通过调用API函数int GetClipRgn( HDC hdc, HRGN hrgn)就可以得到失效区域,但是一般用不着那么精确而只需得到包含该区域的最小矩形就可以了,所以可以利用int CDC::GetClipBox( LPRECT lpRect )完成这一功能。 第三章 文档视结构 3.1 文档 视图 框架窗口间的关系和消息传送规律 在MFC中M$引入了文档-视结构的概念,文档相当于数据容器,视相当于查看数据的窗口或是和数据发生交互的窗口。(这一结构在MFC中的OLE,ODBC开发时又得到更多的拓展)因此一个完整的应用一般由四个类组成:CWinApp应用类,CFrameWnd窗口框架类,CDocument文档类,CView视类。(VC6中支持创建不带文档-视的应用) 在程序运行时CWinApp将创建一个CFrameWnd框架窗口实例,而框架窗口将创建文档模板,然后有文档模板创建文档实例和视实例,并将两者关联。一般来讲我们只需对文档和视进行操作,框架的各种行为已经被MFC安排好了而不需人为干预,这也是M$设计文档-视结构的本意,让我们将注意力放在完成任务上而从界面编写中解放出来。 在应用中一个视对应一个文档,但一个文档可以包含多个视。一个应用中只用一个框架窗口,对多文档界面来讲可能有多个MDI子窗口。每一个视都是一个子窗口,在单文档界面中父窗口即是框架窗口,在多文档界面中父窗口为MDI子窗口。一个多文档应用中可以包含多个文档模板,一个模板定义了一个文档和一个或多个视之间的对应关系。同一个文档可以属于多个模板,但一个模板中只允许定义一个文档。同样一个视也可以属于多个文档模板。(不知道我说清楚没有) 接下来看看如何在程序中得到各种对象的指针: • 全局函数AfxGetApp可以得到CWinApp应用类指针 • AfxGetApp()->m_pMainWnd为框架窗口指针 • 在框架窗口中:CFrameWnd::GetActiveDocument得到当前活动文档指针 • 在框架窗口中:CFrameWnd::GetActiveView得到当前活动视指针 • 在视中:CView::GetDocument得到对应的文档指针 • 在文档中:CDocument::GetFirstViewPosition,CDocument::GetNextView用来遍历所有和文档关联的视。 • 在文档中:CDocument::GetDocTemplate得到文档模板指针 • 在多文档界面中:CMDIFrameWnd::MDIGetActive得到当前活动的MDI子窗口 一般来讲用户输入消息(如菜单选择,鼠标,键盘等)会先发往视,如果视未处理则会发往框架窗口。所以定义消息映射时定义在视中就可以了,如果一个应用同时拥有多个视而当前活动视没有对消息进行处理则消息会发往框架窗口。 3.2 接收用户输入 在视中接收鼠标输入: 鼠标消息是我们常需要处理的消息,消息分为:鼠标移动,按钮按下/松开,双击。利用ClassWizard可以轻松的添加这几种消息映射,下面分别讲解每种消息的处理。 WM_MOUSEMOVE对应的函数为OnMouseMove( UINT nFlags, CPoint point ),nFlags表明了当前一些按键的消息,你可以通过“位与”操作进行检测。 • MK_CONTROL Ctrl键是否被按下 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 Shift键是否被按下 Set if the SHIFT key is down. point表示当前鼠标的设备坐标,坐标原点对应视左上角。 WM_LBUTTONDOWN/WM_RBUTTONDOWN(鼠标左/右键按下)对应的函数为OnLButtonDown/OnRButtonDown( UINT nFlags, CPoint point )参数意义和OnMouseMove相同。 WM_LBUTTONUP/WM_RBUTTONUP(鼠标左/右键松开)对应的函数为OnLButtonUp/OnRButtonUp( UINT nFlags, CPoint point )参数意义和OnMouseMove相同。 WM_LBUTTONDBLCLK/WM_RBUTTONDBLCLK(鼠标左/右键双击)对应的函数为OnLButtonDblClk/OnRButtonDblClk( UINT nFlags, CPoint point )参数意义和OnMouseMove相同。 下面我用一段伪代码来讲解一下这些消息的用法: 代码的作用是用鼠标拉出一个矩形 global BOOL fDowned;//是否在拉动 global CPoint ptDown;//按下位置 global CPoint ptUp;//松开位置 OnLButtonDown(UINT nFlags, CPoint point) { fDowned=TRUE; ptUp=ptDown=point; DrawRect(); ... } OnMouseMove(UINT nFlags, CPoint point) { if(fDowned) { DrawRect();//恢复上次所画的矩形 ptUp=point; DrawRect();//画新矩形 } } OnLButtonUp(UINT nFlags, CPoint point) { if(fDowned) { DrawRect();//恢复上次所画的矩形 ptUp=point; DrawRect();//画新矩形 fDowned=FALSE; } } DrawRect() {//以反色屏幕的方法画出ptDown,ptUp标记的矩形 CClientDC dc(this); MakeRect(ptDown,ptUp); SetROP(NOT); Rect(); } 坐标间转换:在以上的函数中point参数对应的都是窗口的设备坐标,我们应该将设备坐标和逻辑坐标相区别,在图32_g1由于窗口使用了滚动条,所以传入的设备坐标是对应于当前窗口左上角的坐标,没有考虑是否滚动,而逻辑坐标必须考虑滚动后对应的坐标,所以我以黄线虚拟的表达一个逻辑坐标的区域。可以看得出同一点在滚动后的坐标值是不同的,这一规则同样适用于改变了映射方式的窗口,假设你将映射方式设置为每点为0.01毫米,那么设备坐标所对应的逻辑坐标也需要重新计算。进行这种转换需要写一段代码,所幸的是系统提供了进行转换的功能DC的DPtoLP,LPtoDP,下面给出代码完成由设备坐标到逻辑坐标的转换。 图32_g1 CPoint CYourView::FromDP(CPoint point) { CClientDC dc(this); CPoint ptRet=point; dc.PrepareDC();//必须先准备DC,这在使用滚动时让DC重新计算坐标 //如果你作图设置了不同的映射方式,则在下面需要设置 dc.SetMapMode(...) // dc.DPtoLP(&ptRet);//DP->LP进行转换 return ptRet; } 在图32_g1中以蓝线标记的是屏幕区域,红线标记的客户区域。利用ScreenToClient,ClientToScreen可以将坐标在这两个区域间转换。 在视中接收键盘输入: 键盘消息有三个:键盘被按下/松开,输入字符。其中输入字符相当于直接得到用户输入的字符这在不需要处理按键细节时使用,而键盘被按下/松开在按键状态改变时发送。 WM_CHAR对应的函数为OnChar( UINT nChar, UINT nRepCnt, UINT nFlags ),其中nChar为被按下的字符,nRepCnt表明在长时间为松开时相当于的按键次数,nFlags中的不同位代表不同的含义,在这里一般不使用。 WM_KEYDOWN/WM_KEYUP所对应的函数为OnKeyDown/OnKeyUp( UINT nChar, UINT nRepCnt, UINT nFlags )nChar代表按键的虚拟码值,如VK_ALT为ALT键,VK_CONTROL为Ctrl键。nFlags各位的含义如下: Value Description 0? Scan code (OEM-dependent value). 8 Extended key, such as a function key or a key on the numeric keypad (1 if it is an extended key). 9?0 Not used. 11?2 Used internally by Windows. 13 Context code (1 if the ALT key is held down while the key is pressed; otherwise 0). 14 Previous key state (1 if the key is down before the call, 0 if the key is up). 15 Transition state (1 if the key is being released, 0 if the key is being pressed). 3.3 使用菜单 利用菜单接受用户命令是一中很简单的交互方法,同时也是一种很有效的方法。通常菜单作为一中资源存储在文件中,因此我们可以在设计时就利用资源编辑器设计好一个菜单。关于使用VC设计菜单我就不再多讲了,但你在编写菜单时应该尽量在属性对话框的底部提示(Prompt)处输入文字,这虽然不是必要的,但MFC在有状态栏和工具条的情况下会使用该文字,文字的格式为“状态栏出说明\n工具条提示”。 图33_g1 我们要面临的任务是如何知道用户何时选择了菜单,他选的是什么菜单项。当用户选择了一个有效的菜单项时系统会向应用发送一个WM_COMMAND消息,在消息的参数中表明来源。在MFC中我们只需要进行一次映射,将某一菜单ID映射到一处理函数,图33_g2。在这里我们在CView的派生类中处理菜单消息,同时我对同一ID设置两个消息映射,接下来将这两种映射的作用。 图33_g2 ON_COMMAND 映射的作用为在用户选择该菜单时调用指定的处理函数。如:ON_COMMAND(IDM_COMMAND1, OnCommand1)会使菜单被选择时调用OnCommand1成员函数。 ON_UPDATE_COMMAND_UI(IDM_COMMAND1, OnUpdateCommand1) 映射的作用是在菜单被显示时通过调用指定的函数来进行确定其状态。在这个处理函数中你可以设置菜单的允许/禁止状态,其显示字符串是什么,是否在前面打钩。函数的参数为CCmdUI* pCmdUI,CCmdUI是MFC专门为更新命令提供的一个类,你可以调用 • Enable 设置允许/禁止状态 • SetCheck 设置是否在前面打钩 • SetText 设置文字 下面我讲解一个例子:我在CView派生类中有一个变量m_fSelected,并且在视中处理两个菜单的消息,当IDM_COMMAND1被选时,对m_fSelected进行逻辑非操作,当IDM_COMMAND2被选中时出一提示;同时IDM_COMMAND1根据m_fSelected决定菜单显示的文字和是否在前面打上检查符号,IDM_COMMAND2根据m_fSelected的值决定菜单的允许/禁止状态。下面是代码和说明:下载示例代码 17K void CMenuDView::OnCommand1() { m_fSelected=!m_fSelected; TRACE("command1 selected\n"); } void CMenuDView::OnUpdateCommand1(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_fSelected);//决定检查状态 pCmdUI->SetText(m_fSelected?"当前被选中":"当前未被选中");//决定所显示的文字 } void CMenuDView::OnUpdateCommand2(CCmdUI* pCmdUI) {//决定是否为允许 pCmdUI->Enable(m_fSelected); } void CMenuDView::OnCommand2() {//选中时给出提示 AfxMessageBox("你选了command2"); } 接下来再讲一些通过代码操纵菜单的方法,在MFC中有一个类CMenu用来处理和菜单有关的功能。在生成一个CMenu对象时你需要从资源中装如菜单,通过调用BOOL CMenu::LoadMenu( UINT nIDResource )进行装入,然后你就可以对菜单进行动态的修改,所涉及到的函数有: • CMenu* GetSubMenu( int nPos ) 一位置得到子菜单的指针,因为一个CMenu对象只能表示一个弹出菜单,如果菜单中的某一项也为弹出菜单,就需要通过该函数获取指针。 • BOOL AppendMenu( UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL ) 在末尾添加一项,nFlag为MF_SEPARATOR表示增加一个分隔条,这样其他两个参数将会被忽略;为MF_STRING表示添加一个菜单项uIDNewItem为该菜单的ID命令值;为MF_POPUP表示添加一个弹出菜单项,这时uIDNewItem为另一菜单的句柄HMENU。lpszNewItem为菜单文字说明。 • BOOL InsertMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL )用于在指定位置插入一菜单,位置由变量nPosition指明。如果nFlags包含MF_BYPOSITION则表明插入在nPosition位置,如果包含MF_BYCOMMAND表示插入在命令ID为nPosition的菜单处。 • BOOL ModifyMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem = 0, LPCTSTR lpszNewItem = NULL )用于修改某一位置的菜单,如果nFlags包含MF_BYPOSITION则表明修改nPosition位置的菜单,如果包含MF_BYCOMMAND表示修改命令ID为nPosition处的菜单。 • BOOL RemoveMenu( UINT nPosition, UINT nFlags )用于删除某一位置的菜单。如果nFlags包含MF_BYPOSITION则表明删除nPosition位置的菜单,如果包含MF_BYCOMMAND表示删除命令ID为nPosition处的菜单。 • BOOL AppendMenu( UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp ) 和 BOOL InsertMenu( UINT nPosition, UINT nFlags, UINT nIDNewItem, const CBitmap* pBmp )可以添加一位图菜单,但这样的菜单在选中时只是反色显示,并不美观。 视图中是没有菜单的,在框架窗口中才有,所以只有用AfxGetApp()->m_pMainWnd->GetMenu()才能得到应用的菜单指针。 最后我讲一下如何在程序中弹出一个菜单,你必须先装入一个菜单资源,你必需得到一个弹出菜单的指针然后调用BOOL TrackPopupMenu( UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect = NULL )弹出菜单,你需要指定(x,y)为菜单弹出的位置,pWnd为接收命令消息的窗口指针。下面有一段代码说明方法,下载示例代码 17K。当然为了处理消息你应该在pWnd指明的窗口中对菜单命令消息进行映射。 CMenu menu; menu.LoadMenu(IDR_POPUP); CMenu* pM=menu.GetSubMenu(0); CPoint pt; GetCursorPos(&pt); pM->TrackPopupMenu(TPM_LEFTALIGN,pt.x,pt.y,this); 另一种做法是通过CMenu::CreatePopupMenu()建立一个弹出菜单,然后使用TrackPopupMenu弹出菜单。使用CreatePopupMenu创建的菜单也可以将其作为一个弹出项添加另一个菜单中。下面的伪代码演示了如何创建一个弹出菜单并进行修改后弹出: CMenu menu1,menu2; menu1.CreatePopupMenu menu1.InsertMenu(1) menu1.InsertMenu(2) menu1.InsertMenu(3) menu2.CreatePopupMenu menu2.AppendMenu(MF_POPUP,1,menu1.Detach()) 将弹出菜单加入 or InsertMenu... menu2.InsertMenu("string desc"); menu.TrackPopupMenu(...) 3.4 文档,视,框架之间相互作用 一般来说用户的输入/输出基本都是通过视进行,但一些例外的情况下可能需要和框架直接发生作用,而在多视的情况下如何在视之间传递数据。 在使用菜单时大家会发现当一个菜单没有进行映射处理时为禁止状态,在多视的情况下菜单的状态和处理映射是和当前活动视相联系的,这样MFC可以保证视能正确的接收到各种消息,但有时候也会产生不便。有一个解决办法就是在框架中对消息进行处理,这样也可以保证当前文档可以通过框架得到当前消息。 在用户进行输入后如何使视的状态得到更新?这个问题在一个文档对应一个视图时是不存在的,但是现在有一个文档对应了两个视图,当在一个视上进行了输入时如何保证另一个视也得到通知呢?MFC的做法是利用文档来处理的,因为文档管理着当前和它联系的视,由它来通知各个视是最合适的。让我们同时看两个函数: • void CView::OnUpdate( CView* pSender, LPARAM lHint, CObject* pHint ) • void CDocument::UpdateAllViews( CView* pSender, LPARAM lHint = 0L, CObject* pHint = NULL ) 当文档的UpdateAllViews被调用时和此文档相关的所有视的OnUpdate都会被调用,而参数lHint和pHint都会被传递。这样一来发生改变视就可以通知其他的兄弟了。那么还有一个问题:如何在OnUpdate中知道是那个视图发生了改变呢,这就可以利用pHint参数,只要调用者将this指针赋值给参数就可以了,当然完全可以利用该参数传递更复杂的结构。 视的初始化,当一个文档被打开或是新建一个文档时视图的CView::OnInitialUpdate()会被调用,你可以通过重载该函数对视进行初始化,并在结束前调用父类的OnInitialUpdate,因为这样可以保证OnUpdate会被调用。 文档中内容的清除,当文档被关闭时(比如退出或是新建前上一个文档清除)void CDocument::DeleteContents ()会被调用,你可以通过重载该函数来进行清理工作。 在单文档结构中上面两点尤其重要,因为软件运行文档对象和视对象只会被产生并删除一次。所以应该将上面两点和C++对象构造和构析分清楚。 最后将一下文档模板(DocTemplate)的作用,文档模板分为两类单文档模板和多文档模板,分别由CSingleDocTemplate和CMultiDocTemplate表示,模板的作用在于记录文档,视,框架之间的对应关系。还有一点就是模板可以记录应用程序可以打开的文件的类型,当打开文件时会根据文档模板中的信息选择正确的文档和视。模板是一个比较抽想的概念,一般来说是不需要我们直接进行操作的。 当使用者通过视修改了数据时,应该调用GetDocument()->SetModifiedFlag(TRUE)通知文档数据已经被更新,这样在关闭文档时会自动询问用户是否保存数据。 好象这一节讲的有些乱,大家看后有什么想法和问题请在VCHelp论坛上留言,我会尽快回复并且会对本节内容重新整理和修改。 3.5 利用序列化进行文件读写 在很多应用中我们需要对数据进行保存,或是从介质上读取数据,这就涉及到文件的操作。我们可以利用各种文件存取方法完成这些工作,但MFC中也提供了一种读写文件的简单方法——“序列化”。序列化机制通过更高层次的接口功能向开发者提供了更利于使用和透明于字节流的文件操纵方法,举一个例来讲你可以将一个字串写入文件而不需要理会具体长度,读出时也是一样。你甚至可以对字符串数组进行操作。在MFC提供的可自动分配内存的类的支持下你可以更轻松的读/写数据。你也可以根据需要编写你自己的具有序列化功能的类。 序列化在最低的层次上应该被需要序列化的类支持,也就是说如果你需要对一个类进行序列化,那么这个类必须支持序列化。当通过序列化进行文件读写时你只需要该类的序列化函数就可以了。 怎样使类具有序列化功能呢?你需要以下的工作: • 该类从CObject派生。 • 在类声明中包括DECLARE_SERIAL宏定义。 • 提供一个缺省的构造函数。 • 在类中实现Serialze函数 • 使用IMPLEMENT_SERIAL指明类名和版本号 下面的代码建立了一个简单身份证记录的类,同时也能够支持序列化。 in H struct strPID { char szName[10]; char szID[16]; struct strPID* pNext; }; class CAllPID : public CObject { public: DECLARE_SERIAL(CAllPID) CAllPID(); ~CAllPID(); public:// 序列化相关 struct strPID* pHead; //其他的成员函数 void Serialize(CArchive& ar); }; in CPP IMPLEMENT_SERIAL(CAllPID,CObject,1) // version is 1,版本用于读数据时的检测 void CAllPID::Serialize(CArchive& ar) { int iTotal; if(ar.IsStoring()) {//保存数据 iTotal=GetTotalID();//得到链表中的记录数量 arr<26;i++) ar<>iTotal; for(int i=0;i26;j++) ar>>*(((BYTE*)pID)+j);//读一个strPID中所有的数据 //修改链表 } } } 当然上面的代码很不完整,但已经可以说明问题。这样CAllPID就是一个可以支持序列化的类,并且可以根据记录的数量动态分配内存。在序列化中我们使用了CArchive类,该类用于在序列化时提供读写支持,它重载了<>运算符号,并且提供Read和Write函数对数据进行读写。 下面看看如何在文档中使用序列化功能,你只需要修改文档类的Serialize(CArchive& ar)函数,并调用各个进行序列化的类的Serial进行数据读写就可以了。当然你也可以在文档类的内部进行数据读写,下面的代码利用序列化功能读写数据: class CYourDoc : public CDocument { void Serialize(CArchive& ar); CString m_szDesc; CAllPID m_allPID; ...... } void CYourDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) {//由于CString对CArchive定义了<>操作符号,所以可以直接利用>>和<< ar<>m_szDesc; } m_allPID.Serialize(ar);//调用数据类的序列化函数 3.6 MFC中所提供的各种视类介绍 MFC中提供了丰富的视类供开发者使用,下面对各个类进行介绍: CView类是最基本的视类只支持最基本的操作。 CScrollView类提供了滚动的功能,你可以利用void CScrollView::SetScrollSizes( int nMapMode, SIZE sizeTotal, const SIZE& sizePage = sizeDefault, const SIZE& sizeLine = sizeDefault )设置滚动尺寸,和坐标映射模式。但是在绘图和接收用户输入时需要对坐标进行转换。请参见3.2 接收用户输入。 CFormView类提供用户在资源文件中定义界面的能力,并可以将子窗口和变量进行绑定。通过UpdateData函数让数据在变量和子窗口间交换。 CTreeView类利用TreeCtrl界面作为视界面,通过调用CTreeCtrl& CTreeView::GetTreeCtrl( ) const得到CTreeCtrl的引用。 CListView类利用ListCtrl界面作为视界面,通过调用CTreeCtrl& CTreeView::GetTreeCtrl( ) const得到CListCtrl的引用。 CEditView类利用Edit接收用户输入,它具有输入框的一切功能。通过调用CEdit& CEditView::GetEditCtrl( ) const得到Edit&的引用。void CEditView::SetPrinterFont( CFont* pFont )可以设置打印字体。 CRichEditView类作为Rich Text Edit(富文本输入)的视类,提供了可以按照格式显示文本的能力,在使用时需要CRichEditDoc的支持。 第四章 窗口控件 4.1 Button 按钮窗口(控件)在MFC中使用CButton表示,CButton包含了三种样式的按钮,Push Button,Check Box,Radio Box。所以在利用CButton对象生成按钮窗口时需要指明按钮的风格。 创建按钮:BOOL CButton::Create( LPCTSTR lpszCaption, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID );其中lpszCaption是按钮上显示的文字,dwStyle为按钮风格,除了Windows风格可以使用外(如WS_CHILD|WS_VISUBLE|WS_BORDER)还有按钮专用的一些风格。 • BS_AUTOCHECKBOX 检查框,按钮的状态会自动改变 Same as a check box, except that a check mark appears in the check box when the user selects the box; the check mark disappears the next time the user selects the box. • BS_AUTORADIOBUTTON 圆形选择按钮,按钮的状态会自动改变 Same as a radio button, except that when the user selects it, the button automatically highlights itself and removes the selection from any other radio buttons with the same style in the same group. • BS_AUTO3STATE 允许按钮有三种状态即:选中,未选中,未定 Same as a three-state check box, except that the box changes its state when the user selects it. • BS_CHECKBOX 检查框 Creates a small square that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style). • BS_DEFPUSHBUTTON 默认普通按钮 Creates a button that has a heavy black border. The user can select this button by pressing the ENTER key. This style enables the user to quickly select the most likely option (the default option). • BS_LEFTTEXT 左对齐文字 When combined with a radio-button or check-box style, the text appears on the left side of the radio button or check box. • BS_OWNERDRAW 自绘按钮 Creates an owner-drawn button. The framework calls the DrawItem member function when a visual aspect of the button has changed. This style must be set when using the CBitmapButton class. • BS_PUSHBUTTON 普通按钮 Creates a pushbutton that posts a WM_COMMAND message to the owner window when the user selects the button. • BS_RADIOBUTTON 圆形选择按钮 Creates a small circle that has text displayed to its right (unless this style is combined with the BS_LEFTTEXT style). Radio buttons are usually used in groups of related but mutually exclusive choices. • BS_3STATE 允许按钮有三种状态即:选中,未选中,未定 Same as a check box, except that the box can be dimmed as well as checked. The dimmed state typically is used to show that a check box has been disabled. rect为窗口所占据的矩形区域,pParentWnd为父窗口指针,nID为该窗口的ID值。 获取/改变按钮状态:对于检查按钮和圆形按钮可能有两种状态,选中和未选中,如果设置了BS_3STATE或BS_AUTO3STATE风格就可能出现第三种状态:未定,这时按钮显示灰色。通过调用int CButton::GetCheck( ) 得到当前是否被选中,返回0:未选中,1:选中,2:未定。调用void CButton::SetCheck( int nCheck );设置当前选中状态。 处理按钮消息:要处理按钮消息需要在父窗口中进行消息映射,映射宏为ON_BN_CLICKED( id, memberFxn )id为按钮的ID值,就是创建时指定的nID值。处理函数原型为afx_msg void memberFxn( ); 4.2 Static Box 静态文本控件的功能比较简单,可作为显示字符串,图标,位图用。创建一个窗口可以使用成员函数: BOOL CStatic::Create( LPCTSTR lpszText, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID = 0xffff ); 其中dwStyle将指明该窗口的风格,除了子窗口常用的风格WS_CHILD,WS_VISIBLE外,你可以针对静态控件指明专门的风格。 • SS_CENTER,SS_LEFT,SS_RIGHT 指明字符显示的对齐方式。 • SS_GRAYRECT 显示一个灰色的矩形 • SS_NOPREFIX 如果指明该风格,对于字符&将直接显示,否则&将作为转义符,&将不显示而在其后的字符将有下划线,如果需要直接显示&必须使用&&表示。 • SS_BITMAP 显示位图 • SS_ICON 显示图标 • SS_CENTERIMAGE 图象居中显示 控制显示的文本利用成员函数SetWindowText/GetWindowText用于设置/得到当前显示的文本。 控制显示的图标利用成员函数SetIcon/GetIcon用于设置/得到当前显示的图标。 控制显示的位图利用成员函数SetBitmap/GetBitmap用于设置/得到当前显示的位图。下面一段代码演示如何创建一个显示位图的静态窗口并设置位图 CStatic* pstaDis=new CStatic; pstaDis->Create("",WS_CHILD|WS_VISIBLE|SS_BITMAP|SSCENTERIMAGE, CRect(0,0,40,40),pWnd,1); CBitmap bmpLoad; bmpLoad.LoadBitmap(IDB_TEST); pstaDis->SetBitmap(bmpLoad.Detach()); 4.3 Edit Box Edit窗口是用来接收用户输入最常用的一个控件。创建一个输入窗口可以使用成员函数: BOOL CEdit::Create( LPCTSTR lpszText, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID = 0xffff ); 其中dwStyle将指明该窗口的风格,除了子窗口常用的风格WS_CHILD,WS_VISIBLE外,你可以针对输入控件指明专门的风格。 • ES_AUTOHSCROLL,ES_AUTOVSCROLL 指明输入文字超出显示范围时自动滚动。 • ES_CENTER,ES_LEFT,ES_RIGHT 指定对齐方式 • ES_MULTILINE 是否允许多行输入 • ES_PASSWORD 是否为密码输入框,如果指明该风格则输入的文字显示为* • ES_READONLY 是否为只读 • ES_UPPERCASE,ES_LOWERCASE 显示大写/小写字符 控制显示的文本利用成员函数SetWindowText/GetWindowText用于设置/得到当前显示的文本。 通过GetLimitText/SetLimitText可以得到/设置在输入框中输入的字符数量。 由于在输入时用户可能选择某一段文本,所以通过void CEdit::GetSel( int& nStartChar, in
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Menu.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_COMMAND(IDM_TEST, OnTest) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_UPDATE_COMMAND_UI(ID_FILE_NEW, OnUpdateFileNew) ON_COMMAND(IDM_SHOW, OnShow) //}}AFX_MSG_MAP 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 m_bAutoMenuEnable = FALSE; } 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 // be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); /* GetMenu()->GetSubMenu(0)->CheckMenuItem(0, MF_BYPOSITION | MF_CHECKED); GetMenu()->GetSubMenu(0)->CheckMenuItem(ID_FILE_NEW, MF_BYCOMMAND | MF_CHECKED); GetMenu()->GetSubMenu(0)->SetDefaultItem(1,TRUE); GetMenu()->GetSubMenu(0)->SetDefaultItem(ID_FILE_OPEN,FALSE); GetMenu()->GetSubMenu(0)->SetDefaultItem(5,TRUE); CString str; str.Format("x=%d, y=%d",GetSystemMetrics(SM_CXMENUCHECK),GetSystemMetrics(SM_CYMENUCHECK)); MessageBox(str); m_bitmap.LoadBitmap(IDB_BITMAP1); GetMenu()->GetSubMenu(0)->SetMenuItemBitmaps(0,MF_BYPOSITION, &m_bitmap, &m_bitmap); */ GetMenu()->GetSubMenu(0)->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED); SetMenu(NULL); CMenu menu; menu.LoadMenu(IDR_MAINFRAME); SetMenu(&menu); menu.Detach(); 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::OnTest() { // TODO: Add your command handler code here MessageBox("MainFrame Clicked"); } void CMainFrame::OnUpdateEditCut(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here if(2 == pCmdUI->m_nIndex) pCmdUI->Enable(); } void CMainFrame::OnUpdateFileNew(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here // if(ID_FILE_NEW == pCmdUI->m_nID); /* if(0 == pCmdUI->m_nIndex) pCmdUI->Enable(FALSE); */ } void CMainFrame::OnShow() { // TODO: Add your command handler code here MessageBox("Main show"); }
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Menu.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_COMMAND(IDM_TEST, OnTest) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_UPDATE_COMMAND_UI(ID_FILE_NEW, OnUpdateFileNew) ON_COMMAND(IDM_SHOW, OnShow) //}}AFX_MSG_MAP 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 m_bAutoMenuEnable = FALSE; } 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 // be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); /* GetMenu()->GetSubMenu(0)->CheckMenuItem(0, MF_BYPOSITION | MF_CHECKED); GetMenu()->GetSubMenu(0)->CheckMenuItem(ID_FILE_NEW, MF_BYCOMMAND | MF_CHECKED); GetMenu()->GetSubMenu(0)->SetDefaultItem(1,TRUE); GetMenu()->GetSubMenu(0)->SetDefaultItem(ID_FILE_OPEN,FALSE); GetMenu()->GetSubMenu(0)->SetDefaultItem(5,TRUE); CString str; str.Format("x=%d, y=%d",GetSystemMetrics(SM_CXMENUCHECK),GetSystemMetrics(SM_CYMENUCHECK)); MessageBox(str); m_bitmap.LoadBitmap(IDB_BITMAP1); GetMenu()->GetSubMenu(0)->SetMenuItemBitmaps(0,MF_BYPOSITION, &m_bitmap, &m_bitmap); */ GetMenu()->GetSubMenu(0)->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED); SetMenu(NULL); CMenu menu; menu.LoadMenu(IDR_MAINFRAME); SetMenu(&menu); menu.Detach(); 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::OnTest() { // TODO: Add your command handler code here MessageBox("MainFrame Clicked"); } void CMainFrame::OnUpdateEditCut(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here if(2 == pCmdUI->m_nIndex) pCmdUI->Enable(); } void CMainFrame::OnUpdateFileNew(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here // if(ID_FILE_NEW == pCmdUI->m_nID); /* if(0 == pCmdUI->m_nIndex) pCmdUI->Enable(FALSE); */ } void CMainFrame::OnShow() { // TODO: Add your command handler code here MessageBox("Main show"); }
VC++深入了解源代码2 // MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "Menu.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() ON_COMMAND(IDM_TEST, OnTest) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_UPDATE_COMMAND_UI(ID_FILE_NEW, OnUpdateFileNew) ON_COMMAND(IDM_SHOW, OnShow) //}}AFX_MSG_MAP 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 m_bAutoMenuEnable = FALSE; } 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 // be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); /* GetMenu()->GetSubMenu(0)->CheckMenuItem(0, MF_BYPOSITION | MF_CHECKED); GetMenu()->GetSubMenu(0)->CheckMenuItem(ID_FILE_NEW, MF_BYCOMMAND | MF_CHECKED); GetMenu()->GetSubMenu(0)->SetDefaultItem(1,TRUE); GetMenu()->GetSubMenu(0)->SetDefaultItem(ID_FILE_OPEN,FALSE); GetMenu()->GetSubMenu(0)->SetDefaultItem(5,TRUE); CString str; str.Format("x=%d, y=%d",GetSystemMetrics(SM_CXMENUCHECK),GetSystemMetrics(SM_CYMENUCHECK)); MessageBox(str); m_bitmap.LoadBitmap(IDB_BITMAP1); GetMenu()->GetSubMenu(0)->SetMenuItemBitmaps(0,MF_BYPOSITION, &m_bitmap, &m_bitmap); */ GetMenu()->GetSubMenu(0)->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED); SetMenu(NULL); CMenu menu; menu.LoadMenu(IDR_MAINFRAME); SetMenu(&menu); menu.Detach(); 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::OnTest() { // TODO: Add your command handler code here MessageBox("MainFrame Clicked"); } void CMainFrame::OnUpdateEditCut(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here if(2 == pCmdUI->m_nIndex) pCmdUI->Enable(); } void CMainFrame::OnUpdateFileNew(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here // if(ID_FILE_NEW == pCmdUI->m_nID); /* if(0 == pCmdUI->m_nIndex) pCmdUI->Enable(FALSE); */ } void CMainFrame::OnShow() { // TODO: Add your command handler code here MessageBox("Main show"); }

16,467

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧