CLabel Code学习

 

关于 SS_LEFTNOWORDWRAP
 
SS_LEFTNOWORDWRAP属性是用来关闭文本回绕的。它会强迫使用左对齐属性,多余的文字被剪裁。
关于 SS_OWNERDRAW
Specifies that the owner of the static control is responsible for drawing the control. The owner window receives a WM_DRAWITEM message whenever the control needs to be drawn.
关于GetSysColor
COLORREF m_crText = GetSysColor(COLOR_WINDOWTEXT);
DWORD GetSysColor( int nIndex   // display element );
The GetSysColor function retrieves the current color of the specified display element. Display elements are the parts of a window and the display that appear on the system display screen.
关于宏定义
#define INT_DEFAULT_SHIFT_PIXEL 5
class CLabel : public CStatic
{
int m_nShiftPixel;
}
CLabel::CLabel()
{
m_nShiftPixel = INT_DEFAULT_SHIFT_PIXEL;
}
关于 CreateSolidBrush
HBRUSH m_hwndBrush = ::CreateSolidBrush(GetSysColor(COLOR_3DFACE));
HBRUSH CreateSolidBrush( COLORREF crColor brush color value );   //
(1)A solid brush is a bitmap that the system uses to paint the interiors of filled shapes. The CreateSolidBrush function creates a logical brush that has the specified solid color.
(2)After an application creates a brush by calling CreateSolidBrush, it can select that brush into any device context by calling the SelectObject function.
(3 )To paint with a system color brush, an application should use GetSysColorBrush(nIndex) instead of CreateSolidBrush(GetSysColor(nIndex)), because GetSysColorBrush returns a cached brush (instead of allocating a new one). System color brushes track changes in system colors. In other words, when the user changes a system color, the associated system color brush automatically changes to the new color. System color brushes are owned by the system and must not be destroyed.
关于DeleteObject
DeleteObject(m_hwndBrush);
BOOL DeleteObject(HGDIOBJ hObject   // handle to graphic object);
The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system resources associated with the object. After the object is deleted, the specified handle is no longer valid.
(1 )If the function succeeds, the return value is nonzero.If the specified handle is not valid or is currently selected into a DC, the return value is zero.
(2 )Do not delete a drawing object (pen or brush) while it is still selected into a DC.When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.
                  关于 CFont.DeleteObject();
CFont m_font; m_font.DeleteObject();
BOOL CFont::DeleteObject( );
Deletes the attached Windows GDI object from memory by freeing all system storage associated with the Windows GDI object.The storage associated with the CGdiObject object is not affected by this call.
(1)An application should not call DeleteObject on a CGdiObject object that is currently selected into a device context.
(2)When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.
关于CWnd::GetSafeHwnd
HWND CWnd::GetSafeHwnd( ) const;
Returns the window handle for a window. Returns NULL if the CWnd is not attached to a window or if it is used with a NULL CWnd pointer.
 
Reconstruct Font
LOGFONT m_lf;
CFont m_font;
 
m_font.DeleteObject();
BOOL bCreated = m_font.CreateFontIndirect(&m_lf);
ASSERT(bCreated);
 
关于CFont::CreateFontIndirect
BOOL CFont::CreateFontIndirect(const LOGFONT* lpLogFont );
Initializes a CFont object with the characteristics given in a LOGFONT structure pointed to by lpLogFont.The font can subsequently be selected as the current font for any device.When the font is selected by using the CDC::SelectObject member function, the GDI's font mapper attempts to match the logical font with an existing physical font. If it fails to find an exact match for the logical font, it provides an alternative whose characteristics match as many of the requested characteristics as possible.When you finish with the CFont object created by the CreateFontIndirect function, first select the font out of the device context, then delete the CFont object.
                     关于CWnd::GetWindowText
void GetClientRect(LPRECT lpRect) const;
例:CRect rc; GetClientRect(rc);
Copies the client coordinates of the CWnd client area into the structure pointed to by lpRect.
lpRect points to a RECT structure or a CRect object to receive the client coordinates. The left and top members will be 0. The right and bottom members will contain the width and height of the window. The client coordinates specify the upper-left and lower-right corners of the client area. Since client coordinates are relative to the upper-left corners of the CWnd client area, the coordinates of the upper-left corner are (0,0).
CWnd::GetWindowText
int CWnd::GetWindowText(LPTSTR lpszStringBuf, int nMaxCount) const;
void CWnd::GetWindowText(CString& rString) const;
Copies the CWnd caption title (if it has one) into the buffer pointed to by lpszStringBuf or into the destination string rString.
 
关于CpaintDC
class CPaintDC : public CDC
The CPaintDC class is a device-context class derived from CDC. It performs a CWnd::BeginPaint at construction time and CWnd::EndPaint at destruction time. A CPaintDC object can only be used when responding to a WM_PAINT message, usually in your OnPaint message-handler member function.
explicit CPaintDC(CWnd* pWnd );
 
// Get a dc for a CWnd pointer.
CPaintDC dc(pWnd);
// Get a dc for a HWND.
CPaintDC dc2(CWnd::FromHandle(hWnd));
Constructs a CPaintDC object, prepares the application window for painting, and stores the PAINTSTRUCT structure in the m_ps member variable.
 
关于CWnd::GetParent
CWnd* CWnd::GetParent( ) const;
Call this function to get a pointer to a child window's parent window (if any).Identifies the parent window if the member function is successful. Otherwise, the value is NULL, which indicates an error or no parent window. The returned pointer may be temporary and should not be stored for later use.The GetParent function returns a pointer the immediate parent. In contrast, the GetParentOwner function returns a pointer to the most immediate parent or owner window that is not a child window (does not have the WS_CHILD style). If you have a child window within a child window GetParent and GetParentOwner return different results. 
Get Parent Window Color
CWnd *pParent = GetParent();
HBRUSH hParentBrush = (HBRUSH)::SendMessage(pParent->GetSafeHwnd(),
        WM_CTLCOLOR, CTLCOLOR_DLG, (long)pParent);
                    
First Fill The Rect with The Parent Color
pDCMem->FillRect(rc, CBrush::FromHandle(hParentBrush));
//first fill the rect with the parent color, then draw on it.
关于Cbrush:: FromHandle
static CBrush* PASCAL Cbrush::FromHandle(HBRUSH hBrush);
Returns a pointer to a CBrush object when given a handle to a Windows HBRUSH object. If a CBrush object is not already attached to the handle, a temporary CBrush object is created and attached. This temporary CBrush object is valid only until the next time the application has idle time in its event loop. At this time, all temporary graphic objects are deleted. In other words, the temporary object is valid only during the processing of one window message.
关于CDC::CreateCompatibleDC
CPaintDC dc(this); // device context for painting
CDC* pDCMem = new CDC;
pDCMem->CreateCompatibleDC(&dc);
Creates a memory device context that is compatible with the device specified by pDC.(pDC :A pointer to a device context. If pDC is NULL, the function creates a memory device context that is compatible with the system display.) A memory device context is a block of memory that represents a display surface. It can be used to prepare images in memory before copying them to the actual device surface of the compatible device.When a memory device context is created, GDI automatically selects a 1-by-1 monochrome stock bitmap for it. GDI output functions can be used with a memory device context only if a bitmap has been created and selected into that context.This function can only be used to create compatible device contexts for devices that support raster operations. See the CDC::BitBlt member function for information regarding bit-block transfers between device contexts. To determine whether a device context supports raster operations, see the RC_BITBLT raster capability in the member function CDC::GetDeviceCaps.
关于CBitmap:: CreateCompatibleBitmap 
CPaintDC dc(this); // device context for painting
CRect rc;
GetClientRect(&rc);
CBitmap bmp;
CBitmap* pOldBitmap = NULL;
bmp.CreateCompatibleBitmap(&dc,rc.Width(),rc.Height());
pOldBitmap = pDCMem->SelectObject(&bmp);
Initializes a bitmap that is compatible with the device specified by pDC.
The bitmap has the same number of color planes or the same bits-per-pixel format as the specified device context. It can be selected as the current bitmap for any memory device that is compatible with the one specified by pDC.If pDC is a memory device context, the bitmap returned has the same format as the currently selected bitmap in that device context. A "memory device context" is a block of memory that represents a display surface. It can be used to prepare images in memory before copying them to the actual display surface of the compatible device.
When a memory device context is created, GDI automatically selects a monochrome stock bitmap for it.Since a color memory device context can have either color or monochrome bitmaps selected, the format of the bitmap returned by the CreateCompatibleBitmap function is not always the same; however, the format of a compatible bitmap for a nonmemory device context is always in the format of the device.When you finish with the CBitmap object created with the CreateCompatibleBitmap function, first select the bitmap out of the device context, then delete the CBitmap object.
关于CDC::SetBkMode
int CDC::SetBkMode(int nBkMode);
(1)Sets the background mode.
(2)nBkMode Specifies the mode to be set. This parameter can be either of the following values:
A.OPAQUE   Background is filled with the current background color before the text, hatched brush, or pen is drawn. This is the default background mode.
B.TRANSPARENT   Background is not changed before drawing. The background mode defines whether the system removes existing background colors on the drawing surface before drawing text, hatched brushes, or any pen style that is not a solid line.
关于CDC::SetTextColor
virtual COLORREF CDC::SetTextColor(COLORREF crColor);
Sets the text color to the specified color.The system will use this text color when writing text to this device context and also when converting bitmaps between color and monochrome device contexts. If the device cannot represent the specified color, the system sets the text color to the nearest physical color. The background color for a character is specified by the SetBkColor and SetBkMode member functions.
关于CDC::SelectObject
CPen* SelectObject(CPen* pPen);
CBrush* SelectObject(CBrush* pBrush);
virtual CFont* SelectObject(CFont* pFont);
CBitmap* SelectObject(CBitmap* pBitmap);
int SelectObject(CRgn* pRgn);
CGdiObject* SelectObject(CGdiObject* pObject);
Selects an object into the device context
An application can select a bitmap into memory device contexts only and into only one memory device context at a time. The format of the bitmap must either be monochrome or compatible with the device context; if it is not, SelectObject returns an error.
关于CGdiObject::Attach
BOOL CGdiObject::Attach(HGDIOBJ hObject);
Attaches a Windows GDI object to a CGdiObject object.
hObject :A HANDLE to a Windows GDI object (for example, HPEN or HBRUSH).
 
关于CGdiObject::Detach
HGDIOBJ CGdiObject::Detach( );
Detaches a Windows GDI object from a CGdiObject object and returns a handle to the Windows GDI object.
 
关于CDC::FillRect
void CDC::FillRect(LPCRECT lpRect, CBrush* pBrush);
The function fills the complete rectangle, including the left and top borders, but it does not fill the right and bottom borders. The brush needs to either be created using the CBrush member functions CreateHatchBrush, CreatePatternBrush, and CreateSolidBrush, or retrieved by the GetStockObject Windows function. FillRect is similar to CDC::FillSolidRect; however, FillRect takes a brush and therefore can be used to fill a rectangle with a solid color, a dithered color, hatched brushes, or a pattern. FillSolidRect uses only solid colors (indicated by a COLORREF parameter). FillRect usually is slower than FillSolidRect. 
关于GetRValue,GetGValue,GetBValue
BYTE GetRValue (DWORD rgb // RGB value);
The GetRValue macro retrieves an intensity value for the red component of a red, green, blue (RGB) value. 
关于max
max( value1, // low-order word  value2 // high-order word);
The max macro compares two values and returns the larger one. The data type can be any numeric data type, signed or unsigned. The data type of the arguments and the return value is the same.
关于CDC::SelectStockObject
virtual CDC::CGdiObject* SelectStockObject(int nIndex );
Selects a CGdiObject object that corresponds to one of the predefined stock pens, brushes, or fonts.
nIndex  specifies the kind of stock object desired. It can be one of the following values:
·         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. // 无框线绘制
例如
pDC->SelectStockObject(NULL_PEN);
for (int i = 0; i < nSegments; i++, nR += ndR, nG += ndG, nB += ndB)
{
// Use special code for the last segment to avoid any problems with integer
// division.
if (i == (nSegments - 1))
      nRight = pRect->right;
else
      nRight = nLeft + nCX;
cr = RGB(nR / 256, nG / 256, nB / 256);
                 
   {
      CBrush brFill(cr);
      CRect rect(nLeft, pRect->top, nRight + 1, pRect->bottom);
      pDC->FillRect(rect, &brFill);
}
// Reset the left side of the drawing rectangle.
      nLeft = nRight;
}
·         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.
关于Cbrush
class CBrush : public CGdiObject
The CBrush class encapsulates a Windows graphics device interface (GDI) brush. To use a CBrush object, construct a CBrush object and pass it to any CDC member function that requires a brush.Brushes can be solid, hatched, or patterned.
CBrush( );
CBrush(COLORREF crColor );
CBrush(int nIndex, COLORREF crColor);
explicit CBrush(CBitmap* pBitmap);
Constructs a CBrush object.
 
关于CPen
class CPen : public CGdiObject
The CPen class encapsulates a Windows graphics device interface (GDI) pen.
CPen( );
CPen(int nPenStyle, int nWidth, COLORREF crColor );
CPen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, 
               int nStyleCount = 0, const DWORD* lpStyle = NULL );
Constructs a CPen object.
nPenStyle specifies the pen style. This parameter in the first version of the constructor can be one of the following values:
·               PS_SOLID   Creates a solid pen.
·               PS_DASH   Creates a dashed pen. Valid only when the pen width is 1 or less, in device units.
·               PS_DOT   Creates a dotted pen. Valid only when the pen width is 1 or less, in device units.
·               PS_DASHDOT   Creates a pen with alternating dashes and dots. Valid only when the pen width is 1 or less, in device units.
·               PS_DASHDOTDOT   Creates a pen with alternating dashes and double dots. Valid only when the pen width is 1 or less, in device units.
·               PS_NULL   Creates a null pen.
·               PS_INSIDEFRAME   Creates a pen that draws a line inside the frame of closed shapes produced by the Windows GDI output functions that specify a bounding rectangle (for example, the Ellipse, Rectangle, RoundRect, Pie, and Chord member functions). When this style is used with Windows GDI output functions that do not specify a bounding rectangle (for example, the LineTo member function), the drawing area of the pen is not limited by a frame.
The second version of the CPen constructor specifies a combination of type, style, end cap, and join attributes. The values from each category should be combined by using the bitwise OR operator (|). The pen type can be one of the following values:
·               PS_GEOMETRIC   Creates a geometric pen.
·               PS_COSMETIC   Creates a cosmetic pen.
The second version of the CPen constructor adds the following pen styles for nPenStyle:
·               PS_ALTERNATE   Creates a pen that sets every other pixel. (This style is applicable only for cosmetic pens.)
·               PS_USERSTYLE   Creates a pen that uses a styling array supplied by the user.
The end cap can be one of the following values:
·               PS_ENDCAP_ROUND   End caps are round.
·               PS_ENDCAP_SQUARE   End caps are square.
·               PS_ENDCAP_FLAT   End caps are flat.
The join can be one of the following values:
·               PS_JOIN_BEVEL   Joins are beveled.
·               PS_JOIN_MITER   Joins are mitered when they are within the current limit set by the SetMiterLimit function. If the join exceeds this limit, it is beveled.
·               PS_JOIN_ROUND   Joins are round.
nWidth specifies the width of the pen.
·               For the first version of the constructor, if this value is 0, the width in device units is always 1 pixel, regardless of the mapping mode.
·               For the second version of the constructor, if nPenStyle is PS_GEOMETRIC, the width is given in logical units. If nPenStyle is PS_COSMETIC, the width must be set to 1.
crColor contains an RGB color for the pen.
pLogBrush points to a LOGBRUSH structure. If nPenStyle is PS_COSMETIC, the lbColor member of the LOGBRUSH structure specifies the color of the pen and the lbStyle member of the LOGBRUSH structure must be set to BS_SOLID. If nPenStyle is PS_GEOMETRIC, all members must be used to specify the brush attributes of the pen.
nStyleCount specifies the length, in doubleword units, of the lpStyle array. This value must be zero if nPenStyle is not PS_USERSTYLE.
lpStyle points to an array of doubleword values. The first value specifies the length of the first dash in a user-defined style, the second value specifies the length of the first space, and so on. This pointer must be NULL if nPenStyle is not PS_USERSTYLE.
Remarks
If you use the constructor with no arguments, you must initialize the resulting CPen object with the CreatePen, CreatePenIndirect, or CreateStockObject member functions.
If you use the constructor that takes arguments, then no further initialization is necessary. The constructor with arguments can throw an exception if errors are encountered, while the constructor with no arguments will always succeed.
关于CDC::RoundRect
BOOL RoundRect(int x1, int y1, int x2, int y2, int x3, int y3 );
BOOL RoundRect(LPCRECT lpRect, POINT point );
例:CRect rc; GetClientRect(rc); pDCMem->RoundRect(rc, CPoint(20, 20));
Draws a rectangle with rounded corners using the current pen. The interior of the rectangle is filled using the current brush.
x1 specifies the x-coordinate of the upper-left corner of the rectangle (in logical units).
y1 specifies the y-coordinate of the upper-left corner of the rectangle (in logical units).
x2 specifies the x-coordinate of the lower-right corner of the rectangle (in logical units).
y2 specifies the y-coordinate of the lower-right corner of the rectangle (in logical units).
x3 specifies the width of the ellipse used to draw the rounded corners (in logical units).
y3 specifies the height of the ellipse used to draw the rounded corners (in logical units).
lpRect specifies the bounding rectangle in logical units. You can pass either a CRect object or a pointer to a RECT structure for this parameter.
point  The x-coordinate of point specifies the width of the ellipse to draw the rounded corners (in logical units). The y-coordinate of point specifies the height of the ellipse to draw the rounded corners (in logical units). You can pass either a POINT structure or a CPoint object for this parameter.
                                    关于LOGBRUSH
typedef struct tagLOGBRUSH {
 UINT      lbStyle;
  COLORREF lbColor;
 LONG      lbHatch;
} LOGBRUSH, *PLOGBRUSH;
The LOGBRUSH structure defines the style, color, and pattern of a physical brush. It is used by the CreateBrushIndirect and ExtCreatePen functions.
 
关于ZeroMemory
VOID ZeroMemory(PVOID Destination, // memory block
              SIZE_T Length       // size of memory block);
The ZeroMemory function fills a block of memory with zeros.
 
关于GetObject
int GetObject(
 HGDIOBJ hgdiobj, // handle to graphics object
 int cbBuffer,     // size of buffer for object information
 LPVOID lpvObject // buffer for object information);
The GetObject function retrieves information for the specified graphics object.
例:LOGBRUSH lb; ZeroMemory(&lb,sizeof(lb));
        if (m_hBackBrush) ::GetObject(m_hBackBrush,sizeof(lb),&lb);
关于CWnd::GetStyle
DWORD CWnd::GetStyle( ) const;
Returns the current window style.
Static Controls Style
Text Styles and Modifiers
The five basic text styles for static controls are:
  • SS_RIGHT
  • SS_LEFT
  • SS_CENTER
  • SS_LEFTNOWORDWRAP
  • SS_SIMPLE
The SS_NOPREFIX style can modify a static control that has any of these text styles. Although SS_NOPREFIX is called a style, it is really a modifier to the text styles.
 
关于SS_CENTERIMAGE
Specifies that, if the bitmap or icon is smaller than the client area of the static control, the rest of the client area is filled with the color of the pixel in the top left corner of the bitmap or icon. If the static control contains a single line of text, the text is centered vertically in the client area of the control.
关于CDC::SetTextAlign
UINT CDC::SetTextAlign(UINT nFlags );
Sets the text-alignment flags.
nFlags specifies text-alignment flags. The flags specify the relationship between a point and a rectangle that bounds the text. The point can be either the current position or coordinates specified by a text-output function. The rectangle that bounds the text is defined by the adjacent character cells in the text string. The nFlags parameter can be one or more flags from the following three categories. Choose only one flag from each category. The first category affects text alignment in the x-direction:
·                     TA_CENTER   Aligns the point with the horizontal center of the bounding rectangle.
·                     TA_LEFT   Aligns the point with the left side of the bounding rectangle. This is the default setting.
·                     TA_RIGHT   Aligns the point with the right side of the bounding rectangle.
The second category affects text alignment in the y-direction:
·                     TA_BASELINE   Aligns the point with the base line of the chosen font.
·                     TA_BOTTOM   Aligns the point with the bottom of the bounding rectangle.
·                     TA_TOP   Aligns the point with the top of the bounding rectangle. This is the default setting.
The third category determines whether the current position is updated when text is written:
·                     TA_NOUPDATECP   Does not update the current position after each call to a text-output function. This is the default setting.
·                     TA_UPDATECP   Updates the current x-position after each call to a text-output function. The new position is at the right side of the bounding rectangle for the text. When this flag is set, the coordinates specified in calls to the TextOut member function are ignored.
Return Value The previous text-alignment setting, if successful. The low-order byte contains the horizontal setting and the high-order byte contains the vertical setting; otherwise 0.
The TextOut and ExtTextOut member functions use these flags when positioning a string of text on a display or device. The flags specify the relationship between a specific point and a rectangle that bounds the text. The coordinates of this point are passed as parameters to the TextOut member function. The rectangle that bounds the text is formed by the adjacent character cells in the text string.
关于GetViewportOrgEx
BOOL GetViewportOrgEx(HDC hdc, // handle to device context
              LPPOINT lpPoint // viewport origin);
The GetViewportOrgEx function retrieves the x-coordinates and y-coordinates of the viewport origin for the specified device context.
SetViewportOrgEx
BOOL SetViewportOrgEx( HDC hdc, // handle to device context
              int X, // new x-coordinate of viewport origin
              int Y, // new y-coordinate of viewport origin
                LPPOINT lpPoint // original viewport origin);
The SetViewportOrgEx function specifies which device point maps to the window origin (0,0).
lpPoint [out] Pointer to a POINT structure that receives the previous viewport origin, in device coordinates. If lpPoint is NULL, this parameter is not used.
Return Values
关于DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
关于DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the lpRect parameter. A carriage return-line feed sequence also breaks the line.
关于DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
关于CDC::TextOut
virtual BOOL CDC::TextOut(int x, int y, LPCTSTR lpszString, int nCount );
BOOL CDC::TextOut( int x, int y, const CString& str );
 
Writes a character string at the specified location using the currently selected font.
Parameters
Character origins are at the upper-left corner of the character cell. By default, the current position is not used or updated by the function.
If an application needs to update the current position when it calls TextOut, the application can call the SetTextAlign member function with nFlags set to TA_UPDATECP. When this flag is set, Windows ignores the x and y parameters on subsequent calls to TextOut, using the current position instead.
关于CRect::DeflateRect
void DeflateRect(int x, int y) throw( );
void DeflateRect(SIZE size ) throw( );
void DeflateRect(LPCRECT lpRect ) throw( );
void DeflateRect(int l, int t, int r, int b) throw( );
DeflateRect deflates CRect by moving its sides toward its center.
To do this, DeflateRect adds units to the left and top and subtracts units from the right and bottom. The parameters of DeflateRect are signed values; positive values deflate CRect and negative values inflate it.
The first two overloads deflate both pairs of opposite sides of CRect so that its total width is decreased by two times x (or cx) and its total height is decreased by two times y (or cy). The other two overloads deflate each side of CRect independently of the others.
Moves the current position to the point specified by x and y (or by point).
关于CDC::MoveTo
CPoint CDC::MoveTo( int x, int y );
CPoint CDC::MoveTo( POINT point );
Moves the current position to the point specified by x and y (or by point).
关于CDC::LineTo
BOOL LineTo(int xint y);,
BOOL LineTo(POINT point );
Draws a line from the current position up to, but not including, the point specified by x and y (or point). The line is drawn with the selected pen. The current position is set to x,y or to point. point  specifies the endpoint for the line. You can pass either a POINT structure or a CPoint object for this parameter.
关于CDC::DrawText
virtual int CDC::DrawText(LPCTSTR lpszStringint nCount,,
               LPRECT lpRectUINT nFormat );,
int CDC::DrawText(const CString& strLPRECT lpRectUINT nFormat );,,
Call this member function to format text in the given rectangle. To specify additional formatting options, use CDC::DrawTextEx.
It formats text by expanding tabs into appropriate spaces, aligning text to the left, right, or center of the given rectangle, and breaking text into lines that fit within the given rectangle. The type of formatting is specified by nFormat. Unless the DT_NOCLIP format is used, DrawText clips the text so that the text does not appear outside the given rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is given. If the TA_UPDATECP text-alignment flag has been set (see CDC::SetTextAlign), DrawText will display text starting at the current position, rather than at the left of the given rectangle. DrawText will not wrap text when the TA_UPDATECP flag has been set (that is, the DT_WORDBREAK flag will have no effect).
关于DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the lpRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawText modifies 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.
例如:
pDCMem->DrawText(strText, m_rectTextOut, DT_CALCRECT); // Calc Text Rect
 
 
关于CRect::OffsetRect
void CRect::OffsetRect(int x, int y) throw( );
void CRect::OffsetRect(POINT point) throw( );
void CRect::OffsetRect(SIZE size) throw( );
Moves CRect by the specified offsets.
Moves CRect x units along the x-axis and y units along the y-axis. The x and y parameters are signed values, so CRect can be moved left or right and up or down.
关于CDC::BitBlt
BOOL CDC::BitBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC,
               int xSrc, int ySrc, DWORD dwRop );
Copies a bitmap from the source device context to this current device context.
GDI transforms nWidth and nHeight, once by using the destination device context, and once by using the source device context. If the resulting extents do not match, GDI uses the Windows StretchBlt function to compress or stretch the source bitmap as necessary.Note that not all device contexts support BitBlt. To check whether a given device context does support BitBlt, use the GetDeviceCaps member function and specify the RASTERCAPS index.
dwRop specifies the raster operation to be performed. Raster-operation codes define how the GDI combines colors in output operations that involve a current brush, a possible source bitmap, and a destination bitmap.
关于SRCCOPY
Copies the source rectangle directly to the destination rectangle.
 
关于CWnd::RedrawWindow
BOOL CWnd::RedrawWindow( 
         LPCRECT lpRectUpdate = NULL,
         CRgn* prgnUpdate = NULL,
         UINT flags = RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE ); 
Updates the specified rectangle or region in the given window's client area.
Parameters. If both prgnUpdate and lpRectUpdate are NULL, the entire client area is added to the update region.
flags
The following flags are used to invalidate the window:
·                     RDW_ERASE   Causes the window to receive a WM_ERASEBKGND message when the window is repainted. The RDW_INVALIDATE flag must also be specified; otherwise RDW_ERASE has no effect.
·                     RDW_FRAME   Causes any part of the nonclient area of the window that intersects the update region to receive a WM_NCPAINT message. The RDW_INVALIDATE flag must also be specified; otherwise RDW_FRAME has no effect.
·                     RDW_INTERNALPAINT   Causes a WM_PAINT message to be posted to the window regardless of whether the window contains an invalid region.
·                     RDW_INVALIDATE   Invalidate lpRectUpdate or prgnUpdate (only one may be not NULL). If both are NULL, the entire window is invalidated.
The following flags are used to validate the window:
·                     RDW_NOERASE   Suppresses any pending WM_ERASEBKGND messages.
·                     RDW_NOFRAME   Suppresses any pending WM_NCPAINT messages. This flag must be used with RDW_VALIDATE and is typically used with RDW_NOCHILDREN. This option should be used with care, as it could prevent parts of a window from painting properly.
·                     RDW_NOINTERNALPAINT   Suppresses any pending internal WM_PAINT messages. This flag does not affect WM_PAINT messages resulting from invalid areas.
·                     RDW_VALIDATE   Validates lpRectUpdate or prgnUpdate (only one may be not NULL). If both are NULL, the entire window is validated. This flag does not affect internal WM_PAINT messages.
The following flags control when repainting occurs. Painting is not performed by the RedrawWindow function unless one of these bits is specified.
·                     RDW_ERASENOW   Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT and WM_ERASEBKGND messages, if necessary, before the function returns. WM_PAINT messages are deferred.
·                     RDW_UPDATENOW   Causes the affected windows (as specified by the RDW_ALLCHILDREN and RDW_NOCHILDREN flags) to receive WM_NCPAINT, WM_ERASEBKGND, and WM_PAINT messages, if necessary, before the function returns.
By default, the windows affected by the RedrawWindow function depend on whether the specified window has the WS_CLIPCHILDREN style. The child windows of WS_CLIPCHILDREN windows are not affected. However, those windows that are not WS_CLIPCHILDREN windows are recursively validated or invalidated until a WS_CLIPCHILDREN window is encountered. The following flags control which windows are affected by the RedrawWindow function:
·                     RDW_ALLCHILDREN   Includes child windows, if any, in the repainting operation.
·                     RDW_NOCHILDREN   Excludes child windows, if any, from the repainting operation.
When the RedrawWindow member function is used to invalidate part of the desktop window, that window does not receive a WM_PAINT message. To repaint the desktop, an application should use CWnd::ValidateRgn, CWnd::InvalidateRgn, CWnd::UpdateWindow, or RedrawWindow .
关于CWnd::GetWindowRect
void CWnd::GetWindowRect( LPRECT lpRect ) const;
Copies the dimensions of the bounding rectangle of the CWnd object to the structure pointed to by lpRect. The dimensions are given in screen coordinates relative to the upper-left corner of the display screen. The dimensions of the caption, border, and scroll bars, if present, are included.
关于CWnd::ScreenToClient
void CWnd::ScreenToClient(LPPOINT lpPoint) const;
void CWnd::ScreenToClient(LPRECT lpRect) const;
Converts the screen coordinates of a given point or rectangle on the display to client coordinates.The ScreenToClient member function replaces the screen coordinates given in lpPoint or lpRect with client coordinates. The new coordinates are relative to the upper-left corner of the CWnd client area.
关于CWnd::InvalidateRect
void CWnd::InvalidateRect(LPCRECT lpRect, BOOL bErase = TRUE );
Invalidates the client area within the given rectangle by adding that rectangle to the CWnd update region.If lpRect is NULL, the entire client area is added to the region. The invalidated rectangle, along with all other areas in the update region, is marked for painting when the next WM_PAINT message is sent. The invalidated areas accumulate in the update region until the region is processed when the next WM_PAINT call occurs, or until the region is validated by the ValidateRect or ValidateRgn member function.The bErase parameter specifies whether the background within the update area is to be erased when the update region is processed. If bErase is TRUE, the background is erased when the BeginPaint member function is called; if bErase is FALSE, the background remains unchanged. If bErase is TRUE for any part of the update region, the background in the entire region is erased, not just in the given part.
Windows sends a WM_PAINT message whenever the CWnd update region is not empty and there are no other messages in the application queue for that window.
关于CWnd::UpdateWindow
void CWnd::UpdateWindow( );
Updates the client area by sending a WM_PAINT message if the update region is not empty. The UpdateWindow member function sends a WM_PAINT message directly, bypassing the application queue. If the update region is empty, WM_PAINT is not sent.
返回控件本身
CLabel& CLabel::SetText(const CString& strText)
{
//……do something here
            return *this;
}
关于CWindow::IsWindow
BOOL CWindow::IsWindow( ) throw();
Determines whether the specified window handle identifies an existing window.
关于CWnd::SetWindowText
void CWnd::SetWindowText(LPCTSTR lpszString);
Sets the window's title to the specified text.If the window is a control, the text within the control is set. This function causes a WM_SETTEXT message to be sent to this window.
关于UpdateSurface
CLabel& CLabel::SetText(const CString& strText)
{              
               if(IsWindow(this->GetSafeHwnd())) 
               {       
                              SetWindowText(strText);
                              UpdateSurface(); //must be called
               }
               return *this;
}
After setting the window text, repaint must be triggered. Otherwise, some features are not applied to it.
 
typedef struct tagLOGFONT { 
  LONG lfHeight; 
  LONG lfWidth; 
  LONG lfEscapement; 
  LONG lfOrientation; 
  LONG lfWeight; 
  BYTE lfItalic; 
  BYTE lfUnderline; 
  BYTE lfStrikeOut; 
  BYTE lfCharSet; 
  BYTE lfOutPrecision; 
  BYTE lfClipPrecision; 
  BYTE lfQuality; 
  BYTE lfPitchAndFamily; 
  TCHAR lfFaceName[LF_FACESIZE]; 
} LOGFONT, *PLOGFONT; 
 
关于 lfWeight
lfWeight specifies the weight of the font in the range 0 through 1000. For example, 400 is normal and 700 is bold. If this value is zero, a default weight is used.
The following values are defined for convenience.

Value
Weight
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_HEAVY
900
FW_BLACK
900

关于lfItalic
Specifies an italic font if set to TRUE.
lfUnderline
Specifies an underlined font if set to TRUE.
 
关于 lfEscapement and lfOrientation
lfEscapement
Specifies the angle, in tenths of degrees, between the escapement vector and the x-axis of the device. The escapement vector is parallel to the base line of a row of text.
Windows NT/2000/XP: When the graphics mode is set to GM_ADVANCED, you can specify the escapement angle of the string independently of the orientation angle of the string's characters. When the graphics mode is set to GM_COMPATIBLE, lfEscapement specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.
Windows 95/98/Me: The lfEscapement member specifies both the escapement and orientation. You should set lfEscapement and lfOrientation to the same value.
lfOrientation
Specifies the angle, in tenths of degrees, between each character's base line and the x-axis of the device.
Font rotation only works with TrueType fonts, like 'Arial' and 'Times New Roman'.
CLabel& CLabel::SetRotationAngle(UINT nAngle,BOOL bRotation)
{
           
            // nAngle is in Degress
            m_lf.lfEscapement = m_lf.lfOrientation = (nAngle * 10);
            //do something here
}
关于 lfFaceName and lfCharSet
lfCharSet
Specifies the character set. The following values are predefined.
ANSI_CHARSET     
BALTIC_CHARSET      
CHINESEBIG5_CHARSET
DEFAULT_CHARSET    
EASTEUROPE_CHARSET    
GB2312_CHARSET
GREEK_CHARSET      
HANGUL_CHARSET       
MAC_CHARSET
OEM_CHARSET      
RUSSIAN_CHARSET       
SHIFTJIS_CHARSET
SYMBOL_CHARSET     
TURKISH_CHARSET    
VIETNAMESE_CHARSET
lfFaceName
A null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 32 characters, including the null terminator. The EnumFontFamilies function can be used to enumerate the typeface names of all currently available fonts. If lfFaceName is an empty string, GDI uses the first font that matches the other specified attributes.
例如:
CLabel& CLabel::SetFontName(const CString& strFont,
BYTE byCharSet /* Default = ANSI_CHARSET */)
{          
m_lf.lfCharSet = byCharSet;
_tcscpy(m_lf.lfFaceName,strFont);
            //……………..
}
关于_tcscpy
char *strcpy(char * strDestination, const char * strSource);
wchar_t *wcscpy(wchar_t * strDestination, const wchar_t * strSource);
unsigned char *_mbscpy(unsigned char * strDestination, const unsigned char * strSource);
Copy a string.
关于CopyMemory
VOID CopyMemory(
               PVOID Destination,   // copy destination
               CONST VOID* Source, // memory block
               SIZE_T Length);        // size of memory block
The CopyMemory function copies a block of memory from one location to another.
If the source and destination blocks overlap, the results are undefined. For overlapped blocks, use the MoveMemory function. Be aware that the last parameter, Length, is the number of bytes to copy into Destination, not the size of the Destination.
例如:
(1)The following code example shows a safe way to use CopyMemory:
void test(char *pbData, unsigned int cbData) {
             char buf[BUFFER_SIZE];
              CopyMemory(buf, pbData, min(cbData,BUFFER_SIZE));
}
(2)LOGFONT lf; LOGFONT m_lf; CopyMemory(&m_lf, &lf, sizeof(m_lf));
 
3D 字体
m_cr3DHiliteColor  = RGB(255,255,255);
pDCMem->SetTextColor(m_cr3DHiliteColor);
if (m_3dType == Raised)
            rc.OffsetRect(-1,-1);
else       //type is Sunken
            rc.OffsetRect(1,1);
 
pDCMem->DrawText(strText,rc,dwFlags);
 
pDCMem->SetTextColor(m_crText);
pDCMem->DrawText(strText,rcText,dwFlags);
                                                系统颜色改变
//{{AFX_MSG(CLabel)
afx_msg void OnSysColorChange();
//}}AFX_MSG
 
BEGIN_MESSAGE_MAP(CLabel, CStatic)
//{{AFX_MSG_MAP(CLabel)
ON_WM_SYSCOLORCHANGE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
 
void CLabel::OnSysColorChange()
{
            //do something here
}
 
 
字号
点数制
点数制又叫数制,是英文point的音译,缩写为P,既不是公制也不是英制,是印刷中专用的尺度。我国大都使用英美点数制。1点(1P)=0.35146mm
号数制
号数制是以互不成倍数的几种活字为标准,加倍或减半自成体系。
字号的大小可以分为以下四个序列。
• 四号序列:一号、四号、小六号
• 五号序列:初号、二号、五号、七号
• 小五号序列:小初号、小二号、小五号、八号
• 六号序列:三号、六号
关于CFont::CreatePointFont
BOOL CFont::CreatePointFont(int nPointSize, LPCTSTR lpszFaceName, 
               CDC* pDC = NULL );
This function provides a simple way to create a font of a specified typeface and point size.
It automatically converts the height in nPointSize to logical units using the CDC object pointed to by pDC.When you finish with the CFont object created by the CreatePointFont function, first select the font out of the device context, then delete the CFont object.
Parameters
nPointSize
Requested font height in tenths of a point. (For instance, pass 120 to request a 12-point font.)
lpszFaceName
A CString or pointer to a null-terminated string that specifies the typeface name of the font. The length of this string must not exceed 30 characters. The Windows EnumFontFamilies function can be used to enumerate all currently available fonts. If lpszFaceName is NULL, the GDI uses a device-independent typeface.
pDC
Pointer to the CDC object to be used to convert the height in nPointSize to logical units. If NULL, a screen device context is used for the conversion.
例如:
CLabel& CLabel::SetFontSize(int nSize)
{
            CFont cf;
            LOGFONT lf;
            cf.CreatePointFont(nSize * 10, m_lf.lfFaceName);
            cf.GetLogFont(&lf);
            m_lf.lfHeight = lf.lfHeight;
            m_lf.lfWidth = lf.lfWidth;
            //……………..
}
关于CFont::GetLogFont
int CFont::GetLogFont(LOGFONT * pLogFont );
Call this function to retrieve a copy of the LOGFONT structure for CFont.
关于CWnd::KillTimer
BOOL CWnd::KillTimer(UINT_PTR nIDEvent );
Kills the timer event identified by nIDEvent from the earlier call to SetTimer.
Pending WM_TIMER messages associated with the timer are not removed from the message queue.
关于CWnd::SetTimer
UINT_PTR SetTimer(UINT_PTR nIDEvent,UINT nElapse
            void (CALLBACK* lpfnTimer)(HWND, UINT, UINT_PTR, DWORD) );
Installs a system timer. lpfnTimer specifies the address of the application-supplied TimerProc callback function that processes the WM_TIMER messages. If this parameter is NULL, the WM_TIMER messages are placed in the application's message queue and handled by the CWnd object. A time-out value is specified, and every time a time-out occurs, the system posts a WM_TIMER message to the installing application's message queue or passes the message to an application-defined TimerProc callback function.
The lpfnTimer callback function need not be named TimerProc, but it must be defined as follows:
void CALLBACK EXPORT TimerProc(
   HWND hWnd,      // handle of CWnd that called SetTimer
   UINT nMsg,      // WM_TIMER
   UINT nIDEvent   // timer identification
   DWORD dwTime    // system time
);
Timers are a limited global resource; therefore it is important that an application check the value returned by the SetTimer member function to verify that a timer is actually available.
Return Value
The timer identifier of the new timer if the function is successful. An application passes this value to the KillTimer member function to kill the timer. Nonzero if successful; otherwise 0.
关于OnTimer
//{{AFX_MSG(CLabel)
            afx_msg void OnTimer(UINT nIDEvent);
//}}AFX_MSG
BEGIN_MESSAGE_MAP(CLabel, CStatic)
            //{{AFX_MSG_MAP(CLabel)
            ON_WM_TIMER()
            //}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CLabel::OnTimer(UINT nIDEvent)
{
            //do something here
            CStatic::OnTimer(nIDEvent);
}
 
关于CWnd::ModifyStyleEx
BOOL CWnd::ModifyStyleEx(DWORD dwRemove, DWORD dwAdd, 
               UINT nFlags = 0 );
Call this member function to modify a window's extended style. To modify windows using regular window styles, see ModifyStyle.
nFlags
Flags to be passed to SetWindowPos, or zero if SetWindowPos should not be called. The default is zero. If nFlags is nonzero, ModifyStyleEx calls the Windows API function SetWindowPos and redraws the window by combining nFlags with the following four preset flags:
  • SWP_NOSIZE   Retains the current size.
  • SWP_NOMOVE   Retains the current position.
  • SWP_NOZORDER   Retains the current Z order.
  • SWP_NOACTIVATE   Does not activate the window.
Example
// This example would make the dialog box transparent by
// changing the dialog window's extended styles.
int CMyDialog::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
   if (CDialog::OnCreate(lpCreateStruct) == -1)
      return -1;
   ModifyStyleEx(0, WS_EX_TRANSPARENT);   
   return 0;
}
关于WS_EX_STATICEDGE
Creates a window with a three-dimensional border style intended to be used for items that do not accept user input.
例如:ModifyStyleEx(WS_EX_STATICEDGE, 0, SWP_DRAWFRAME);
关于SWP_DRAWFRAME
Draws a frame (defined in the window's class description) around the window.
It is a flag of a parameter of the SetWindowPos function.
关于WS_BORDER
Creates a window that has a border.
例如:ModifyStyle(WS_BORDER,0,SWP_DRAWFRAME);
关于CStatic::SetCursor
HCURSOR CStatic::SetCursor(HCURSOR hCursor);
Associates a new cursor image with the static control. The cursor will be automatically drawn in the static control. By default, it will be drawn in the upper-left corner and the static control will be resized to the size of the cursor.You can use various window and static control styles, including the following:
·               SS_ICON   Use this style always for cursors and icons.
·               SS_CENTERIMAGE   Use to center in the static control. If the image is larger than the static control, it will be clipped. If it is smaller than the static control, the empty space around the image will be filled with the background color of the static control.
Return Value
The handle of the cursor previously associated with the static control, or NULL if no cursor was associated with the static control.
关于CWnd::PreSubclassWindow
virtual void CWnd::PreSubclassWindow( );
This member function is called by the framework to allow other necessary subclassing to occur before the window is subclassed.Overriding this member function allows for dynamic subclassing of controls. It is an advanced overridable.
关于子类化和超类化
子类化
子类化的目的是在不修改现有代码的前提下,扩展现有窗口的功能。它的思路很简单,就是 将窗口过程地址修改为一个新函数地址,新的窗口过程函数处理自己感兴趣的消息,将其它消息传递给原窗口过程。通过子类化,我们不需要现有窗口的源代码,就可以定制窗口功能。
子类化可以分为实例子类化和全局子类化。实例子类化就是修改窗口实例的窗口过程地址,全局子类化就是修改窗口类的窗口过程地址。实例子类化只影响被修改的窗口。全局子类化会影响在修改之后,按照该窗口类创建的所有窗口。显然,全局子类化不会影响修改前已经创建的窗口。
子类化方法虽然是二十年前的概念,却很好地实践了面向对象技术的开闭原则(OCP:The Open-Closed Principle):对扩展开放,对修改关闭。
超类化
超类化的概念更简单,就是读取现有窗口类的数据,保存窗口过程函数地址。对窗口类数据作必要的修改,设置新窗口过程,再换一个名称后登记一个新窗口类。新窗口类的窗口过程函数还是仅处理自己感兴趣的消息,而将其它消息传递给原窗口过程函数处理。使用GetClassInfo函数可以读取现有窗口类的数据。
 
关于CWnd::GetFont
CFont* CWnd::GetFont( ) const;
Gets the current font for this window.
Return Value
A pointer to a CFont that contains the current font. The pointer may be temporary and should not be stored for later use.
关于CGdiObject::GetObject
int CGdiObject::GetObject(int nCount, LPVOID lpObject ) const;
Fills a buffer with data that defines a specified object.
例如:cf->GetObject(sizeof(m_lf),&m_lf);
关于GetStockObject
HGDIOBJ GetStockObject(int fnObject stock:常备的,库存   // stock object type);    //
The GetStockObject function retrieves a handle to one of the stock pens, brushes, fonts, or palettes.
例如:GetStockObject(SYSTEM_FONT)
关于CWnd::PreCreateWindow
virtual BOOL CWnd::PreCreateWindow(CREATESTRUCT& cs);
Called by the framework before the creation of the Windows window attached to this CWnd object.
关于Static Styles SS_NOTIFY
Sends the parent window STN_CLICKED, STN_DBLCLK, STN_DISABLE, and STN_ENABLE notification messages when the user clicks or double-clicks the control.
例如:ModifyStyle(0,SS_NOTIFY);
关于CWnd::OnSetCursor
afx_msg BOOL CWnd::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
The framework calls this member function if mouse input is not captured and the mouse causes cursor movement within the CWnd object.The default implementation calls the parent window's OnSetCursor before processing. If the parent window returns TRUE, further processing is halted. Calling the parent window gives the parent window control over the cursor's setting in a child window. The default implementation sets the cursor to an arrow if it is not in the client area or to the registered-class cursor if it is.
关于NMHDR
typedef struct tagNMHDR {HWND hwndFrom; UINT idFrom; UINT code; } NMHDR; 
Contains information about a notification message.
code
Notification code. This member can be a control-specific notification code or it can be one of the common notification codes.
   
关于WM_NOTIFY
WM_NOTIFY
    idCtrl = (int) wParam;
    pnmh = (LPNMHDR) lParam;
The WM_NOTIFY message is sent by a common control to its parent window when an event has occurred or the control requires some information.
Notification the parent window
#define  NM_LINKCLICK            WM_APP + 0x200
NMHDR nm;
nm.hwndFrom = GetSafeHwnd();
nm.idFrom = GetDlgCtrlID();
nm.code = NM_LINKCLICK;
GetParent()->SendMessage(WM_NOTIFY,nm.idFrom,(LPARAM) &nm);
关于ShellExecute
HINSTANCE ShellExecute(
    HWND hwnd,
    LPCTSTR lpOperation,
    LPCTSTR lpFile,
    LPCTSTR lpParameters,
    LPCTSTR lpDirectory,
    INT nShowCmd
);
Performs an operation on a specified file.
Parameters
hwnd
[in] Handle to a parent window. This window receives any message boxes that an application produces, such as error reporting.
lpOperation
[in] Pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object's shortcut menu are available verbs. For more information about verbs and their availability, see Object Verbs. See Extending Shortcut Menus for further discussion of shortcut menus. The following verbs are commonly used.

Verb
Description
edit
Launches an editor and opens the document for editing. If lpFile is not a document file, the function will fail.
explore
Explores the folder specified by lpFile.
find
Initiates a search starting from the specified directory.
open
Opens the file specified by the lpFile parameter. The file can be an executable file, a document file, or a folder.
print
Prints the document file specified by lpFile. If lpFile is not a document file, the function will fail.

If you set this parameter to NULL:
For systems prior to Microsoft® Windows® 2000, the default verb is used if it is valid and available in the registry. If not, the "open" verb is used.
For Windows 2000 and later systems, the default verb is used if available. If not, the "open" verb is used. If neither verb is available, the system uses the first verb listed in the registry.
lpFile
[in] Pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully-qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the "print" verb.
lpParameters
[in] If the lpFile parameter specifies an executable file, lpParameters is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL.
lpDirectory
[in] Pointer to a null-terminated string that specifies the default directory.
nShowCmd
[in] Flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it.

SW_HIDE
Hides the window and activates another window.
SW_MAXIMIZE
Maximizes the specified window.
SW_MINIMIZE
Minimizes the specified window and activates the next top-level window in the z-order.
SW_RESTORE
Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW
Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT
Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.
SW_SHOWMAXIMIZED
Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE
Displays the window as a minimized window. The active window remains active.
SW_SHOWNA
Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE
Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL
Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

Return Values
Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise. The following table lists the error values. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Microsoft® Windows® applications. It is not a true HINSTANCE, however. The only thing that can be done with the returned HINSTANCE is to cast it to an integer and compare it with the value 32 or one of the error codes below.

0
The operating system is out of memory or resources.
ERROR_FILE_NOT_FOUND
The specified file was not found.
ERROR_PATH_NOT_FOUND
The specified path was not found.
ERROR_BAD_FORMAT
The .exe file is invalid (non-Win32® .exe or error in .exe image).
SE_ERR_ACCESSDENIED
The operating system denied access to the specified file.
SE_ERR_ASSOCINCOMPLETE
The file name association is incomplete or invalid.
SE_ERR_DDEBUSY
The DDE transaction could not be completed because other DDE transactions were being processed.
SE_ERR_DDEFAIL
The DDE transaction failed.
SE_ERR_DDETIMEOUT
The DDE transaction could not be completed because the request timed out.
SE_ERR_DLLNOTFOUND
The specified dynamic-link library was not found.
SE_ERR_FNF
The specified file was not found.
SE_ERR_NOASSOC
There is no application associated with the given file name extension. This error will also be returned if you attempt to print a file that is not printable.
SE_ERR_OOM
There was not enough memory to complete the operation.
SE_ERR_PNF
The specified path was not found.
SE_ERR_SHARE
A sharing violation occurred.

Remarks
This method allows you to execute any commands in a folder's shortcut menu or stored in the registry.
To open a folder, use either of the following calls:
ShellExecute(handle, NULL, path_to_folder, NULL, NULL, SW_SHOWNORMAL);
or
ShellExecute(handle, "open", path_to_folder, NULL, NULL, SW_SHOWNORMAL);
To explore a folder, use:
ShellExecute(handle, "explore", path_to_folder, NULL, NULL, SW_SHOWNORMAL);
To launch the Shell's Find utility for a directory, use:
ShellExecute(handle, "find", path_to_folder, NULL, NULL, 0);
If lpOperation is NULL, the function opens the file specified by lpFile. If lpOperation is "open" or "explore", the function will attempt to open or explore the folder.
To obtain information about the application that is launched as a result of calling ShellExecute, use ShellExecuteEx.
Windows 95/98/Me: ShellExecute is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.
例如:
CString strLink;
GetWindowText(strLink);
if (m_Link == HyperLink)
{
ShellExecute(NULL,_T("open"), strLink, NULL, NULL, SW_SHOWNORMAL);
}
if (m_Link == MailLink)
{
strLink = "mailto:" + strLink;
ShellExecute( NULL, NULL, strLink, NULL, NULL, SW_SHOWNORMAL );
}
关于CDC::DeleteDC
BOOL CDC::DeleteDC( );
In general, do not call this function; the destructor will do it for you.The DeleteDC member function deletes the Windows device contexts that are associated with m_hDC in the current CDC object. If this CDC object is the last active device context for a given device, the device is notified and all storage and system resources used by the device are released. An application should not call DeleteDC if objects have been selected into the device context. Objects must first be selected out of the device context before it it is deleted. An application must not delete a device context whose handle was obtained by calling CWnd::GetDC. Instead, it must call CWnd::ReleaseDC to free the device context. The CClientDC and CWindowDC classes are provided to wrap this functionality.
The DeleteDC function is generally used to delete device contexts created with CreateDC, CreateIC, or CreateCompatibleDC.
 
 
关于 CGdiObject::DeleteObject
BOOL CGdiObject::DeleteObject( );
Deletes the attached Windows GDI object from memory by freeing all system storage associated with the Windows GDI object.The storage associated with the CGdiObject object is not affected by this call. An application should not call DeleteObject on a CGdiObject object that is currently selected into a device context.When a pattern brush is deleted, the bitmap associated with the brush is not deleted. The bitmap must be deleted independently.
MFC 双缓冲(double buffering)
把image显示在monitor上有多种方法,最简单的就是把image直接画出,但这样会导致画面闪烁(Flicker)。因为每次更新图片时计算机要erase然后redraw,在这个时间段内观察者会看到上一次的背景,但这个时候本应该是显示下一个frame。要解决这个问题,就可以使用双缓冲Double buffering技术。先把image绘制到后台缓冲,等到全部绘好后再copy到screen中显示。
Draw()
{
    CPaintDC dc(this);
    CDC dcMem;
    dc.CreateCompatibleDC(&dc);
    CBitmap bmp;
    bmp.CreateCompatibleBitmap(&dc,m_Bounds.Width(),m_Bounds.Height());
    CBitmap *pOldBitmap = dcMem.SelectObject(&bmp);
    Draw(&dcMem);
       dc.BitBlt(0,0,m_Bounds.Width(),m_Bounds.Height(),
&dcMem,0,0,SRCCOPY);
    dc.SelectObject(pOldBitmap);
}
We can define macros to make this funcationality easy to reach
#define BEGIN_DOUBLE_BUFFERING(pCWnd, pDc) /
CPaintDC dc(pCWnd);/
CDC dcMem;/
CDC *pDc = &dcMem;
dc.CreateCompatibleDC(&dc);/
CBitmap bmp;/
CRect rc;/
GetClientRect(rc);/
bmp.CreateCompatibleBitmap(&dc,rc.Width(),rc.Height());/
CBitmap *pOldBitmap = dcMem.SelectObject(&bmp);/
#define END_DOUBLE_BUFFERING(pCWnd, pDc) /
   dc.BitBlt(0,0, rc.Width(),rc.Height(),&dcMem,0,0,SRCCOPY);/
dc.SelectObject(pOldBitmap);/
Then we can use double buffering like below:
DOUBLE_BUFFERING_BEGIN(this, pDc);
    pDc->TextOutW(20,20,_T("Your drawing logic"),4);
DOUBLE_BUFFERING_END(this, pDc);
关于 SS_TYPEMASK
#define   SS_TYPEMASK  0x0000000FL
The mask code of the static control.
                  A Regular Order
Clabel::SetFeature()
{
//(1)set flag
//(2)call UpdateSurface
}
Clabel:: UpdateSurface()
{
      // Add criteria when update
if (GetSafeHwnd())
{
      //do something here
      }
}
update the parent after updating
void CLabel::UpdateSurface()
{
    if (GetSafeHwnd())
    {
          CRect (rc);
          GetWindowRect(rc);
          RedrawWindow();
          //I don’t know is it necessary.
          GetParent()->ScreenToClient(rc);
         GetParent()->InvalidateRect(rc,TRUE);
         GetParent()->UpdateWindow();
    }
}
关于SetBkMode(TRANSPARENT)
pDC->SetBkMode(TRANSPARENT);使文本背景与控件背景一样。这个函数只能去掉文字的背景,默认情况下,一个文字是一个方块,文字用文本前景,背景用文字背景(可能和窗口背景不一样),使用这个函数后,文字背景就透明了(和窗口背景一样),
但窗口背景并不也变成透明.
ModifyStyleEx(0,WS_EX_TRANSPARENT);使窗口背景透明。
关于static
class CLabel : public Cstatic
{
public:
      //I don’t know why should use “static” here?
static enum LinkStyle { LinkNone, HyperLink, MailLink };
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值