宏的应用
#define BTNST_USE_BCMENU
class CButtonST
{
#ifdef BTNST_USE_BCMENU
DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bWinXPStyle = TRUE,
UINT nToolbarID = NULL, CSize sizeToolbarIcon = CSize(16, 16),
COLORREF crToolbarBk = RGB(255, 0, 255), BOOL bRepaint = TRUE);
#else
DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bRepaint = TRUE);
#endif
}
version
//Version: See GetVersionC() or GetVersionI()
class CButtonST
{
static short GetVersionI(){return 40;}
static LPCTSTR GetVersionC(){return (LPCTSTR)_T("4.0");}
}
about “enum”
class CButtonST
{
enum
{BTNST_COLOR_BK_IN = 0, BTNST_COLOR_FG_IN, BTNST_COLOR_BK_OUT, BTNST_COLOR_FG_OUT, BTNST_COLOR_BK_FOCUS, BTNST_COLOR_FG_FOCUS,
BTNST_MAX_COLORS};
COLORREF m_crColors[BTNST_MAX_COLORS];
}
关于ZeroMemory
STRUCT_BITMAPS
m_csBitmaps[2];
::ZeroMemory(&m_csBitmaps, sizeof(m_csBitmaps)); //
用于结构体和数组
关于初始化
如果变量过多,以相关性分组,分别写初始化函数。
关于CWnd::OnGetDlgCode
afx_msg UINT CWnd::OnGetDlgCode( );
Called for a control so the control can process arrow-key and TAB-key input itself. Normally, Windows handles all arrow-key and TAB-key input to a CWnd control. By overriding OnGetDlgCode, a CWnd control can choose a particular type of input to process itself. The default OnGetDlgCode functions for the predefined control classes return a code appropriate for each class.
Return Value
One or more of the following values, indicating which type of input the application processes:
· DLGC_BUTTON Button (generic).
· DLGC_DEFPUSHBUTTON Default pushbutton.
· DLGC_HASSETSEL EM_SETSEL messages.
· DLGC_UNDEFPUSHBUTTON No default pushbutton processing. (An application can use this flag with DLGC_BUTTON to indicate that it processes button input but relies on the system for default pushbutton processing.)
· DLGC_RADIOBUTTON Radio button.
· DLGC_STATIC Static control.
· DLGC_WANTALLKEYS All keyboard input.
· DLGC_WANTARROWS Arrow keys.
· DLGC_WANTCHARS WM_CHAR messages.
· DLGC_WANTMESSAGE All keyboard input. The application passes this message on to the control.
· DLGC_WANTTAB TAB key.
CWnd::Invalidate
void CWnd::Invalidate(BOOL bErase = TRUE);
Invalidates the entire client area of CWnd.The client area is marked for painting when the next
WM_PAINT message occurs. The region can also be validated before a WM_PAINT message occurs 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, not just in the given part, is erased.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.
关于BS_TYPEMASK
//Mask for control's type
#define BS_TYPEMASK SS_TYPEMASK
关于GetSysColor
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.
COLOR_BTNTEXT Text on push buttons.
COLOR_BTNFACE Face color for three-dimensional display elements and for dialog box backgrounds.
关于memset, wmemset
void *memset(void *dest,int c,size_t count);
wchar_t *wmemset(wchar_t *dest,wchar_t c,size_t count);
Sets the first count bytes of dest to the character c.
例如://Remove any existing URL memset(m_szURL, 0, sizeof(m_szURL));
关于_tcsncpy
Generic-Text Routine Mappings
TCHAR.H routine
|
_UNICODE & _MBCS not defined
|
_MBCS defined
|
_UNICODE defined
|
_tcsncpy
|
strncpy
|
_mbsnbcpy
|
wcsncpy
|
char *strncpy(char *strDest,const char *strSource,size_t count);
wchar_t *wcsncpy(wchar_t *strDest,const wchar_t *strSource,
size_t count);
unsigned char *_mbsncpy(unsigned char *strDest,
const unsigned char *strSource, size_t count);
The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.
关于_MAX_PATH
#include <stdlib.h>
_MAX_PATH Maximum length of full path
关于ToolTip
CButtonST::CButtonST()
{
// No tooltip created.
m_ToolTip.m_hWnd = NULL;
}
Must do like this. Otherwise, after CtoolTipCtrl:: CtoolTipCtrl() executes, m_ToolTip.m_hWnd is also a random number.
关于DestroyCursor
BOOL DestroyCursor(HCURSOR hCursor // handle to cursor to destroy);
The DestroyCursor function destroys a cursor and frees any memory the cursor occupied. Do not use this function to destroy a shared cursor.
A shared cursor is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared cursor:
- LoadCursor
- LoadCursorFromFile
- LoadImage (if you use the LR_SHARED flag)
- CopyImage (if you use the LR_COPYRETURNORG flag and the hImage parameter is a shared cursor)
关于DestroyMenu
BOOL DestroyMenu(HMENU hMenu // handle to menu);
The DestroyMenu function destroys the specified menu and frees any memory that the menu occupies. Before closing, an application must use the DestroyMenu function to destroy a menu not assigned to a window. A menu that is assigned to a window is automatically destroyed when the application closes. DestroyMenu is recursive, that is, it will destroy the menu and all its submenus.
关于CMenu::DestroyMenu
BOOL CMenu::DestroyMenu( );
Destroys the menu and any Windows resources that were used.The menu is detached from the CMenu object before it is destroyed.
The Windows DestroyMenu function is automatically called in the CMenu destructor.
关于CButton::GetButtonStyle
UINT CButton::GetButtonStyle( ) const;
Retrieves information about the button control style.Returns the button styles for this CButton object. This function returns only the
BS_ style values, not any of the other window styles.
· 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_PUSHBUTTON Creates a pushbutton that posts a WM_COMMAND message to the owner window when the user selects the button.
关于CButton::DrawItem
virtual void CButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
Called by the framework when a visual aspect of an owner-drawn button has changed. An owner-drawn button has the BS_OWNERDRAW style set. Override this member function to implement drawing for an owner-drawn CButton object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before the member function terminates.
关于DRAWITEMSTRUCT
typedef struct tagDRAWITEMSTRUCT {
UINT CtlType;
UINT CtlID;
UINT itemID;
UINT itemAction;
UINT itemState;
HWND hwndItem;
HDC hDC;
RECT rcItem;
DWORD itemData;
} DRAWITEMSTRUCT;
The DRAWITEMSTRUCT structure provides information the owner window must have to determine how to paint an owner-drawn control or menu item. The owner window of the owner-drawn control or menu item receives a pointer to this structure as the lParam parameter of the WM_DRAWITEM message.
Parameters
CtlType The control type. The values for control types are as follows:
· ODT_BUTTON Owner-drawn button
· ODT_COMBOBOX Owner-drawn combo box
· ODT_LISTBOX Owner-drawn list box
· ODT_MENU Owner-drawn menu
· ODT_LISTVIEW List view control
· ODT_STATIC Owner-drawn static control
· ODT_TAB Tab control
CtlID
The control ID for a combo box, list box, or button. This member is not used for a menu.
itemID
The menu-item ID for a menu or the index of the item in a list box or combo box. For an empty list box or combo box, this member is a negative value, which allows the application to draw only the focus rectangle at the coordinates specified by the rcItem member even though there are no items in the control. The user can thus be shown whether the list box or combo box has the input focus. The setting of the bits in the itemAction member determines whether the rectangle is to be drawn as though the list box or combo box has input focus.
itemAction
Defines the drawing action required. This will be one or more of the following bits:
· ODA_DRAWENTIRE This bit is set when the entire control needs to be drawn.
· ODA_FOCUS This bit is set when the control gains or loses input focus. The itemState member should be checked to determine whether the control has focus.
· ODA_SELECT This bit is set when only the selection status has changed. The itemState member should be checked to determine the new selection state.
itemState
Specifies the visual state of the item after the current drawing action takes place. That is, if a menu item is to be dimmed, the state flag ODS_GRAYED will be set. The state flags are as follows:
· ODS_CHECKED This bit is set if the menu item is to be checked. This bit is used only in a menu.
· ODS_DISABLED This bit is set if the item is to be drawn as disabled.
· ODS_FOCUS This bit is set if the item has input focus.
· ODS_GRAYED This bit is set if the item is to be dimmed. This bit is used only in a menu.
· ODS_SELECTED This bit is set if the item's status is selected.
· ODS_COMBOBOXEDIT The drawing takes place in the selection field (edit control) of an ownerdrawn combo box.
· ODS_DEFAULT The item is the default item.
hwndItem
Specifies the window handle of the control for combo boxes, list boxes, and buttons. Specifies the handle of the menu (HMENU) that contains the item for menus.
hDC
Identifies a device context. This device context must be used when performing drawing operations on the control.
rcItem
A rectangle in the device context specified by the hDC member that defines the boundaries of the control to be drawn. Windows automatically clips anything the owner draws in the device context for combo boxes, list boxes, and buttons, but it does not clip menu items. When drawing menu items, the owner must not draw outside the boundaries of the rectangle defined by the rcItem member.
itemData
For a combo box or list box, this member contains the value that was passed to the list box by one of the following:
·
CComboBox::AddString
·
CComboBox::InsertString
·
CListBox::AddString
·
CListBox::InsertString
For a menu, this member contains the value that was passed to the menu by one of the following:
·
CMenu::AppendMenu
·
CMenu::InsertMenu
·
CMenu::ModifyMenu
关于CClientDC
class CClientDC : public CDC
The CClientDC class is derived from CDC and takes care of calling the Windows functions GetDC at construction time and ReleaseDC at destruction time.
This means that the device context associated with a CClientDC object is the client area of a window.
关于CDC::FrameRect
void CDC::FrameRect(LPCRECT lpRect,CBrush* pBrush);
Draws a border around the rectangle specified by lpRect. The function uses the given brush to draw the border. The width and height of the border is always 1 logical unit. The border drawn by FrameRect is in the same position as a border drawn by the Rectangle member function using the same coordinates (if Rectangle uses a pen that is 1 logical unit wide).
The interior of the rectangle is not filled by FrameRect.
关于COLOR_3DSHADOW, COLOR_BTNSHADOW
Shadow color for three-dimensional display elements (for edges facing away from the light source).
关于CDC::Draw3dRect
void CDC::Draw3dRect(LPCRECT
lpRectCOLORREF
clrTopLeft,,
COLORREF
clrBottomRight);
void CDC::Draw3dRect(int
x,int
y,int
cx,int
cy,COLORREF
clrTopLeft,
COLORREF
clrBottomRight);
The rectangle will be drawn with the top and left sides in the color specified by clrTopLeft and the bottom and right sides in the color specified by clrBottomRight.
COLOR_BTNHILIGHT Highlight color for three-dimensional display elements (for edges facing the light source.)
例如:
pDC->Draw3dRect(pRect, ::GetSysColor(COLOR_BTNSHADOW),
::GetSysColor(COLOR_BTNHILIGHT));
About Color
COLOR_BTNHILIGHT
// White
COLOR_3DLIGHT
// Light gray
COLOR_BTNSHADOW
// Dark gray
COLOR_3DDKSHADOW
// Black
关于BYTE
BYTE
byIndex = 0; //占用较少的内存空间(比int)
关于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.
关于CRect::CopyRect
void CRect::CopyRect(LPCRECT lpSrcRect) throw( );
Copies the lpSrcRect rectangle into CRect.
Parameters
lpSrcRect
Points to the
RECT structure or CRect object that is to be copied.
关于CDC::DrawState
BOOL CDC::DrawState(CPoint pt,CSize size,HBITMAP hBitmap,
UINT nFlags,HBRUSH hBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,CBitmap* pBitmap,
UINT nFlags,CBrush* pBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,HICON hIcon,
UINT nFlags,HBRUSH hBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,HICON hIcon,
UINT nFlags,CBrush* pBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,LPCTSTR lpszText,
UINT nFlags,BOOL bPrefixText = TRUE, int nTextLen = 0,
HBRUSH hBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,LPCTSTR lpszText,
UINT nFlags,BOOL bPrefixText = TRUE, int nTextLen = 0,
CBrush* pBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,DRAWSTATEPROC lpDrawProc,
LPARAM lData,UINT nFlags,HBRUSH hBrush = NULL);
BOOL CDC::DrawState(CPoint pt,CSize size,DRAWSTATEPROC lpDrawProc,
LPARAM lData,UINT nFlags,CBrush* pBrush = NULL);
Call this member function to display an image and apply a visual effect to indicate a state, such as a disabled or default state. For all nFlag states except DSS_NORMAL, the image is converted to monochrome before the visual effect is applied.
Parameters
nFlags
Flags that specify the image type and state.
DSS_NORMAL
Draws the image without any modification.
DSS_DISABLED
Embosses(浮雕) the image.
bPrefixText
Text that may contain an accelerator mnemonic. The lData parameter specifies the address of the string, and the nTextLen parameter specifies the length. If nTextLen is 0, the string is assumed to be null-terminated.
lpDrawProc
A pointer to a callback function used to render an image. This parameter is required if the image type in nFlags is DST_COMPLEX. It is optional and can be NULL if the image type is DST_TEXT. For all other image types, this parameter is ignored.
lData
Specifies information about the image. The meaning of this parameter depends on the image type.
定义即初始化
HDC hdcMem = NULL;
关于CreateCompatibleDC
HDC CreateCompatibleDC(HDC hdc // handle to DC);
The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device. A memory DC exists only in memory. When the memory DC is created, its display surface is exactly one monochrome pixel wide and one monochrome pixel high.
Before an application can use a memory DC for drawing operations, it must select a bitmap of the correct width and height into the DC. To select a bitmap into a DC, use the
CreateCompatibleBitmap function, specifying the height, width, and color organization required. When a memory DC is created, all attributes are set to normal default values. The memory DC can be used as a normal DC. You can set the attributes; obtain the current settings of its attributes; and select pens, brushes, and regions.
Parameters
hdc
[in] Handle to an existing DC.
If this handle is NULL, the function creates a memory DC compatible with the application's current screen.
关于FillRect
int FillRect(HDC hDC,//handle to DC CONST RECT *lprc,// rectangle
HBRUSH hbr // handle to brush);
The FillRect function fills a rectangle by using the specified brush. This function includes the left and top borders, but excludes the right and bottom borders of the rectangle. The brush identified by the hbr parameter may be either a handle to a logical brush or a color value. If specifying a handle to a logical brush, call one of the following functions to obtain the handle: CreateHatchBrush, CreatePatternBrush, or CreateSolidBrush. Additionally, you may retrieve a handle to one of the stock brushes by using the GetStockObject function. If specifying a color value for the hbr parameter, it must be one of the standard system colors (the value 1 must be added to the chosen color). For example:
FillRect(hdc, &rect, (HBRUSH) (COLOR_WINDOW+1));For a list of all the standard system colors, see GetSysColor.
关于SetBkColor
COLORREF SetBkColor(HDC hdc, // handle to DC
COLORREF crColor // background color value);
The SetBkColor function sets the current background color to the specified color value, or to the nearest physical color if the device cannot represent the specified color value. This function fills the gaps between styled lines drawn using a pen created by the
CreatePen function; it does not fill the gaps between styled lines drawn using a pen created by the
ExtCreatePen function. The SetBKColor function also sets the background colors for
TextOut and
ExtTextOut. If the background mode is OPAQUE, the background color is used to fill gaps between styled lines, gaps between hatched lines in brushes, and character cells. The background color is also used when converting bitmaps from color to monochrome and vice versa.
例如:
::FillRect(hDC, &rRect, (HBRUSH)RGB(255, 255, 255));
COLORREF crOldColor = ::SetBkColor(hDC, RGB(255,255,255));
关于BitBlt
SRCAND Combines the colors of the source and destination rectangles by using the Boolean AND operator.
SRCPAINT Combines the colors of the source and destination rectangles by using the Boolean OR operator.
DeleteDC
关于DeleteDC
BOOL DeleteDC(HDC hdc // handle to DC);
The DeleteDC function deletes the specified device context (DC). An application must not delete a DC whose handle was obtained by calling the
GetDC function. Instead, it must call the
ReleaseDC function to free the DC.
例如:
hDC = ::CreateCompatibleDC(pDC->m_hDC);
::DeleteDC(hDC);
关于CDC::DrawText
virtual int DrawText(LPCTSTR lpszString,int nCount,LPRECT lpRect,
UINT nFormat);
int DrawText(const CString& str,LPRECT lpRect,UINT nFormat);
Call this member function to format text in the given rectangle. To specify additional formatting options, use
CDC::DrawTextEx.
Parameters
lpszString
Points to the string to be drawn.
If nCount is –1, the string must be null-terminated.
nCount
Specifies the number of chars in the string. If nCount is –1, then lpszString is assumed to be a long pointer to a null-terminated string and DrawText computes the character count automatically.
lpRect
Points to a
RECT structure or
CRect object that contains the rectangle (in logical coordinates) in which the text is to be formatted.
str
A
CString object that contains the specified characters to be drawn.
nFormat
Specifies the method of formatting the text. It can be any combination of the values described for the uFormat parameter in DrawText in the Platform SDK. (combine using the bitwise OR operator):
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.
DT_CENTER Centers text horizontally in the rectangle.
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.
关于CDC::DrawFocusRect
void DrawFocusRect(LPCRECT lpRect);
Draws a rectangle in the style used to indicate that the rectangle has the focus.Since this is a Boolean XOR function, calling this function a second time with the same rectangle removes the rectangle from the display. The rectangle drawn by this function cannot be scrolled. To scroll an area containing a rectangle drawn by this function, first call DrawFocusRect to remove the rectangle from the display, then scroll the area, and then call DrawFocusRect again to draw the rectangle in the new position.Caution DrawFocusRect works only in MM_TEXT mode. In other modes, this function does not draw the focus rectangle correctly, but it does not return error values.
关于CToolTipCtrl::Create
virtual BOOL CToolTipCtrl::Create(CWnd* pParentWnd,DWORD dwStyle = 0);
Creates a tool tip control and attaches it to a CToolTipCtrl object.You construct a CToolTipCtrl in two steps. First, call the constructor to construct the CToolTipCtrl object, and then call Create to create the tool tip control and attach it to the CToolTipCtrl object.
The dwStyle parameter can be any combination of
Window Styles. In addition, a tool tip control has two class-specific styles: TTS_ALWAYSTIP and TTS_NOPREFIX.
Style
|
Meaning
|
TTS_ALWAYSTIP
|
Specifies that the tool tip will appear when the cursor is on a tool, regardless of whether the tool tip control's owner window is active or inactive. Without this style, the tool tip control appears when the tool's owner window is active, but not when it is inactive.
|
TTS_NOPREFIX
|
This style prevents the system from stripping the ampersand (&) character from a string. If a tool tip control does not have the TTS_NOPREFIX style, the system automatically strips ampersand characters, allowing an application to use the same string as both a menu item and as text in a tool tip control.
|
A tool tip control has the WS_POPUP and WS_EX_TOOLWINDOW window styles, regardless of whether you specify them when creating the control.
To create a tool tip control with extended windows styles, call
CToolTipCtrl::CreateEx instead of Create.
关于CToolTipCtrl::Activate
void CToolTipCtrl::Activate(BOOL bActivate);
Call this function to activate or deactivate a tool tip control.When a tool tip control is active, the tool tip information appears when the cursor is on a tool that is registered with the control; when it is inactive, the tool tip information does not appear, even when the cursor is on a tool.
关于TTM_SETMAXTIPWIDTH
TTM_SETMAXTIPWIDTH
wParam = 0;
lParam = (LPARAM)(INT) iWidth;
Sets the maximum width for a ToolTip window. The maximum ToolTip width value does not indicate a ToolTip window's actual width. Rather, if a ToolTip string exceeds the maximum width, the control breaks the text into multiple lines, using spaces to determine line breaks. If the text cannot be segmented into multiple lines, it will be displayed on a single line. The length of this line may exceed the maximum ToolTip width.
关于TTM_SETTITLE
TTM_SETTITLE
wParam = icon;
lParam = (LPCTSTR) pszTitle;
Adds a standard icon and title string to a ToolTip.
Parameters
icon
Set wParam to one of the following values to specify the icon to be displayed.
0
|
No icon.
|
1
|
Info icon.
|
2
|
Warning icon
|
3
|
Error Icon
|
Public Const TTI_NONE = 0 '无图标
Public Const TTI_INFO = 1 '信息
Public Const TTI_WARNING = 2 '警告
Public Const TTI_ERROR = 3 '错误
pszTitle
A pointer to the title string. You must assign a value to pszTitle.
关于TTM_SETTITLE
#ifndef TTM_SETTITLE
#define TTM_SETTITLEA (WM_USER+32)//wParam=TTI_*,lParam=char* szTitle
#define TTM_SETTITLEW (WM_USER+33)//wParam=TTI_*,lParam=wchar* szTitle
#ifdef UNICODE
#define TTM_SETTITLE TTM_SETTITLEW
#else
#define TTM_SETTITLE TTM_SETTITLEA
#endif
#endif
how to define a struct using typedef
typedef struct _STRUCT_ICONS
{
HICON hIcon; // Handle to icon
DWORD dwWidth; // Width of icon
DWORD dwHeight; // Height of icon
} STRUCT_ICONS;
关于CToolTipCtrl::RelayEvent
void CToolTipCtrl::RelayEvent(LPMSG lpMsg );
Passes a mouse message to a tool tip control for processing.
Parameters
lpMsg
Pointer to a MSG structure that contains the message to relay.
Remarks
A tool tip control processes only the following messages, which are sent to it by RelayEvent:
WM_LBUTTONDOWN
|
WM_MOUSEMOVE
|
WM_LBUTTONUP
|
WM_RBUTTONDOWN
|
WM_MBUTTONDOWN
|
WM_RBUTTONUP
|
WM_MBUTTONUP
|
|
关于CWnd::PreTranslateMessage
virtual BOOL CWnd::PreTranslateMessage(MSG* pMsg);
Used by class
CWinApp to translate window messages before they are dispatched to the TranslateMessage and DispatchMessage Windows functions.
Nonzero if the message was translated and should not be dispatched; 0 if the message was not translated and should be dispatched.
例如:
BOOL CButtonST::PreTranslateMessage(MSG* pMsg)
{
InitToolTip();
m_ToolTip.RelayEvent(pMsg);
if (pMsg->message == WM_LBUTTONDBLCLK)
pMsg->message = WM_LBUTTONDOWN;
return CButton::PreTranslateMessage(pMsg);
}
关于MAKEINTRESOURCE
LPTSTR MAKEINTRESOURCE(WORD wInteger);
The MAKEINTRESOURCE macro converts an integer value to a resource type compatible with the resource-management functions. This macro is used in place of a string containing the name of the resource. The return value should be passed only to functions which explicitly indicate that they accept MAKEINTRESOURCE as a parameter. For example, the resource management functions allow the return value of MAKEINTRESOURCE to be passed as the lpType or lpName parameters.
关于AfxFindResourceHandle
HINSTANCE AFXAPI AfxFindResourceHandle(LPCTSTR lpszName,
LPCTSTR lpszType);
Use AfxFindResourceHandle to walk the resource chain and locate a specific resource by resource ID and resource type.
Parameters
lpszName
A pointer to a string containing the resource ID.
lpszType
A pointer to the type of resource. For a list of resource types, see FindResource in the Platform SDK.
The following are the predefined resource types.
Value
|
Meaning
|
RT_ACCELERATOR
|
Accelerator table
|
RT_ANICURSOR
|
Animated cursor
|
RT_ANIICON
|
Animated icon
|
RT_BITMAP
|
Bitmap resource
|
RT_CURSOR
|
Hardware-dependent cursor resource
|
RT_DIALOG
|
Dialog box
|
RT_DLGINCLUDE
|
|
RT_FONT
|
Font resource
|
RT_FONTDIR
|
Font directory resource
|
RT_GROUP_CURSOR
|
Hardware-independent cursor resource
|
RT_GROUP_ICON
|
Hardware-independent icon resource
|
RT_HTML
|
HTML
|
RT_ICON
|
Hardware-dependent icon resource
|
RT_MANIFEST
|
Windows XP: Fusion XML Manifest
|
RT_MENU
|
Menu resource
|
RT_MESSAGETABLE
|
Message-table entry
|
RT_PLUGPLAY
|
Plug and Play resource
|
RT_RCDATA
|
Application-defined resource (raw data)
|
RT_STRING
|
String-table entry
|
RT_VERSION
|
Version resource
|
RT_VXD
|
VXD
|
Return Value
A handle to the module that contains the resource.
Remarks
AfxFindResourceHandle finds the specific resource and returns a handle to the module that contains the resource. The resource might be in any extension DLL you have loaded. AfxFindResourceHandle tells you which one has the resource.
例如:
// Find correct resource handle
HINSTANCE hInstResource = AfxFindResourceHandle(MAKEINTRESOURCE(nIconIn),
RT_GROUP_ICON);
关于LoadImage
HANDLE LoadImage(
HINSTANCE hinst, // handle to instance
LPCTSTR lpszName, // image to load
UINT uType, // image type
int cxDesired, // desired width
int cyDesired, // desired height
UINT fuLoad // load options
);
The LoadImage function loads an icon, cursor, animated cursor, or bitmap.
Parameters
uType
[in] Specifies the type of image to be loaded. This parameter can be one of the following values.
Value
|
Meaning
|
IMAGE_BITMAP
|
Loads a bitmap.
|
IMAGE_CURSOR
|
Loads a cursor.
|
IMAGE_ICON
|
Loads an icon.
|
cxDesired
[in] Specifies the width, in pixels, of the icon or cursor. If this parameter is zero and the fuLoad parameter is LR_DEFAULTSIZE, the function uses the SM_CXICON or SM_CXCURSOR system metric value to set the width. If this parameter is zero and LR_DEFAULTSIZE is not used, the function uses the actual resource width.
fuLoad
[in] This parameter can be one or more of the following values.
Value
|
Meaning
|
LR_DEFAULTCOLOR
|
The default flag; it does nothing. All it means is "not LR_MONOCHROME".
|
LR_CREATEDIBSECTION
|
When the uType parameter specifies IMAGE_BITMAP, causes the function to return a DIB section bitmap rather than a compatible bitmap. This flag is useful for loading a bitmap without mapping it to the colors of the display device.
|
LR_DEFAULTSIZE
|
Uses the width or height specified by the system metric values for cursors or icons, if the cxDesired or cyDesired values are set to zero. If this flag is not specified and cxDesired and cyDesired are set to zero, the function uses the actual resource size. If the resource contains multiple images, the function uses the size of the first image.
|
LR_LOADFROMFILE
|
Loads the image from the file specified by the lpszName parameter. If this flag is not specified, lpszName is the name of the resource.
|
LR_LOADMAP3DCOLORS
|
Searches the color table for the image and replaces the following shades of gray with the corresponding 3-D color:
|
|
Color
|
Replaced with
|
|
Dk Gray,
RGB(128,128,128)
|
COLOR_3DSHADOW
|
|
Gray,
RGB(192,192,192)
|
COLOR_3DFACE
|
|
Lt Gray,
RGB(223,223,223)
|
COLOR_3DLIGHT
|
|
Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.
|
LR_LOADTRANSPARENT
|
Retrieves the color value of the first pixel in the image and replaces the corresponding entry in the color table with the default window color (COLOR_WINDOW). All pixels in the image that use that entry become the default window color. This value applies only to images that have corresponding color tables.
Do not use this option if you are loading a bitmap with a color depth greater than 8bpp.
If fuLoad includes both the LR_LOADTRANSPARENT and LR_LOADMAP3DCOLORS values, LRLOADTRANSPARENT takes precedence. However, the color table entry is replaced with COLOR_3DFACE rather than COLOR_WINDOW.
|
LR_MONOCHROME
|
Loads the image in black and white.
|
LR_SHARED
|
Shares the image handle if the image is loaded multiple times. If LR_SHARED is not set, a second call to LoadImage for the same resource will load the image again and return a different handle.
When you use this flag, the system will destroy the resource when it is no longer needed.
Do not use LR_SHARED for images that have non-standard sizes, that may change after loading, or that are loaded from a file.
When loading a system icon or cursor, you must use LR_SHARED or the function will fail to load the resource.
Windows 95/98/Me: The function finds the first image with the requested resource name in the cache, regardless of the size requested.
|
LR_VGACOLOR
|
Uses true VGA colors.
|
When you are finished using a bitmap, cursor, or icon you loaded without specifying the LR_SHARED flag, you can release its associated memory by calling one of the functions in the following table.
Resource
|
Release function
|
Bitmap
|
DeleteObject
|
Cursor
|
DestroyCursor
|
Icon
|
DestroyIcon
|
The system automatically deletes these resources when the process that created them terminates, however, calling the appropriate function saves memory and decreases the size of the process's working set.
关于ICONINFO
typedef struct _ICONINFO {
BOOL fIcon;
DWORD xHotspot;
DWORD yHotspot;
HBITMAP hbmMask;
HBITMAP hbmColor;
} ICONINFO;
The ICONINFO structure contains information about an icon or a cursor.
Members
fIcon
Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies an icon; FALSE specifies a cursor.
xHotspot
Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
yHotspot
Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
hbmMask
Specifies the icon bitmask bitmap. If this structure defines a black and white icon, this bitmask is formatted so that the upper half is the icon AND bitmask and the lower half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. If this structure defines a color icon, this mask only defines the AND bitmask of the icon.
hbmColor
Handle to the icon color bitmap. This member can be optional if this structure defines a black and white icon. The AND bitmask of hbmMask is applied with the SRCAND flag to the destination; subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag.
关于GetIconInfo
BOOL GetIconInfo(HICON hIcon, // icon handle
PICONINFO piconinfo // icon structure);
The GetIconInfo function retrieves information about the specified icon or cursor.
例如:
::GetIconInfo(hIconIn, &ii);
m_csIcons[0].dwWidth = (DWORD)(ii.xHotspot * 2);
m_csIcons[0].dwHeight = (DWORD)(ii.yHotspot * 2);
::DeleteObject(ii.hbmMask);
::DeleteObject(ii.hbmColor);
关于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.
例如:
BITMAP csBitmapSize;
::GetObject(hBitmap, sizeof(csBitmapSize), &csBitmapSize);
m_csBitmaps[0].dwWidth = (DWORD)csBitmapSize.bmWidth;
m_csBitmaps[0].dwHeight = (DWORD)csBitmapSize.bmHeight;
关于GetDC
HDC GetDC(HWND hWnd // handle to window);
The GetDC function retrieves a handle to a display device context (DC) for the client area of a specified window or for the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC. The
GetDCEx function is an extension to GetDC, which gives an application more control over how and whether clipping occurs in the client area.
Parameters
hWnd
[in] Handle to the window whose DC is to be retrieved. If this value is NULL, GetDC retrieves the DC for the entire screen.
The GetDC function retrieves a common, class, or private DC depending on the class style of the specified window. For class and private DCs, GetDC leaves the previously assigned attributes unchanged. However, for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. For example, the default font is System, which is a bitmap font. Because of this, the handle for a common DC returned by GetDC does not tell you what font, color, or brush was used when the window was drawn. Note that the handle to the DC can only be used by a single thread at any one time.
After painting with a common DC, the ReleaseDC function must be called to release the DC. Class and private DCs do not have to be released. ReleaseDC must be called from the same thread that called GetDC. The number of DCs is limited only by available memory.
Windows 95/98/Me: There are only 5 common DCs available per thread, thus failure to release a DC can prevent other applications from accessing one.
关于CreateBitmap
HBITMAP CreateBitmap(
int nWidth, // bitmap width, in pixels
int nHeight, // bitmap height, in pixels
UINT cPlanes, // number of color planes
UINT cBitsPerPel, // number of bits to identify color
CONST VOID *lpvBits // color data array
);
The CreateBitmap function creates a bitmap with the specified width, height, and
color format (color planes and bits-per-pixel).
Parameters
nWidth
[in] Specifies the bitmap width, in pixels.
nHeight
[in] Specifies the bitmap height, in pixels.
cPlanes
[in] Specifies the number of color planes used by the device.
cBitsPerPel
[in] Specifies the number of bits required to identify the color of a single pixel.
lpvBits
[in] Pointer to an array of color data used to set the colors in a rectangle of pixels. Each scan line in the rectangle must be word aligned (scan lines that are not word aligned must be padded with zeros). If this parameter is NULL, the contents of the new bitmap is undefined.
The CreateBitmap function creates a device-dependent bitmap. After a bitmap is created, it can be selected into a device context by calling the
SelectObject function. However, the bitmap can only be selected into a device context if the bitmap and the DC have the same format.
The CreateBitmap function can be used to create color bitmaps. However, for performance reasons applications should use CreateBitmap to create monochrome bitmaps and
CreateCompatibleBitmap to create color bitmaps. Whenever a color bitmap returned from CreateBitmap is selected into a device context, the system checks that the bitmap matches the format of the device context it is being selected into. Because CreateCompatibleBitmap takes a device context, it returns a bitmap that has the same format as the specified device context. Thus, subsequent calls to SelectObject are faster with a color bitmap from CreateCompatibleBitmap than with a color bitmap returned from CreateBitmap.
If the bitmap is monochrome, zeros represent the foreground color and ones represent the background color for the destination device context.
If an application sets the nWidth or nHeight parameters to zero, CreateBitmap returns the handle to a 1-by-1 pixel, monochrome bitmap.
When you no longer need the bitmap, call the
DeleteObject function to delete it.
Windows 95/98/Me: The created bitmap cannot exceed 16MB in size.
例如:
BITMAP bmp;
::GetObject(csII.hbmColor, sizeof(BITMAP), &bmp)
csII.hbmColor = ::CreateBitmap(dwWidth, dwHeight,
bmp.bmPlanes, bmp.bmBitsPixel,NULL);
关于GetPixel
COLORREF GetPixel(
HDC hdc, // handle to DC
int nXPos, // x-coordinate of pixel
int nYPos // y-coordinate of pixel
);
The GetPixel function retrieves the red, green, blue (RGB) color value of the pixel at the specified coordinates. The pixel must be within the boundaries of the current clipping region. Not all devices support GetPixel. An application should call
GetDeviceCaps to determine whether a specified device supports this function. The return value is the RGB value of the pixel. If the pixel is outside of the current clipping region, the return value is CLR_INVALID.
关于SetPixel
COLORREF SetPixel(
HDC hdc, // handle to DC
int X, // x-coordinate of pixel
int Y, // y-coordinate of pixel
COLORREF crColor // pixel color
);
The SetPixel function sets the pixel at the specified coordinates to the specified color. If the function succeeds, the return value is the RGB value that the function sets the pixel to. This value may differ from the color specified by crColor; that occurs when an exact match for the specified color cannot be found.If the function fails, the return value is –1.
关于CreateIconIndirect
HICON CreateIconIndirect(PICONINFO piconinfo // icon information);
The CreateIconIndirect function creates an icon or cursor from an ICONINFO structure. The system copies the bitmaps in the ICONINFO structure before creating the icon or cursor. Because the system may temporarily select the bitmaps in a device context, the hbmMask and hbmColor members of the
ICONINFO structure should not already be selected into a device context. The application must continue to manage the original bitmaps and delete them when they are no longer necessary.
When you are finished using the icon, destroy it using the
DestroyIcon function.
关于ReleaseDC
int ReleaseDC(HWND hWnd,// handle to window HDC hDC // handle to DC);
The ReleaseDC function releases a device context (DC), freeing it for use by other applications. The effect of the ReleaseDC function depends on the type of DC. It frees only common and window DCs. It has no effect on class or private DCs.
Parameters
hWnd
[in] Handle to the window whose DC is to be released.
hDC
[in] Handle to the DC to be released.
The application must call the ReleaseDC function for each call to the
GetWindowDC function and for each call to the GetDC function that retrieves a common DC. An application cannot use the ReleaseDC function to release a DC that was created by calling the
CreateDC function; instead, it must use the
DeleteDC function. ReleaseDC must be called from the same thread that called GetDC.
关于CStringT::LoadString
BOOL CStringT::LoadString(HINSTANCE hInstance,UINT nID,
WORD wLanguageID);
BOOL CStringT::LoadString(HINSTANCE hInstance,UINT nID);
BOOL CStringT::LoadString(UINT nID);
Reads a Windows string resource, identified by nID, into an existing CStringT object. Loads the string resource (nID) from the specified module (hInstance) using the specified language (wLanguage).
Parameters
hInstance
A handle to the instance of the module.
nID
A Windows string resource ID.
wLanguageID
The language of the string resource.
关于CToolTipCtrl::GetToolCount
int CToolTipCtrl::GetToolCount( ) const;
Retrieves a count of the tools registered with the tool tip control.
关于CToolTipCtrl::AddTool
BOOL CToolTipCtrl::AddTool(
CWnd* pWnd,
UINT nIDText,
LPCRECT lpRectTool = NULL,
UINT_PTR nIDTool = 0
);
BOOL CToolTipCtrl::AddTool(
CWnd* pWnd,
LPCTSTR lpszText = LPSTR_TEXTCALLBACK,
LPCRECT lpRectTool = NULL,
UINT_PTR nIDTool = 0
);
Registers a tool with the tool tip control. A tool tip control can be associated with more than one tool. Call this function to register a tool with the tool tip control, so that the information stored in the tool tip is displayed when the cursor is on the tool.You cannot set a tool tip to a static control using AddTool.
Parameters
pWnd
Pointer to the window that contains the tool.
nIDText
ID of the string resource that contains the text for the tool.
lpRectTool
Pointer to a RECT structure containing coordinates of the tool's bounding rectangle. The coordinates are relative to the upper-left corner of the client area of the window identified by pWnd.
nIDTool
ID of the tool.
lpszText
Pointer to the text for the tool. If this parameter contains the value LPSTR_TEXTCALLBACK, TTN_NEEDTEXT notification messages go to the parent of the window that pWnd points to.
例如:
// If there is no tooltip defined then add it
if (m_ToolTip.GetToolCount() == 0)
{
CRect rectBtn;
GetClientRect(rectBtn);
m_ToolTip.AddTool(this, lpszText, rectBtn, 1);
} // if
关于CToolTipCtrl::UpdateTipText
void CToolTipCtrl::UpdateTipText(
LPCTSTR lpszText,
CWnd* pWnd,
UINT_PTR nIDTool = 0
);
void CToolTipCtrl::UpdateTipText(
UINT nIDText,
CWnd* pWnd,
UINT_PTR nIDTool = 0
);
Updates the tool tip text for this control's tools.
Parameters
lpszText
Pointer to the text for the tool.
pWnd
Pointer to the window that contains the tool.
nIDTool
ID of the tool.
nIDText
ID of the string resource that contains the text for the tool.
关于IsBadReadPtr
BOOL IsBadReadPtr(
CONST VOID *lp, // memory address
UINT_PTR ucb // size of block
);
The IsBadReadPtr function verifies that the calling process has read access to the specified range of memory. This function is typically used when working with pointers returned from third-party libraries, where you cannot determine the memory management behavior in the third-party DLL. Threads in a process are expected to cooperate in such a way that one will not free memory that the other needs. Use of this function does not negate the need to do this. If this is not done, the application may fail in an unpredictable manner. Dereferencing potentially invalid pointers can disable stack expansion in other threads. A thread exhausting its stack, when stack expansion has been disabled, results in the immediate termination of the parent process, with no pop-up error window or diagnostic information.If the calling process has read access to some, but not all, of the bytes in the specified memory range, the return value is nonzero. In a preemptive multitasking environment, it is possible for some other thread to change the process's access to the memory being tested. Even when the function indicates that the process has read access to the specified memory, you should use structured exception handling when attempting to access the memory. Use of structured exception handling enables the system to notify the process if an access violation exception occurs, giving the process an opportunity to handle the exception.
Parameters
lp
[in] Pointer to the first byte of the memory block.
ucb
[in] Specifies the size, in bytes, of the memory block. If this parameter is zero, the return value is zero.
Return Values
If the calling process has read access to all bytes in the specified memory range, the return value is zero.If the calling process does not have read access to all bytes in the specified memory range, the return value is nonzero. If the application is compiled as a debugging version, and the process does not have read access to all bytes in the specified memory range, the function causes an assertion and breaks into the debugger. Leaving the debugger, the function continues as usual, and returns a nonzero value This behavior is by design, as a debugging aid.
关于ToolTip Styles
ToolTip controls support a variety of control styles in addition to standard window styles. A ToolTip control always has the WS_POPUP and WS_EX_TOOLWINDOW window styles, regardless of whether you specify them when creating the control.
The following control styles are used with ToolTip controls:
TTS_BALLOON
Version 5.80. Indicates that the ToolTip control has the appearance of a cartoon "balloon," with rounded corners and a stem pointing to the item.
例如:
DWORD dwToolTipStyle = 0;
dwToolTipStyle |= TTS_BALLOON;
m_ToolTip.Create(this, dwToolTipStyle);
关于CWnd::GetNextDlgTabItem
CWnd* CWnd::GetNextDlgTabItem(
CWnd* pWndCtl,
BOOL bPrevious = FALSE) const;
COleControlSiteOrWnd* CWnd::GetNextDlgTabItem(
COleControlSiteOrWnd *pCurSiteOrWnd,
BOOL bPrevious) const;
Retrieves a pointer to the first control that was created with the
WS_TABSTOP style and that precedes or follows the specified control.
The input focus directs all subsequent keyboard input to this window. Any window that previously had the input focus loses it. The SetFocus member function sends a WM_KILLFOCUS message to the window that loses the input focus and a WM_SETFOCUS message to the window that receives the input focus. It also activates either the window or its parent.
If the current window is active but does not have the focus (that is, no window has the focus), any key pressed will produce the messages
WM_SYSCHAR,
WM_SYSKEYDOWN, or
WM_SYSKEYUP.
Parameters
pWndCtl
Identifies the control to be used as the starting point for the search.
pCurSiteOrWnd
Identifies the COleControlSiteOrWnd control. For more information about COleControlSiteOrWnd, see
CWnd::GetNextDlgGroupItem.
bPrevious
Specifies how the function is to search the dialog box. If TRUE, the function searches for the previous control in the dialog box; if FALSE, it searches for the next control.
Return Value
Pointer to the previous or next control that has the WS_TABSTOP style, if the member function is successful. The returned pointer may be temporary and should not be stored for later use.
例如:
CWnd*
pWnd = GetParent()->GetNextDlgTabItem(this);
if (pWnd)
pWnd->SetFocus();
else
GetParent()->SetFocus();
CWnd::SetFocus
CWnd* CWnd::SetFocus( );
Claims the input focus.
Return Value
A pointer to the window object that previously had the input focus. It is NULL if there is no such window. The returned pointer may be temporary and should not be stored.
关于CWnd::OnActivate
afx_msg void CWnd::OnActivate(
UINT nState,
CWnd* pWndOther,
BOOL bMinimized
);
The framework calls this member function when a CWnd object is being activated or deactivated. If the CWnd object is activated with a mouse click, it will also receive an
OnMouseActivate member function call.
This member function is called by the framework to allow your application to handle a Windows message. The parameters passed to your function reflect the parameters received by the framework when the message was received. If you call the base-class implementation of this function, that implementation will use the parameters originally passed with the message and not the parameters you supply to the function.
Parameters
nState
Specifies whether the CWnd is being activated or deactivated. It can be one of the following values:
· WA_INACTIVE The window is being deactivated.
· WA_ACTIVE The window is being activated through some method other than a mouse click (for example, by use of the keyboard interface to select the window).
· WA_CLICKACTIVE The window is being activated by a mouse click.
pWndOther
Pointer to the CWnd being activated or deactivated. The pointer can be NULL, and it may be temporary.
bMinimized
Specifies the minimized state of the CWnd being activated or deactivated. A value of TRUE indicates the window is minimized.
If TRUE, the CWnd is being activated; otherwise deactivated.
关于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.
Parameters
pWnd
Specifies a pointer to the window that contains the cursor. The pointer may be temporary and should not be stored for later use.
nHitTest
Specifies the
hit-test area code. The hit test determines the cursor's location.
message
Specifies the mouse message number.
Return Value
Nonzero to halt further processing, or 0 to continue.
Remarks
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.
关于SetCursor
HCURSOR SetCursor(
HCURSOR hCursor // handle to cursor
);
The SetCursor function sets the cursor shape. The cursor is set only if the new cursor is different from the previous cursor; otherwise, the function returns immediately. The cursor is a shared resource. A window should set the cursor shape only when the cursor is in its client area or when the window is capturing mouse input.
关于CWnd::OnCancelMode
afx_msg void CWnd::OnCancelMode( );
The framework calls this member function to inform CWnd to cancel any internal mode.If the CWnd object has the focus, its OnCancelMode member function is called when a dialog box or message box is displayed. This gives the CWnd the opportunity to cancel modes such as mouse capture.
The default implementation responds by calling the ReleaseCapture Windows function. Override this member function in your derived class to handle other modes.
关于CWnd::SetWindowPos
BOOL CWnd::SetWindowPos(
const CWnd* pWndInsertAfter,
int x,
int y,
int cx,
int cy,
UINT nFlags
);
Call this member function to change the size, position, and Z-order of child, pop-up, and top-level windows.
Parameters
pWndInsertAfter
Identifies the CWnd object that will precede this CWnd object in the Z-order. This parameter can be a pointer to a CWnd or a Pointer to one of the following values:
· wndBottom Places the window at the bottom of the Z-order. If this CWnd is a topmost window, the window loses its topmost status; the system places the window at the bottom of all other windows.
· wndTop Places the window at the top of the Z-order.
· wndTopMost Places the window above all nontopmost windows. The window maintains its topmost position even when it is deactivated.
· wndNoTopMost Repositions the window to the top of all nontopmost windows (that is, behind all topmost windows). This flag has no effect if the window is already a nontopmost window.
x
Specifies the new position of the left side of the window.
y
Specifies the new position of the top of the window.
cx
Specifies the new width of the window.
cy
Specifies the new height of the window.
nFlags
Specifies sizing and positioning options. This parameter can be a combination of the following:
· SWP_DRAWFRAME Draws a frame (defined when the window was created) around the window.
· SWP_FRAMECHANGED Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
· SWP_HIDEWINDOW Hides the window.
· SWP_NOACTIVATE Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or the nontopmost group (depending on the setting of the pWndInsertAfter parameter).
· SWP_NOCOPYBITS Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
· SWP_NOMOVE Retains current position (ignores the x and y parameters).
· SWP_NOOWNERZORDER Does not change the owner window's position in the Z-order.
· SWP_NOREDRAW Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title and scroll bars), and any part of the parent window uncovered as a result of the moved window. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that must be redrawn.
· SWP_NOREPOSITION Same as SWP_NOOWNERZORDER.
· SWP_NOSENDCHANGING Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
· SWP_NOSIZE Retains current size (ignores the cx and cy parameters).
· SWP_NOZORDER Retains current ordering (ignores pWndInsertAfter).
· SWP_SHOWWINDOW Displays the window.
例如:
SetWindowPos(NULL, -1, -1, m_csIcons[0].dwWidth, m_csIcons[0].dwHeight,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE);
关于DestroyCursor
BOOL DestroyCursor(HCURSOR hCursor // handle to cursor to destroy);
The DestroyCursor function destroys a cursor and frees any memory the cursor occupied. Do not use this function to destroy a shared cursor.
The DestroyCursor function destroys a nonshared cursor. Do not use this function to destroy a shared cursor. A shared cursor is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared cursor:
- LoadCursor
- LoadCursorFromFile
- LoadImage (if you use the LR_SHARED flag)
- CopyImage (if you use the LR_COPYRETURNORG flag and the hImage parameter is a shared cursor)
hCursor
[in] Handle to the cursor to be destroyed. The cursor must not be in use.
关于ON_MESSAGE
ON_MESSAGE(message, memberFxn )
Indicates which function will handle a user-defined message. User-defined messages are usually defined in the range WM_USER to 0x7FFF. User-defined messages are any messages that are not standard Windows WM_MESSAGE messages. There should be exactly one ON_MESSAGE macro statement in your message map for every user-defined message that must be mapped to a message-handler function. In addition to user-defined messages, ON_MESSAGE handles less common Windows messages. For more information, see the Knowledge Base article Q99848.
Parameters
message
The message ID.
memberFxn
The name of the message-handler function to which the message is mapped.
关于BM_SETSTYLE
SendMessage(
(HWND) hWnd, // handle to destination window
BM_SETSTYLE, // message to send
(WPARAM) wParam, // button style
(LPARAM) lParam // redraw state
);
An application sends a BM_SETSTYLE message to change the style of a button.
Parameters
wParam
Specifies the new button style. This parameter can be a combination of button styles. For a table of button styles, see
Button Styles.
lParam
The low-order word of lParam specifies whether the button is to be redrawn. A value of TRUE redraws the button; a value of FALSE does not redraw the button.
关于CWnd::DefWindowProc
virtual LRESULT CWnd::DefWindowProc(
UINT message,
WPARAM wParam,
LPARAM lParam
);
Calls the default window procedure, which provides default processing for any window message that an application does not process.This member function ensures that every message is processed. It should be called with the same parameters as those received by the window procedure.
例如:
LRESULT CButtonST::OnSetStyle(WPARAM wParam, LPARAM lParam)
{
UINT nNewType = (wParam & BS_TYPEMASK);
// Update default state flag
if (nNewType == BS_DEFPUSHBUTTON)
{
m_bIsDefault = TRUE;
} // if
else if (nNewType == BS_PUSHBUTTON)
{
// Losing default state always allowed
m_bIsDefault = FALSE;
} // if
// Can't change control type after owner-draw is set.
// Let the system process changes to other style bits
// and redrawing, while keeping owner-draw style.
return DefWindowProc(BM_SETSTYLE,
(wParam & ~BS_TYPEMASK) | BS_OWNERDRAW, lParam);
} // End of OnSetStyle
关于BM_SETCHECK
SendMessage(
(HWND) hWnd, // handle to destination window
BM_SETCHECK, // message to send
(WPARAM) wParam, // check state
(LPARAM) lParam // not used; must be zero
);
An application sends a BM_SETCHECK message to set the check state of a radio button or check box. The BM_SETCHECK message has no effect on push buttons.
wParam
Specifies the check state. This parameter can be one of the following values.
Value
|
Meaning
|
BST_CHECKED
|
Sets the button state to checked.
|
BST_INDETERMINATE
|
Sets the button state to grayed, indicating an indeterminate state. Use this value only if the button has the BS_3STATE or BS_AUTO3STATE style.
|
BST_UNCHECKED
|
Sets the button state to cleared.
|
lParam
This parameter is not used.
关于BM_GETCHECK
SendMessage(
(HWND) hWnd, // handle to destination window
BM_GETCHECK, // message to send
(WPARAM) wParam, // not used; must be zero
(LPARAM) lParam // not used; must be zero
);
An application sends a BM_GETCHECK message to retrieve the check state of a radio button or check box.
Return Values
The return value from a button created with the BS_AUTOCHECKBOX, BS_AUTORADIOBUTTON, BS_AUTO3STATE, BS_CHECKBOX, BS_RADIOBUTTON, or BS_3STATE style can be one of the following.
Value
|
Meaning
|
BST_CHECKED
|
Button is checked.
|
BST_INDETERMINATE
|
Button is grayed, indicating an indeterminate state (applies only if the button has the BS_3STATE or BS_AUTO3STATE style).
|
BST_UNCHECKED
|
Button is cleared
|
If the button has any other style, the return value is zero.
关于TRACKMOUSEEVENT
typedef struct tagTRACKMOUSEEVENT {
DWORD cbSize;
DWORD dwFlags;
HWND hwndTrack;
DWORD dwHoverTime;
} TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;
The TRACKMOUSEEVENT structure is used by the TrackMouseEvent function to track when the mouse pointer leaves a window or hovers over a window for a specified amount of time.
Members
cbSize
Specifies the size of the TRACKMOUSEEVENT structure.
dwFlags
Specifies the services requested. This member can be a combination of the following values.
Value
|
Meaning
|
TME_CANCEL
|
The caller wants to cancel a prior tracking request.
The caller should also specify the type of tracking that it wants to cancel. For example, to cancel hover tracking, the caller must pass the TME_CANCEL and TME_HOVER flags.
|
TME_HOVER
|
The caller wants hover notification. Notification is delivered as a WM_MOUSEHOVER message.
If the caller requests hover tracking while hover tracking is already active, the hover timer will be reset.
This flag is ignored if the mouse pointer is not over the specified window or area.
|
TME_LEAVE
|
The caller wants leave notification. Notification is delivered as a WM_MOUSELEAVE message.
If the mouse is not over the specified window or area, a leave notification is generated immediately and no further tracking is performed.
|
TME_NONCLIENT
|
Windows 98/Me, Windows 2000/XP: The caller wants hover and leave notification for the nonclient areas. Notification is delivered as WM_NCMOUSEHOVER and WM_NCMOUSELEAVE messages.
|
TME_QUERY
|
The function fills in the structure instead of treating it as a tracking request. The structure is filled such that had that structure been passed to TrackMouseEvent, it would generate the current tracking. The only anomaly is that the hover time-out returned is always the actual time-out and not HOVER_DEFAULT, if HOVER_DEFAULT was specified during the original TrackMouseEvent request.
|
hwndTrack
Specifies a handle to the window to track.
dwHoverTime
Specifies the hover time-out (if TME_HOVER was specified in dwFlags), in milliseconds. Can be HOVER_DEFAULT, which means to use the system default hover time-out.
Remarks
The system default hover time-out is initially the menu drop-down time, which is 400 milliseconds. You can
call SystemParametersInfo and use SPI_GETMOUSEHOVERTIME to retrieve the default hover time-out.The system default hover rectangle is the same as the double-click rectangle. You can call SystemParametersInfo and use SPI_GETMOUSEHOVERWIDTH and SPI_GETMOUSEHOVERHEIGHT to retrieve the size of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message.
关于CWnd::ClientToScreen
void CWnd::ClientToScreen(LPPOINT lpPoint) const;
void CWnd::ClientToScreen(LPRECT lpRect) const;
Converts the client coordinates of a given point or rectangle on the display to screen coordinates.The ClientToScreen member function uses the client coordinates in the POINT or RECT structure or the CPoint or CRect object pointed to by lpPoint or lpRect to compute new screen coordinates; it then replaces the coordinates in the structure with the new coordinates. The new screen coordinates are relative to the upper-left corner of the system display. The ClientToScreen member function assumes that the given point or rectangle is in client coordinates.
关于CWnd::WindowFromPoint
static CWnd* PASCAL CWnd::WindowFromPoint(POINT point);
Retrieves the window that contains the specified point; point must specify the screen coordinates of a point on the screen. A pointer to the window object in which the point lies. It is NULL if no window exists at the given point. The returned pointer may be temporary and should not be stored for later use. WindowFromPoint does not retrieve a hidden or disabled window, even if the point is within the window. An application should use the
ChildWindowFromPoint member function for a nonrestrictive search.
Parameters
point
Specifies a
CPoint object or
POINT data structure that defines the point to be checked.
关于CWnd::OnMouseMove
afx_msg void CWnd::OnMouseMove(UINT nFlags,CPoint point);
The framework calls this member function when the mouse cursor moves.
If the mouse is not captured, the WM_MOUSEMOVE message is received by the CWnd object beneath the mouse cursor; otherwise, the message goes to the window that has captured the mouse.
Parameters
nFlags
Indicates whether various virtual keys are down. This parameter can be any combination of the following values:
· MK_CONTROL Set if the CTRL key is down.
· MK_LBUTTON Set if the left mouse button is down.
· MK_MBUTTON Set if the middle mouse button is down.
· MK_RBUTTON Set if the right mouse button is down.
· MK_SHIFT Set if the SHIFT key is down.
point
Specifies the x- and y-coordinate of the cursor. These coordinates are always relative to the upper-left corner of the window.
关于CWnd::GetActiveWindow
static CWnd* PASCAL CWnd::GetActiveWindow( );
Retrieves a pointer to the active window.
The active window is either the window that has the current input focus or the window explicitly made active by the SetActiveWindow member function.
Return Value
The active window or NULL if no window was active at the time of the call. The pointer may be temporary and should not be stored for later use.
关于PlaySound
BOOL PlaySound(
LPCSTR pszSound,
HMODULE hmod,
DWORD fdwSound
);
The PlaySound function plays a sound specified by the given filename, resource, or system event. (A system event may be associated with a sound in the registry or in the WIN.INI file.) The sound specified by pszSound must fit into available physical memory and be playable by an installed waveform-audio device driver. PlaySound searches the following directories for sound files: the current directory; the Windows directory; the Windows system directory; directories listed in the PATH environment variable; and the list of directories mapped in a network. For more information about the directory search order, see the documentation for the OpenFile function.
If it cannot find the specified sound, PlaySound uses the default system event sound entry instead. If the function can find neither the system default entry nor the default sound, it makes no sound and returns FALSE.
Windows 95/98/Me
: PlaySoundW 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.
Parameters
pszSound
A string that specifies the sound to play. If this parameter is NULL, any currently playing waveform sound is stopped. To stop a non-waveform sound, specify SND_PURGE in the fdwSound parameter.
Three flags in fdwSound (SND_ALIAS, SND_FILENAME, and SND_RESOURCE) determine whether the name is interpreted as an alias for a system event, a filename, or a resource identifier. If none of these flags are specified, PlaySound searches the registry or the WIN.INI file for an association with the specified sound name. If an association is found, the sound event is played. If no association is found in the registry, the name is interpreted as a filename.
hmod
Handle to the executable file that contains the resource to be loaded. This parameter must be NULL unless SND_RESOURCE is specified in fdwSound.
fdwSound
Flags for playing the sound. The following values are defined.
Value
|
Meaning
|
SND_APPLICATION
|
The sound is played using an application-specific association.
|
SND_ALIAS
|
The pszSound parameter is a system-event alias in the registry or the WIN.INI file. Do not use with either SND_FILENAME or SND_RESOURCE.
|
SND_ALIAS_ID
|
The pszSound parameter is a predefined sound identifier.
|
SND_ASYNC
|
The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call PlaySound with pszSound set to NULL.
|
SND_FILENAME
|
The pszSound parameter is a filename.
|
SND_LOOP
|
The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. You must also specify the SND_ASYNC flag to indicate an asynchronous sound event.
|
SND_MEMORY
|
A sound event's file is loaded in RAM. The parameter specified by pszSound must point to an image of a sound in memory.
|
SND_NODEFAULT
|
No default sound event is used. If the sound cannot be found, PlaySound returns silently without playing the default sound.
|
SND_NOSTOP
|
The specified sound event will yield to another sound event that is already playing. If a sound cannot be played because the resource needed to generate that sound is busy playing another sound, the function immediately returns FALSE without playing the requested sound.
If this flag is not specified, PlaySound attempts to stop the currently playing sound so that the device can be used to play the new sound.
|
SND_NOWAIT
|
If the driver is busy, return immediately without playing the sound.
|
SND_PURGE
|
Sounds are to be stopped for the calling task. If pszSound is not NULL, all instances of the specified sound are stopped. If pszSound is NULL, all sounds that are playing on behalf of the calling task are stopped.
You must also specify the instance handle to stop SND_RESOURCE events.
|
SND_RESOURCE
|
The pszSound parameter is a resource identifier; hmod must identify the instance that contains the resource.
|
SND_SYNC
|
Synchronous playback of a sound event. PlaySound returns after the sound event completes.
|
例如:
#ifdef BTNST_USE_SOUND
#pragma comment(lib, "winmm.lib")
#include <Mmsystem.h>
#endif
dwFlags = SND_NODEFAULT | SND_NOWAIT;
dwFlags |= hMod ? SND_RESOURCE : SND_FILENAME;
dwFlags |= bPlayAsync ? SND_ASYNC : SND_SYNC;
::PlaySound(lpszSound, hMod, dwFlags);
#pragma comment( "comment-type" [, commentstring] )
Places a comment record into an object file or executable file. The comment-type is one of five predefined identifiers, described below, that specifies the type of comment record. The optional commentstring is a string literal that provides additional information for some comment types. Because commentstring is a string literal, it obeys all the rules for string literals with respect to escape characters, embedded quotation marks ("), and concatenation.
compiler
Places the name and version number of the compiler in the object file. This comment record is ignored by the linker. If you supply a commentstring parameter for this record type, the compiler generates a warning.
exestr
Places commentstring in the object file. At link time this string is placed in the executable file. The string is not loaded into memory when the executable file is loaded; however, it can be found with a program that finds printable strings in files. One use for this comment-record type is to embed a version number or similar information in an executable file.
lib
Places a library-search record in the object file. This comment type must be accompanied by a commentstring parameter containing the name (and possibly the path) of the library that you want the linker to search. The library name follows the default library-search records in the object file; the linker searches for this library just as if you had named it on the command line provided that the library is not specified with /nodefaultlib. You can place multiple library-search records in the same source file; each record appears in the object file in the same order in which it is encountered in the source file.
If the order of the default library and an added library is important, compiling with the /Zl switch will prevent the default library name from being placed in the object module. A second comment pragma then can be used to insert the name of the default library after the added library. The libraries listed with these pragmas will appear in the object module in the same order they are found in the source code.
linker
Places a linker option in the object file. You can use this comment-type to specify a linker option instead of passing it to the command line or specifying it in the development environment. For example, you can specify the /include option to force the inclusion of a symbol:
#pragma comment(linker, "/include:__mySymbol")
Only the following linker options are available to be passed to the linker identifier:
· /DEFAULTLIB
· /EXPORT
· /INCLUDE
· /MERGE
· /SECTION
user
Places a general comment in the object file. The commentstring parameter contains the text of the comment. This comment record is ignored by the linker.
The following pragma causes the linker to search for the EMAPI.LIB library while linking. The linker searches first in the current working directory and then in the path specified in the LIB environment variable.
#pragma comment( lib, "emapi" )
The following pragma causes the compiler to place the name and version number of the compiler in the object file:
#pragma comment( compiler )
For comments that take a commentstring parameter, you can use a macro in any place where you would use a string literal, provided that the macro expands to a string literal. You can also concatenate any combination of string literals and macros that expand to string literals. For example, the following statement is acceptable:
#pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )
如何添加系统中Lib到当前项目
(1)在Project | Settings | Link | Object/library modules:输入Lib名
称,不同的Lib之间用空格格开。
(2)#pragma comment(lib,"yourlib.lib")
关于_TrackMouseEvent
The _TrackMouseEvent function posts messages when the mouse pointer leaves a window or hovers over a window for a specified amount of time. This function calls
TrackMouseEvent if it exists, otherwise it emulates it.
关于ON_CONTROL_RANGE
ON_CONTROL_RANGE(wNotifyCode, id1, id2, memberFxn )
Use this macro to map a contiguous range of control IDs to a single message handler function for a specified Windows notification message, such as BN_CLICKED. The range of IDs starts with id1 and ends with id2. The handler is called for the specified notification coming from any of the mapped controls.There is no automatic support for message map ranges, so you must place the macro yourself.
Parameters
wNotifyCode
The notification code to which your handler is responding.
id1
Command ID at the beginning of a contiguous range of control IDs.
id2
Command ID at the end of a contiguous range of control IDs.
memberFxn
The name of the message-handler function to which the controls are mapped.
例如:
ON_CONTROL_RANGE(<wNotifyCode>, <id>,<idLast>, <memberFxn>)
afx_msg void memberFxn(UINT uID);
关于CMenu::GetSubMenu
CMenu* CMenu::GetSubMenu(int nPos) const;
Retrieves the CMenu object of a pop-up menu.
Parameters
nPos
Specifies the position of the pop-up menu contained in the menu. Position values start at 0 for the first menu item. The pop-up menu's identifier cannot be used in this function.
Return Value
A pointer to a CMenu object whose m_hMenu member contains a handle to the pop-up menu if a pop-up menu exists at the given position; otherwise NULL. If a CMenu object does not exist, then a temporary one is created. The CMenu pointer returned should not be stored.
关于GetSubMenu
HMENU GetSubMenu(
HMENU hMenu, // handle to menu
int nPos // menu item position
);
The GetSubMenu function retrieves a handle to the drop-down menu or submenu activated by the specified menu item. If the function succeeds, the return value is a handle to the drop-down menu or submenu activated by the menu item. If the menu item does not activate a drop-down menu or submenu, the return value is NULL.
Parameters
hMenu
[in] Handle to the menu.
nPos
[in] Specifies the zero-based relative position in the specified menu of an item that activates a drop-down menu or submenu.
关于TrackPopupMenu
BOOL TrackPopupMenu(
HMENU
hMenu, // handle to shortcut menu
UINT
uFlags, // options
int
x, // horizontal position
int
y, // vertical position
int
nReserved, // reserved, must be zero
HWND
hWnd, // handle to owner window
CONST RECT *
prcRect // ignored
);
The TrackPopupMenu function displays a shortcut menu at the specified location and tracks the selection of items on the menu. The shortcut menu can appear anywhere on the screen.To specify an area of the screen the menu should not overlap, use the
TrackPopupMenuEx function.
Parameters
hMenu
[in] Handle to the shortcut menu to be displayed. The handle can be obtained by calling
CreatePopupMenu to create a new shortcut menu, or by calling
GetSubMenu to retrieve a handle to a submenu associated with an existing menu item.
uFlags
[in] Use zero of more of these flags to specify function options.
Use one of the following flags to specify how the function positions the shortcut menu horizontally.
Value
|
Meaning
|
TPM_CENTERALIGN
|
If this flag is set, the function centers the shortcut menu horizontally relative to the coordinate specified by the x parameter.
|
TPM_LEFTALIGN
|
If this flag is set, the function positions the shortcut menu so that its left side is aligned with the coordinate specified by the x parameter.
|
TPM_RIGHTALIGN
|
Positions the shortcut menu so that its right side is aligned with the coordinate specified by the x parameter.
|
Use one of the following flags to specify how the function positions the shortcut menu vertically.
Value
|
Meaning
|
TPM_BOTTOMALIGN
|
If this flag is set, the function positions the shortcut menu so that its bottom side is aligned with the coordinate specified by the y parameter.
|
TPM_TOPALIGN
|
If this flag is set, the function positions the shortcut menu so that its top side is aligned with the coordinate specified by the y parameter.
|
TPM_VCENTERALIGN
|
If this flag is set, the function centers the shortcut menu vertically relative to the coordinate specified by the y parameter.
|
Use the following flags to determine the user selection without having to set up a parent window for the menu.
Value
|
Meaning
|
TPM_NONOTIFY
|
If this flag is set, the function does not send notification messages when the user clicks on a menu item.
|
TPM_RETURNCMD
|
If this flag is set, the function returns the menu item identifier of the user's selection in the return value.
|
Use one of the following flags to specify which mouse button the shortcut menu tracks.
Value
|
Meaning
|
TPM_LEFTBUTTON
|
If this flag is set, the user can select menu items with only the left mouse button.
|
TPM_RIGHTBUTTON
|
If this flag is set, the user can select menu items with both the left and right mouse buttons.
|
Windows 98/Me, Windows 2000/XP: Use any reasonable combination of the following flags to modify the animation of a menu. For example, by selecting a horizontal and a vertical flag you can achieve diagonal animation.
Value
|
Meaning
|
TPM_HORNEGANIMATION
|
Animates the menu from right to left.
|
TPM_HORPOSANIMATION
|
Animates the menu from left to right.
|
TPM_NOANIMATION
|
Displays menu without animation.
|
TPM_VERNEGANIMATION
|
Animates the menu from bottom to top.
|
TPM_VERPOSANIMATION
|
Animates the menu from top to bottom.
|
For any animation to occur, the SystemParametersInfo function must set SPI_SETMENUANIMATION. Also, all the TPM_*ANIMATION flags, except TPM_NOANIMATION, are ignored if menu fade animation is on, See the SPI_GETMENUFADE flag in
SystemParametersInfo.
Windows 98/Me, Windows 2000/XP: Use the TPM_RECURSE flag to display a menu when another menu is already displayed. This is intended to support context menus within a menu.
Windows XP: To have text layout from right-to-left, use TPM_LAYOUTRTL. By default, the text layout is left-to-right.
x
[in] Specifies the horizontal location of the shortcut menu, in screen coordinates.
y
[in] Specifies the vertical location of the shortcut menu, in screen coordinates.
nReserved
Reserved; must be zero.
hWnd
[in] Handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a
WM_COMMAND message from the menu until the function returns.
If you specify TPM_NONOTIFY in the uFlags parameter, the function does not send messages to the window identified by hWnd. However, you must still pass a window handle in hWnd. It can be any window handle from your application.
prcRect
Ignored.
Return Values
If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.If you do not specify TPM_RETURNCMD in the uFlags parameter, the return value is nonzero if the function succeeds and zero if it fails. To get extended error information, call GetLastError.
Remarks
To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible). However, when the current window is the foreground window, the second time this menu is displayed, it displays and then immediately disappears. To correct this, you must force a task switch to the application that called TrackPopupMenu at some time in the near future. This is done by posting a benign message to the window or thread, as shown in the following code sample:
SetForegroundWindow(hDlg);
// Display the menu
TrackPopupMenu( hSubMenu,
TPM_RIGHTBUTTON,
pt.x,
pt.y,
0,
hDlg,
NULL);
PostMessage(hDlg, WM_NULL, 0, 0);
关于CMenu::TrackPopupMenu
BOOL CMenu::TrackPopupMenu(
UINT nFlags,
int x,
int y,
CWnd* pWnd,
LPCRECT lpRect = 0
);
Displays a floating pop-up menu at the specified location and tracks the selection of items on the pop-up menu.
Parameters
nFlags
Specifies a screen-position flag and a mouse-button flag. The screen-position flag can be one of the following:
· TPM_CENTERALIGN Centers the pop-up menu horizontally relative to the coordinate specified by x.
· TPM_LEFTALIGN Positions the pop-up menu so that its left side is aligned with the coordinate specified by x.
· TPM_RIGHTALIGN Positions the pop-up menu so that its right side is aligned with the coordinate specified by x.
The mouse-button flag can be either of the following:
· TPM_LEFTBUTTON Causes the pop-up menu to track the left mouse button.
· TPM_RIGHTBUTTON Causes the pop-up menu to track the right mouse button.
x
Specifies the horizontal position in screen coordinates of the pop-up menu. Depending on the value of the nFlags parameter, the menu can be left-aligned, right-aligned, or centered relative to this position.
y
Specifies the vertical position in screen coordinates of the top of the menu on the screen.
pWnd
Identifies the window that owns the pop-up menu. This window receives all WM_COMMAND messages from the menu. In Windows versions 3.1 and later, the window does not receive WM_COMMAND messages until TrackPopupMenu returns. In Windows 3.0, the window receives WM_COMMAND messages before TrackPopupMenu returns.
lpRect
Points to a RECT structure or CRect object that contains the screen coordinates of a rectangle within which the user can click without dismissing the pop-up menu. If this parameter is 0, the pop-up menu is dismissed if the user clicks outside the pop-up menu. This must be 0 for Windows 3.0.
For Windows 3.1 and later, you can use the following constants:
- TPM_CENTERALIGN
- TPM_LEFTALIGN
- TPM_RIGHTALIGN
- TPM_RIGHTBUTTON
关于MAKEWPARAM
WPARAM MAKEWPARAM(
WORD wLow,
WORD wHigh
);
The MAKEWPARAM macro creates a value for use as a wParam parameter in a message. The macro concatenates the specified values.
Parameters
wLow
Specifies the low-order word of the new value.
wHigh
Specifies the high-order word of the new value.
Return Values
The return value is a WPARAM value.
关于_tcslen
size_t strlen(
const char *string
);
size_t wcslen(
const wchar_t *string
);
size_t _mbslen(
const unsigned char *string
);
size_t _mbstrlen(
const char *string
);
Parameters
string
Null-terminated string.
Return Value
Each of these functions returns the number of characters in string, excluding the terminal NULL. No return value is reserved to indicate an error.
关于SHELLEXECUTEINFO
typedef struct _SHELLEXECUTEINFO{
DWORD cbSize;
ULONG fMask;
HWND hwnd;
LPCTSTR lpVerb;
LPCTSTR lpFile;
LPCTSTR lpParameters;
LPCTSTR lpDirectory;
int nShow;
HINSTANCE hInstApp;
// Optional members
LPVOID lpIDList;
LPCTSTR lpClass;
HKEY hkeyClass;
DWORD dwHotKey;
union {
HANDLE hIcon;
HANDLE hMonitor;
} DUMMYUNIONNAME;
HANDLE hProcess;
} SHELLEXECUTEINFO, *LPSHELLEXECUTEINFO;
Contains information used by
ShellExecuteEx.
Members
cbSize
Size of the structure, in bytes.
fMask
Array of flags that indicate the content and validity of the other structure members. This can be a combination of the following values.
SEE_MASK_CLASSKEY
|
Use the class key given by the hkeyClass member.
|
SEE_MASK_CLASSNAME
|
Use the class name given by the lpClass member.
|
SEE_MASK_CONNECTNETDRV
|
Validate the share and connect to a drive letter. The lpFile member is a Universal Naming Convention (UNC) path of a file on a network.
|
SEE_MASK_DOENVSUBST
|
Expand any environment variables specified in the string given by the lpDirectory or lpFile member.
|
SEE_MASK_FLAG_DDEWAIT
|
Wait for the DDE conversation to terminate before returning (if the
ShellExecuteEx function causes a DDE conversation to start). For circumstances in which this flag is necessary, see the Remarks section.
|
SEE_MASK_FLAG_LOG_USAGE
|
Version 6.0. Keep track of the number of times this application has been launched. Applications that accrue sufficiently high counts appear in the Start Menu's list of most frequently used programs.
|
SEE_MASK_FLAG_NO_UI
|
Do not display an error message box if an error occurs.
|
SEE_MASK_HMONITOR
|
Use this flag when specifying a monitor on multi-monitor systems. The monitor is specified in the hMonitor member. This flag cannot be combined with SEE_MASK_ICON.
|
SEE_MASK_HOTKEY
|
Use the hot key given by the dwHotKey member.
|
SEE_MASK_ICON
|
Use the icon given by the hIcon member. This flag cannot be combined with SEE_MASK_HMONITOR.
|
SEE_MASK_IDLIST
|
Use the item identifier list given by the lpIDList member. The lpIDList member must point to an
ITEMIDLIST structure.
|
SEE_MASK_INVOKEIDLIST
|
Use the
IContextMenu interface of the selected item's
shortcut menu handler. Use either lpFile to identify the item by its file system path or lpIDList to identify the item by its PIDL. This flag allows applications to use
ShellExecuteEx to invoke verbs from shortcut menu extensions instead of the static verbs listed in the registry.
Note SEE_MASK_INVOKEIDLIST overrides SEE_MASK_IDLIST.
|
SEE_MASK_NOCLOSEPROCESS
|
Use to indicate that the hProcess member receives the process handle. This handle is typically used to allow an application to find out when a process created with
ShellExecuteEx terminates. In some cases, such as when execution is satisfied through a DDE conversation, no handle will be returned. The calling application is responsible for closing the handle when it is no longer needed.
|
SEE_MASK_NO_CONSOLE
|
Use to create a console for the new process instead of having it inherit the parent's console. It is equivalent to using a CREATE_NEW_CONSOLE flag with CreateProcess.
|
SEE_MASK_UNICODE
|
Use this flag to indicate a Unicode application.
|
hwnd
Window handle to any message boxes that the system might produce while executing this function.
lpVerb
String, referred to 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 specific information about verbs, see
Object Verbs. For further discussion of shortcut menus, see
Extending Shortcut Menus. The following verbs are commonly used.
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.
|
properties
|
Displays the file or folder's properties.
|
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
Address of a null-terminated string that specifies the name of the file or object on which
ShellExecuteEx will perform the action specified by the lpVerb parameter. The system registry verbs that are supported by the
ShellExecuteEx function include "open" for executable files and document files and "print" for document files for which a print handler has been registered. Other applications might have added Shell verbs through the system registry, such as "play" for AVI and WAV files. To specify a Shell namespace object, pass the fully qualified parse name and set the SEE_MASK_INVOKEIDLIST flag in the fMask parameter.
Note If the SEE_MASK_INVOKEIDLIST flag is set, you can use either lpFile or lpIDList to identify the item by its file system path or its PIDL respectively.
Note If the path is not included with the name, the current directory is assumed.
lpParameters
Address of a null-terminated string that contains the application parameters. The parameters must be separated by spaces. To include double quotation marks, enclose each mark in a pair of quotation marks, as in the following example.
sei.lpParameters = "An example: /"/"/"quoted text/"/"/"";
In this case, the application receives three parameters: An, example:, and "quoted text".
If the lpFile member specifies a document file, this member should be NULL.
lpDirectory
Address of a null-terminated string that specifies the name of the working directory. If this member is not specified, the current directory is used as the working directory.
nShow
Flags that specify how an application is to be shown when it is opened. It can be one of the SW_ values listed for the
ShellExecute function. 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.
hInstApp
If the function succeeds, it sets this member to a value greater than 32. If the function fails, it is set to an SE_ERR_XXX error value that indicates the cause of the failure. Although hInstApp is declared as an HINSTANCE for compatibility with 16-bit Windows applications, it is not a true HINSTANCE. It can be cast only to an integer and compared to either 32 or the following SE_ERR_XXX error codes.
SE_ERR_FNF
|
File not found.
|
SE_ERR_PNF
|
Path not found.
|
SE_ERR_ACCESSDENIED
|
Access denied.
|
SE_ERR_OOM
|
Out of memory.
|
SE_ERR_DLLNOTFOUND
|
Dynamic-link library not found.
|
SE_ERR_SHARE
|
Cannot share an open file.
|
SE_ERR_ASSOCINCOMPLETE
|
File association information not complete.
|
SE_ERR_DDETIMEOUT
|
DDE operation timed out.
|
SE_ERR_DDEFAIL
|
DDE operation failed.
|
SE_ERR_DDEBUSY
|
DDE operation is busy.
|
SE_ERR_NOASSOC
|
File association not available.
|
lpIDList
Address of an
ITEMIDLIST structure to contain an item identifier list uniquely identifying the file to execute. This member is ignored if the fMask member does not include SEE_MASK_IDLIST or SEE_MASK_INVOKEIDLIST.
lpClass
Address of a null-terminated string that specifies the name of a file class or a globally unique identifier (GUID). This member is ignored if fMask does not include SEE_MASK_CLASSNAME.
hkeyClass
Handle to the registry key for the file class. This member is ignored if fMask does not include SEE_MASK_CLASSKEY.
dwHotKey
Hot key to associate with the application. The low-order word is the virtual key code, and the high-order word is a modifier flag (HOTKEYF_). For a list of modifier flags, see the description of the WM_SETHOTKEY message. This member is ignored if fMask does not include SEE_MASK_HOTKEY.
hIcon
Handle to the icon for the file class. This member is ignored if fMask does not include SEE_MASK_ICON.
hMonitor
Handle to the monitor upon which the document is to be displayed. This member is ignored if fMask does not include SEE_MASK_HMONITOR.
hProcess
Handle to the newly started application. This member is set on return and is always NULL unless fMask is set to SEE_MASK_NOCLOSEPROCESS. Even if fMask is set to SEE_MASK_NOCLOSEPROCESS, hProcess will be NULL if no process was launched. For example, if a document to be launched is a URL and an instance of Microsoft® Internet Explorer is already running, it will display the document. No new process is launched, and hProcess will be NULL.
Note ShellExecuteEx does not always return an hProcess, even if a process is launched as the result of the call. For example, an hProcess does not return when you use SEE_MASK_INVOKEIDLIST to invoke
IContextMenu.
Remarks
The SEE_MASK_FLAG_DDEWAIT flag must be specified if the thread calling
ShellExecuteEx does not have a message loop or if the thread or process will terminate soon after ShellExecuteEx returns. Under such conditions, the calling thread will not be available to complete the DDE conversation, so it is important that ShellExecuteEx complete the conversation before returning control to the caller. Failure to complete the conversation can result in an unsuccessful launch of the document.
If the calling thread has a message loop and will exist for some time after the call to ShellExecuteEx returns, the SEE_MASK_FLAG_DDEWAIT flag is optional. If the flag is omitted, the calling thread's message pump will be used to complete the DDE conversation. The calling application regains control sooner, since the DDE conversation can be completed in the background.
When populating the most frequently used program list using the SEE_MASK_FLAG_LOG_USAGE flag in fMask, counts are made differently for the classic and Windows XP-style Start menus. The classic style menu only counts hits to the shortcuts in the Program menu. The Windows XP-style menu counts both hits to the shortcuts in the Program menu and hits to those shortcuts' targets outside of the Program menu. Therefore, setting lpFile to myfile.exe would affect the count for the Windows XP-style menu regardless of whether that file was launched directly or through a shortcut. The classic style—which would require lpFile to contain a .lnk file name—would not be affected.
例如:
SHELLEXECUTEINFO csSEI;
memset(&csSEI, 0, sizeof(csSEI));
csSEI.cbSize = sizeof(SHELLEXECUTEINFO);
csSEI.fMask = SEE_MASK_FLAG_NO_UI;
csSEI.lpVerb = _T("open");
csSEI.lpFile = m_szURL;
csSEI.nShow = SW_SHOWMAXIMIZED;
::ShellExecuteEx(&csSEI);
关于CMenu::LoadMenu
BOOL CMenu::LoadMenu(LPCTSTR lpszResourceName);
BOOL CMenu::LoadMenu(UINT nIDResource);
Loads a menu resource from the application's executable file and attaches it to the CMenu object.
Parameters
lpszResourceName
Points to a null-terminated string that contains the name of the menu resource to load.
nIDResource
Specifies the menu ID of the menu resource to load.
Return Value
Nonzero if the menu resource was loaded successfully; otherwise 0.
Remarks
Before exiting, an application must free system resources associated with a menu if the menu is not assigned to a window. An application frees a menu by calling the
DestroyMenu member function.
关于CToolBar::LoadToolBar
BOOL CToolBar::LoadToolBar(
LPCTSTR lpszResourceName
);
BOOL CToolBar::LoadToolBar(
UINT nIDResource
);
Call this member function to load the toolbar specified by lpszResourceName or nIDResource.
Parameters
lpszResourceName
Pointer to the resource name of the toolbar to be loaded.
nIDResource
Resource ID of the toolbar to be loaded.
Return Value
Nonzero if successful; otherwise 0.
关于ON_WM_MENUCHAR
afx_msg LRESULT CWnd::
OnMenuChar(UINT
nChar, UINT
nFlags, CMenu*
pMenu);
The framework calls this member function when the user presses a menu mnemonic character that doesn't match any of the predefined mnemonics in the current menu.
Parameters
nChar
Depending on the build settings, specifies the ANSI or Unicode character that the user pressed.
nFlags
Contains the MF_POPUP flag if the menu is a pop-up menu. It contains the MF_SYSMENU flag if the menu is a Control menu.
pMenu
Contains a pointer to the selected CMenu. The pointer may be temporary and should not be stored.
Return Value
The high-order word of the return value should contain one of the following command codes:
Value
|
Description
|
0
|
Tells Windows to discard the character that the user pressed and creates a short beep on the system speaker.
|
1
|
Tells Windows to close the current menu.
|
2
|
Informs Windows that the low-order word of the return value contains the item number for a specific item. This item is selected by Windows.
|
The low-order word is ignored if the high-order word contains 0 or 1. Applications should process this message when accelerator (shortcut) keys are used to select bitmaps placed in a menu.
Remarks
It is sent to the CWnd that owns the menu. OnMenuChar is also called when the user presses ALT and any other key, even if the key does not correspond to a mnemonic character. In this case, pMenu points to the menu owned by the CWnd, and nFlags is 0.
关于ON_WM_MEASUREITEM
afx_msg void CWnd::
OnMeasureItem(int
nIDCtl,
LPMEASUREITEMSTRUCT
lpMeasureItemStruct);
The framework calls this member function by the framework for the owner of an owner-draw button, combo box, list box, or menu item when the control is created. Override this member function and fill in the MEASUREITEMSTRUCT data structure pointed to by lpMeasureItemStruct and return;
this informs Windows of the dimensions of the control and allows Windows to process user interaction with the control correctly.
If a list box or combo box is created with the
LBS_OWNERDRAWVARIABLE or
CBS_OWNERDRAWVARIABLE style, the framework calls this function for the owner for each item in the control; otherwise this function is called once. Windows initiates the call to OnMeasureItem for the owner of combo boxes and list boxes created with the OWNERDRAWFIXED style before sending the WM_INITDIALOG message. As a result, when the owner receives this call, Windows has not yet determined the height and width of the font used in the control; function calls and calculations that require these values should occur in the main function of the application or library.If the item being measured is a CMenu, CListBox or CComboBox object, then the MeasureItem virtual function of the appropriate class is called. Override the MeasureItem member function of the appropriate control's class to calculate and set the size of each item.
OnMeasureItem will be called only if the control's class is created at run time, or it is created with the LBS_OWNERDRAWVARIABLE or CBS_OWNERDRAWVARIABLE style. If the control is created by the dialog editor, OnMeasureItem will not be called. This is because the WM_MEASUREITEM message is sent early in the creation process of the control. If you subclass by using DDX_Control, SubclassDlgItem, or SubclassWindow, the subclassing usually occurs after the creation process. Therefore, there is no way to handle the WM_MEASUREITEM message in the control's OnChildNotify function, which is the mechanism MFC uses to implement ON_WM_MEASUREITEM_REFLECT.
Parameters
nIDCtl
The ID of the control.
lpMeasureItemStruct
Points to a
MEASUREITEMSTRUCT data structure that contains the dimension dimensions of the owner-draw control.
关于MEASUREITEMSTRUCT
typedef struct tagMEASUREITEMSTRUCT {
UINT CtlType;
UINT CtlID;
UINT itemID;
UINT itemWidth;
UINT itemHeight;
DWORD itemData
} MEASUREITEMSTRUCT;
The MEASUREITEMSTRUCT structure informs Windows of the dimensions of an owner-drawn control or menu item.
Parameters
CtlType
Contains the control type. The values for control types are as follows:
· ODT_COMBOBOX Owner-draw combo box
· ODT_LISTBOX Owner-draw list box
· ODT_MENU Owner-draw menu
CtlID
Contains the control ID for a combo box, list box, or button. This member is not used for a menu.
itemID
Contains the menu-item ID for a menu or the list-box-item ID for a variable-height combo box or list box. This member is not used for a fixed-height combo box or list box, or for a button.
itemWidth
Specifies the width of a menu item. The owner of the owner-draw menu item must fill this member before it returns from the message.
itemHeight
Specifies the height of an individual item in a list box or a menu. Before it returns from the message, the owner of the owner-draw combo box, list box, or menu item must fill out this member. The maximum height of a list box item is 255.
itemData
For a combo box or list box, this member contains the value that was passed to the list box by one of the following:
·
CComboBox::AddString
·
CComboBox::InsertString
·
CListBox::AddString
·
CListBox::InsertString
For a menu, this member contains the value that was passed to the menu by one of the following:
·
CMenu::AppendMenu
·
CMenu::InsertMenu
·
CMenu::ModifyMenu
This allows Windows to process user interaction with the control correctly. Failure to fill out the proper members in the MEASUREITEMSTRUCT structure will cause improper operation of the control.
关于IsMenu
BOOL IsMenu(HMENU hMenu // handle to test);
The IsMenu function determines whether a handle is a menu handle.
关于ON_WM_CTLCOLOR_REFLECT
afx_msg HBRUSH CtlColor ( CDC* pDC, UINT nCtlColor );
Message Reflection for Windows Controls
Note The following technical note has not been updated since it was first included in the online documentation. As a result, some procedures and topics might be out of date or incorrect. For the latest information, it is recommended that you search for the topic of interest in the online documentation index.
This technical note describes message reflection, a new feature in MFC 4.0. It also contains directions for creating a simple reusable control that uses message reflection.
This technical note does not discuss message reflection as it applies to ActiveX controls (formerly called OLE controls). Please see the article ActiveX Controls: Subclassing a Windows Control.
What Is Message Reflection?
Windows controls frequently send notification messages to their parent windows. For instance, many controls send a control color notification message (WM_CTLCOLOR or one of its variants) to their parent to allow the parent to supply a brush for painting the background of the control.
In Windows and in MFC before version 4.0, the parent window, often a dialog box, is responsible for handling these messages. This means that the code for handling the message needs to be in the parent window's class and that it has to be duplicated in every class that needs to handle that message. In the case above, every dialog box that wanted controls with custom backgrounds would have to handle the control color notification message.
It would be much easier to reuse code if a control class could be written that would handle its own background color.In MFC 4.0, the old mechanism still works — parent windows can handle notification messages. In addition, however, MFC 4.0 facilitates reuse by providing a feature called "message reflection" that allows these notification messages to be handled in either the child control window or the parent window, or in both. In the control background color example, you can now write a control class that sets its own background color by handling the reflected WM_CTLCOLOR message — all without relying on the parent. (Note that since message reflection is implemented by MFC, not by Windows, the parent window class must be derived from CWnd for message reflection to work.)
Older versions of MFC did something similar to message reflection by providing virtual functions for a few messages, such as messages for owner-drawn list boxes (WM_DRAWITEM, and so on). The new message reflection mechanism is generalized and consistent.Message reflection is backward compatible with code written for versions of MFC before 4.0. If you have supplied a handler for a specific message, or for a range of messages, in your parent window's class, it will override reflected message handlers for the same message provided you don't call the base class handler function in your own handler. For example, if you handle WM_CTLCOLOR in your dialog box class, your handling will override any reflected message handlers.If, in your parent window class, you supply a handler for a specific WM_NOTIFY message or a range of WM_NOTIFY messages, your handler will be called only if the child control sending those messages does not have a reflected message handler through ON_NOTIFY_REFLECT(). If you use ON_NOTIFY_REFLECT_EX() in your message map, your message handler may or may not allow the parent window to handle the message. If the handler returns FALSE, the message will be handled by the parent as well, while a call that returns TRUE does not allow the parent to handle it.
Note that the reflected message is handled before the notification message.When a WM_NOTIFY message is sent, the control is offered the first chance to handle it. If any other reflected message is sent, the parent window has the first chance to handle it and the control will receive the reflected message. To do so, it will need a handler function and an appropriate entry in the control's class message map.The message-map macro for reflected messages is slightly different than for regular notifications: it has _REFLECT appended to its usual name. For instance, to handle a WM_NOTIFY message in the parent, you use the macro ON_NOTIFY in the parent's message map. To handle the reflected message in the child control, use the ON_NOTIFY_REFLECT macro in the child control's message map. In some cases, the parameters are different, as well. Note that ClassWizard can usually add the message-map entries for you and provide skeleton function implementations with correct parameters.
See
TN061: ON_NOTIFY and WM_NOTIFY Messages for information on the new WM_NOTIFY message.Message-Map Entries and Handler Function Prototypes for Reflected Messages.To handle a reflected control notification message, use the message-map macros and function prototypes listed in the table below.ClassWizard can usually add these message-map entries for you and provide skeleton function implementations. See Defining a Message Handler for a Reflected Message for information about how to define handlers for reflected messages.To convert from the message name to the reflected macro name, prepend ON_ and append _REFLECT. For example, WM_CTLCOLOR becomes ON_WM_CTLCOLOR_REFLECT. (To see which messages can be reflected, do the opposite conversion on the macro entries in the table below.)
The three exceptions to the rule above are as follows:
- The macro for WM_COMMAND notifications is ON_CONTROL_REFLECT.
- The macro for WM_NOTIFY reflections is ON_NOTIFY_REFLECT.
- The macro for ON_UPDATE_COMMAND_UI reflections is ON_UPDATE_COMMAND_UI_REFLECT.
In each of the above special cases, you must specify the name of the handler member function. In the other cases, you must use the standard name for your handler function.
The meanings of the parameters and return values of the functions are documented under either the function name or the function name with On prepended. For instance, CtlColor is documented in OnCtlColor. Several reflected message handlers need fewer parameters than the similar handlers in a parent window. Just match the names in the table below with the names of the formal parameters in the documentation.
Map entry
|
Function prototype
|
ON_CONTROL_REFLECT( wNotifyCode, memberFxn )
|
afx_msg void memberFxn ( );
|
ON_NOTIFY_REFLECT( wNotifyCode, memberFxn )
|
afx_msg void memberFxn ( NMHDR * pNotifyStruct, LRESULT* result );
|
ON_UPDATE_COMMAND_UI_REFLECT( memberFxn )
|
afx_msg void memberFxn ( CCmdUI* pCmdUI );
|
ON_WM_CTLCOLOR_REFLECT( )
|
afx_msg HBRUSH CtlColor ( CDC* pDC, UINT nCtlColor );
|
ON_WM_DRAWITEM_REFLECT( )
|
afx_msg void DrawItem ( LPDRAWITEMSTRUCT lpDrawItemStruct );
|
ON_WM_MEASUREITEM_REFLECT( )
|
afx_msg void MeasureItem ( LPMEASUREITEMSTRUCT lpMeasureItemStruct );
|
ON_WM_DELETEITEM_REFLECT( )
|
afx_msg void DeleteItem ( LPDELETEITEMSTRUCT lpDeleteItemStruct );
|
ON_WM_COMPAREITEM_REFLECT( )
|
afx_msg int CompareItem ( LPCOMPAREITEMSTRUCT lpCompareItemStruct );
|
ON_WM_CHARTOITEM_REFLECT( )
|
afx_msg int CharToItem ( UINT nKey, UINT nIndex );
|
ON_WM_VKEYTOITEM_REFLECT( )
|
afx_msg int VKeyToItem ( UINT nKey, UINT nIndex );
|
ON_WM_HSCROLL_REFLECT( )
|
afx_msg void HScroll ( UINT nSBCode, UINT nPos );
|
ON_WM_VSCROLL_REFLECT( )
|
afx_msg void VScroll ( UINT nSBCode, UINT nPos );
|
ON_WM_PARENTNOTIFY_REFLECT( )
|
afx_msg void ParentNotify ( UINT message, LPARAM lParam );
|
The ON_NOTIFY_REFLECT and ON_CONTROL_REFLECT macros have variations that allow more than one object (such as the control and its parent) to handle a given message.
Map entry
|
Function prototype
|
ON_NOTIFY_REFLECT_EX( wNotifyCode, memberFxn )
|
afx_msg BOOL memberFxn ( NMHDR * pNotifyStruct, LRESULT* result );
|
ON_CONTROL_REFLECT_EX( wNotifyCode, memberFxn )
|
afx_msg BOOL memberFxn ( );
|
Handling Reflected Messages: An Example of a Reusable control
This simple example creates a reusable control called CYellowEdit. The control works the same as a regular edit control except that it displays black text on a yellow background. It would be easy to add member functions that would allow the CYellowEdit control to display different colors.
To try the example that creates a reusable control
- Create a new dialog box in an existing application. For more information, see the dialog editor topic.
You must have an application in which to develop the reusable control. If you don't have an existing application to use, create a dialog-based application using AppWizard.
- With your project loaded into Visual C++, use ClassWizard to create a new class called CYellowEdit based on CEdit. Leave the Add to Component Gallery check box checked.
- Add three member variables to your CYellowEdit class. The first two will be COLORREF variables to hold the text color and the background color. The third will be a CBrush object that will hold the brush for painting the background. The CBrush object allows you to create the brush once, merely referencing it after that, and to destroy the brush automatically when the CYellowEdit control is destroyed.
- Initialize the member variables by writing the constructor as follows:
5. CYellowEdit::CYellowEdit()
6. {
7. m_clrText = RGB( 0, 0, 0 );
8. m_clrBkgnd = RGB( 255, 255, 0 );
9. m_brBkgnd.CreateSolidBrush( m_clrBkgnd );
}
- Using ClassWizard, add a handler for the reflected WM_CTLCOLOR message to your CYellowEdit class. Note that the equal sign in front of the message name in the list of messages you can handle indicates that the message is reflected. This is described in Defining a Message Handler for a Reflected Message.
ClassWizard adds the following message-map macro and skeleton function for you:
ON_WM_CTLCOLOR_REFLECT()
// Note: other code will be in between....
HBRUSH CYellowEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
// TODO: Change any attributes of the DC here
// TODO: Return a non-NULL brush if the
// parent's handler should not be called
return NULL;
}
- Replace the body of the function with the following code. The code specifies the text color, the text background color, and the background color for rest of the control.
12. pDC->SetTextColor( m_clrText ); // text
13. pDC->SetBkColor( m_clrBkgnd ); // text bkgnd
return m_brBkgnd; // ctl bkgnd
- Create an edit control in your dialog box, then attach it to a member variable by double-clicking the edit control while holding a control key down. In the Add Member Variable dialog box, finish the variable name and choose "Control" for the category, then "CYellowEdit" for the variable type. Don't forget to set the tab order in the dialog box. Also, be sure to include the header file for the CYellowEdit control in your dialog box's header file.
- Build and run your application. The edit control will have a yellow background.
- You can now use Component Gallery to add your CYellowEdit control class to other projects.
例如:
ON_CONTROL_REFLECT_EX(BN_CLICKED, OnClicked)
afx_msg BOOL OnClicked();
About Attribute Change
DWORD CButtonST::SetDefaultColors(BOOL bRepaint = TRUE)
{
//change flag
if(bRepaint)
{
if(//window is created)
{
//update surface
}
}
}
关于#pragma pack
#pragma pack(1)
typedef struct _STRUCT_ICONS
{
HICON hIcon; // Handle to icon
DWORD dwWidth; // Width of icon
DWORD dwHeight; // Height of icon
} STRUCT_ICONS;
#pragma pack()
#pragma pack( [ show ] | [ push | pop ] [, identifier ] , n )
Specifies packing alignment for structure, union, and class members. pack gives control at the data-declaration level. This differs from compiler option /Zp, which only provides module-level control. pack takes effect at the first struct, union, or class declaration after the pragma is seen; pack has no effect on definitions.
Calling pack with no arguments sets n to its default value. This is equivalent to compiler option /Zp8.
show (optional)
Displays the current byte value for packing alignment. The value is displayed by means of a warning message.
push (optional)
Puts a specified packing alignment value, n, on the internal compiler stack, and sets the current packing alignment value to n. If n is not specified, the current packing alignment value is pushed.
pop (optional)
Removes the record from the top of the internal compiler stack. If n is not specified with pop, then the packing value associated with the resulting record on the top of the stack is the new packing alignment value. If n is specified, for example, #pragma pack(pop, 16), n becomes the new packing alignment value. If you pop with identifier, for example, #pragma pack(pop, r1), then all records on the stack are popped until the record with identifier is found, and that record is popped and the packing value associated with the resulting record on the top of is the stack the new packing alignment value. If you pop with an identifier that is not found in any record on the stack, then the pop is ignored.
identifier (optional)
When used with push, assigns a name to the record on the internal compiler stack. When used with pop, pops records off the internal stack until identifier is removed; if identifier is not found on the internal stack, nothing is popped.
n (optional)
Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.
Consider the following example,
struct s
{
int i; // aligned on byte boundary 0, size is 4
short j; // aligned on byte boundary 4, size is 2
double k; // aligned on byte boundary 8, size is 8
}
n can be used with push or pop for setting a particular stack value, or alone for setting the current value used by the compiler.
Example
// pragma_directives_pack.cpp
// C4810 expected
#pragma pack() // n defaults to 8; equivalent to /Zp8
#pragma pack(show) // C4810
#pragma pack(4) // n=4
#pragma pack(show) // C4810
#pragma pack(push, r1, 16) // n=16, pushed to stack
#pragma pack(show) // C4810
#pragma pack(pop, r1, 2) // n=2 , stack popped
#pragma pack(show) // C4810
void main()
{
}
关于字符类型
typedef char CHAR;
typedef wchar_t WCHAR;
typedef CHAR * PCHAR, * LPCH, * PCH, * NPSTR, * LPSTR, * PSTR ;
typedef CONST CHAR * LPCCH, * PCCH, * LPCSTR, * PCSTR ;
typedef WCHAR * PWCHAR, * LPWCH, * PWCH, * NWPSTR, * LPWSTR, * PWSTR ;
typedef CONST WCHAR * LPCWCH, * PCWCH, * LPCWSTR, * PCWSTR ;
#ifdef UNICODE
typedef WCHAR TCHAR, * PTCHAR ;
typedef LPWSTR LPTCH, PTCH, PTSTR, LPTSTR ;
typedef LPCWSTR LPCTSTR ;
#else
typedef char TCHAR, * PTCHAR ;
typedef LPSTR LPTCH, PTCH, PTSTR, LPTSTR ;
typedef LPCSTR LPCTSTR ;
#endif
关于DrawItem和OnPaint
(1)自绘控件笔记
不选择在 PreSubclassWindow中作“初始化”工作是因为用户可能在使用中改变属性,必须在一个经常进入的地方检查是否要重新“初始化”。把这项工作放到和绘制有关的消息响应函数里则父窗口一个 RedrawWindow() 就可以引起重新“初始化”。
一般步骤:
1.派生控件子类
2.添加 PreTranslateMessage
3.进行常规操作记下消息类型
4.在子类里处理消息
MFC的 CStatic 控件无法有效 SS_OWNERDRAW 属性,从而无法响应 OnDrawItem。
按MSDN SDK中的static控件可以使能 SS_OWNERDRAW 并发送 WM_DRAWITEM 消息。经测试 CStatic 控件可利用的只有 WM_PAINT 消息。
设有 BS_OWNERDRAW 属性的 CButton 控件先响应 OnEraseBkgnd 再响应 DrawItem。因此调整窗口尺寸等“初始化”工作可以放再 OnEraseBkgnd 里完成。
CProgressCtrl 控件通过 SetPos 、StepIt 绘制,更改进度值不会触发 OnEraseBkgnd 消息但至少会有一次 OnEraseBkgnd,可以利用来作初始化。OnPaint 不完成绘制工作,截获该消息默认的绘制将停止。
CSliderCtrl 绘制行为类似 CProgressCtrl,截获 OnPaint 默认不绘制,但状态改变时会触发 OnPaint 消息。OnEraseBkgnd 可以用来作初始化。OnTimer 在点击轨道时触发,每500ms一次,用来模拟 PageDown/Up,在鼠标放开时timer被kill掉。如果鼠标恰好在当前位置按下则不触发 OnTimer,拖曳滑块不触发 OnTimer。
CMenu 不是 CWnd 的子类但有纯虚的 MeasureItem 和 DrawItem,绘制工作能且只能依赖它们。菜单风格包括 整体背景风格、菜单项风格、文字风格,尺寸参数包括菜单项尺寸、菜单项图标尺寸、文字尺寸。以上种种还因菜单项状态不同改变。
MEASUREITEMSTRUCT 和 DRAWITEMSTRUCT 中的 itemData 在 MF_OWNERDRAW 时都是取自 AppendMenu 、InsertMenu 、ModifyMenu 的最后一个参数,所以不得不有一个结构专门管理菜单项类型、文字、图像等信息。使用 SetMenuInfo、SetMenuItemInfo、GetMenuInfo、GetMenuItemInfo 可以方便的管理菜单信息,但要实现自绘必须有 MF_OWNERDRAW 属性,因此用一个自定义结构管理菜单项的若干重要信息仍是有意义的。
自绘按钮在 MeasureItem 或 DrawItem 里设断点会引起windows菜单显示异常!折腾了很久以为是我的问题呢!
GDI+ new 出的 Bitmap 对象竟然会使用相同的地址!?而且就算地址不同也有冲突?难道不能存储大量的 Bitmap 对象吗?? GdiAlloc 和 GdipCreateBitmapFrom*** 究竟怎么管理内存,new 出的对象不 delete 也不会有任何问题, 文档太少!
CreateMenu 和 CreatePopupMenu 的绘图方式有差异,一定要确定到底是要哪种菜单。 支持子菜单需要动态创建、删除 CSkinMenu 实例,如果用Load方式载入按钮爬一遍即可;如果Insert方式加入的子菜单则由用户决定是否拓展,换言之应不作特殊处理。另外Detach、DestroyMenu、RemoveMenu 都应处理被扩展的子菜单。
CScrollBar 的消息反射OnVscroll、OnHscroll里设置pos是没有用的,大概反射消息只是用来通知不是用来操作。关于Scroll Bar的详细状态可以用GetScrollBarInfo获得。
CListBox的OwnerDraw属性只能在创建的时候指定,不能在PreSubclassWindow里用ModifyStyle改变。而且如果需要触发MeasureItem必须把OwnerDraw设成Variable,Fix时MeasureItem不被调用只能使用SetItemHeight设置高度。
CComboBox的edit部分由OnPaint控制,输入文字是发出OnEditChange,通过列表改变时发出OnSelchange。list部分由DrawItem控制,创立时必须有OwnerDraw风格。但CListBox似乎不能触发MeasureItem。
(2)DrawItem虚函数重载它可以自绘各种控件的外观. OnPaint发送一个全窗口重绘的消息,引起当前窗口全部重绘
(3) OnPaint是全窗口绘制.DrawItem是按项绘制,比如ListCtrl等,可以从函数参数直接取得相关信息.
如何为一radio单选按钮引入一对应的CButton型变量?
将radio button属性中的group选中,就可以加你要的变量了。
关于pDC->SetBkColor(RGB(255,255,255));
I don’t know why call the function“pDC->SetBkColor(RGB(255,255,255))”
void CButtonST::DrawItem(LPDRAWITEMSTRUCT lpDIS)
{
//………
if (m_csBitmaps[0].hBitmap)
{
pDC->SetBkColor(RGB(255,255,255));
DrawTheBitmap(pDC,
!sTitle.IsEmpty(),
&lpDIS->rcItem,
&captionRect,
m_bIsPressed,
m_bIsDisabled);
} // if
//………
}
创建蒙板
//I don’t know the essential of the code
HBITMAP CButtonST::CreateBitmapMask(HBITMAP hSourceBitmap, DWORD dwWidth,
DWORD dwHeight, COLORREF crTransColor)
{
HBITMAP hMask = NULL;
HDC hdcSrc = NULL;
HDC hdcDest = NULL;
HBITMAP hbmSrcT = NULL;
HBITMAP hbmDestT = NULL;
COLORREF crSaveBk;
COLORREF crSaveDestText;
hMask = ::CreateBitmap(dwWidth, dwHeight, 1, 1, NULL);
if (hMask == NULL) return NULL;
hdcSrc = ::CreateCompatibleDC(NULL);
hdcDest = ::CreateCompatibleDC(NULL);
hbmSrcT = (HBITMAP)::SelectObject(hdcSrc, hSourceBitmap);
hbmDestT = (HBITMAP)::SelectObject(hdcDest, hMask);
crSaveBk = ::SetBkColor(hdcSrc, crTransColor);
::BitBlt(hdcDest, 0, 0, dwWidth, dwHeight, hdcSrc, 0, 0, SRCCOPY);
crSaveDestText = ::SetTextColor(hdcSrc, RGB(255, 255, 255));
::SetBkColor(hdcSrc,RGB(0, 0, 0));
::BitBlt(hdcSrc, 0, 0, dwWidth, dwHeight, hdcDest, 0, 0, SRCAND);
::SetTextColor(hdcDest, crSaveDestText);
::SetBkColor(hdcSrc, crSaveBk);
::SelectObject(hdcSrc, hbmSrcT);
::SelectObject(hdcDest, hbmDestT);
::DeleteDC(hdcSrc);
::DeleteDC(hdcDest);
return hMask;
} // End of CreateBitmapMask
关于DrawTheBitmap
//(1)what is the effect of this line code:
COLORREF crOldColor = ::SetBkColor(hDC, RGB(255,255,255));
//(2)I don’t know the essential of the code
::BitBlt(pDC->m_hDC, rImage.left, rImage.top,
m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcMem, 0, 0, SRCAND);
::BitBlt(pDC->m_hDC, rImage.left, rImage.top,
m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcBmpMem, 0, 0, SRCPAINT);
void CButtonST::DrawTheBitmap(CDC* pDC, BOOL bHasTitle, RECT* rpItem,
CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled)
{
HDC hdcBmpMem = NULL;
HBITMAP hbmOldBmp = NULL;
HDC hdcMem = NULL;
HBITMAP hbmT = NULL;
BYTE byIndex = 0;
// Select the bitmap to use
if ((m_bIsCheckBox && bIsPressed) || (!m_bIsCheckBox && (bIsPressed ||
m_bMouseOnButton)))
byIndex = 0;
else
byIndex = (m_csBitmaps[1].hBitmap == NULL ? 0 : 1);
CRect rImage;
PrepareImageRect(bHasTitle, rpItem, rpCaption, bIsPressed,
m_csBitmaps[byIndex].dwWidth, m_csBitmaps[byIndex].dwHeight, &rImage);
hdcBmpMem = ::CreateCompatibleDC(pDC->m_hDC);
hbmOldBmp = (HBITMAP)::SelectObject(hdcBmpMem,
m_csBitmaps[byIndex].hBitmap);
hdcMem = ::CreateCompatibleDC(NULL);
hbmT = (HBITMAP)::SelectObject(hdcMem, m_csBitmaps[byIndex].hMask);
if (bIsDisabled && m_bShowDisabledBitmap)
{
HDC hDC = NULL;
HBITMAP hBitmap = NULL;
hDC = ::CreateCompatibleDC(pDC->m_hDC);
hBitmap = ::CreateCompatibleBitmap(pDC->m_hDC,
m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight);
HBITMAP hOldBmp2 = (HBITMAP)::SelectObject(hDC, hBitmap);
RECT rRect;
rRect.left = 0;
rRect.top = 0;
rRect.right = rImage.right + 1;
rRect.bottom = rImage.bottom + 1;
::FillRect(hDC, &rRect, (HBRUSH)RGB(255, 255, 255));
COLORREF crOldColor = ::SetBkColor(hDC, RGB(255,255,255));
::BitBlt(hDC, 0, 0, m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcMem, 0, 0, SRCAND);
::BitBlt(hDC, 0, 0, m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcBmpMem, 0, 0, SRCPAINT);
::SetBkColor(hDC, crOldColor);
::SelectObject(hDC, hOldBmp2);
::DeleteDC(hDC);
//the code above is to create a bitmap,because the DrawState
//function only accept the bitmap parameter.DrawState add
//some special state to the displayed bitmap.
pDC->DrawState( CPoint(rImage.left/*+1*/, rImage.top),
CSize(m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight),
hBitmap, DST_BITMAP | DSS_DISABLED);
::DeleteObject(hBitmap);
} // if
else
{
::BitBlt(pDC->m_hDC, rImage.left, rImage.top,
m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcMem, 0, 0, SRCAND);
::BitBlt(pDC->m_hDC, rImage.left, rImage.top,
m_csBitmaps[byIndex].dwWidth,
m_csBitmaps[byIndex].dwHeight, hdcBmpMem, 0, 0, SRCPAINT);
} // else
::SelectObject(hdcMem, hbmT);
::DeleteDC(hdcMem);
::SelectObject(hdcBmpMem, hbmOldBmp);
::DeleteDC(hdcBmpMem);
} // End of DrawTheBitmap