25. How to obtain information about the current message being processed by the window
Call cwnd: getcurrentmessage to obtain a MSG pointer. For example, you can use
Classwizard maps several menu item handlers to a function, and then calls getcurrentmessage
To determine the selected menu items.
Viod cmainframe: oncommmonmenuhandler ()
{
// Display selected menu item in debug window.
Trace ("menu item % u was selected./N ",
Getcruuentmessage ()-> wparam );
}
26. How to create an irregular window
You can use the new SDK function setjavaswrgn. This function limits painting and mouse messages to one in the window.
In fact, the window is made into a specified irregular shape.
Use Appwizard to create a pair-based application and use the resource editor to delete
In addition to the default control, title, and border.
Add a crgn data member to the dialog class and use the data member to create a window area later.
Class crounddlg: Public cdialog
{
...
PRIVATE:
Crgn m_rgn: // WINDOW REGION
...
};
Modify the oninitdialog function to create an elliptical region and call setdomainwrgn to allocate the region
Window:
Bool crounddlg: oninitdialog ()
{
Cdialog: oninitdialog ();
// Get size of dialog.
Crect rcdialog;
Getclientrect (rcdialog );
// Create region and assign to window.
M_rgn. createellipticrgn (0, 0, rcdialog. Width (), rcdialog. Height ());
Setjavaswrgn (getsafehwnd (), (hrgn) M _ RGN, true );
Return true;
}
By creating a region and calling setjavaswrgn, you have created an irregular window, as shown in the following example:
The subroutine is used to modify the onpaint function so that the window shape looks like a spherical body.
Voik crounddlg: onpaint ()
{
Cpaintdc de (this); // device context for painting.
// Draw Ellipse with out any border
DC. selecstockobject (null_pen );
// Get the RGB color components of the sphere color
Colorref color = RGB (0, 0,255 );
Byte byred = getrvalue (color );
Byte bygreen = getgvalue (color );
Byte byblue = getbvalue (color );
// Get the size of the View window
Crect rect;
Getclientrect (rect );
// Get minimun number of units
Int nunits = min (rect. Right, rect. Bottom );
// Calculate he horiaontal and vertical step size
Float fltstephen orz = (float) rect. Right/nunits;
Float fltstepvert = (float) rect. Bottom/nunits;
Int nellipse = nunits/3; // calculate how many to draw
Int nindex; // current ellipse that is being draw
Cbrush brush; // bursh used for ellipse fill color
Cbrush * pbrushold; // previous brush that was selected into DC
// Draw Ellipse, gradually moving towards upper-right corner
For (nindex = 0; nindes <+ nellipse; nindes ++)
{
// Creat solid brush
Brush. creatsolidbrush (RGB (nindex * byred)/nellipse ).
(Nindex * bygreen)/nellipse), (nindex * byblue)/nellipse )));
// Select brush into DC
Pbrushold = Dc. SelectObject (& brhsh );
// Draw Ellipse
DC. ellipse (INT) fltstephen orz * 2, (INT) fltstepvert * nindex,
Rect. Right-(INT) fltstephen orz * nindex) + 1,
Rect. Bottom-(INT) fltstepvert * (nindex * 2) + 1 );
// Delete the brush
Brush. delecteobject ();
}
}
Finally, the wm_nchittest message is processed so that the window can be moved whenever the window is hit.
Uint crounddlg: onnchittest (cpoint point)
{
// Let user move window by clickign anywhere on the window.
Uint nhittest = cdialog: onnchittest (point );
Rerurn (nhittest = htclient )? Htcaption: nhittest;
}
27. How to get the pointer of toolbar and status bar in code
The status bar and toolbar are used as subwindows and status bars of the main window when the work box is created.
There is an afx_idw_status_bar identifier, and the toolbar has a afx_idw_toolbar identifier.
Demonstrate how to call cwnd: getdescendantwindow and afxgetmainwnd together to obtain these
Sub-window pointer:
// Get pointer to status bar.
Cstatusbar * pstatusbar =
(Cstatusbar *) afxgetmainwnd ()-> getdescendantwindow
(Afx_idw_stutus_bar );
// Get pointer to toolbar.
Ctoolbar * ptoolbar =
(Ctoolbar *) afxgetmainwnd ()-> getdescendantwindow (afx_idw_toolbar );
28. How to enable and disable tooltip
If the cbrs_tooltips style bit is set, the toolbar displays a tooltip to enable or disable
Tooltip: You need to set or clear the style bit. In the following example, call ccontrolbar: getbarstyle
Create a member function with ccontrolbar: setbarstyle to complete this function:
Void cmainframe: enabletooltips (bool bdisplaytips)
{
Assert_valid (m_wndtoolbar );
DWORD dwstyle = M _ wndtoolbar. getbarstyle ();
If (bdisplaytips)
Dwstyle | = cbrs_tooltips;
Else
Dwstyle & = ~ Cbrs_tooltips;
M_wndtoolbar.setbarstyle (dwstyle );
}
29. How to set the toolbar title
The toolbar is a window, so you can call cwnd: setwindowtext to set the title. For example:
Int cmainframe: oncreate (maid)
{
...
// Set the caption of the toolbar.
M_wndtoolbar.setwindowtext (_ t "standdard ");
30. How to create and use the modeless dialog box
MFC encapsulates the mode and mode-free dialog in the same class, but it requires a few
A dialog takes several steps. First, use the resource editor to create a dialog resource and use
Classwizard creates a cdialog derived class. The pause of a Mode dialog is different from that of a Non-mode dialog:
A mode dialog is aborted by calling cdialog: enddialog. A mode dialog is called.
Cwnd: destroywindow to abort, function cdialog: onok and cdialog: oncancel
Call enddialog, so you need to call destroywindow and reset the function of the mode-free dialog.
Void csampledialog: onok ()
{
// Retrieve and validate dialog data.
If (! Updatedata (true ))
{
// The updatedata rountine will set focus to correct item
Traceo ("updatedata failed during dialog termination./N ");
Return;
}
// Call destroywindow instead of enddialog.
Destroywindow ();
}
Void csampledialog: oncancel ()
{
// Call destroywindow instead of enddialog.
Destroywindow ();
}
Second, you must delete the C ++ object indicating the dialog correctly. For mode, this is very easy. You need to create a function to return and then delete the C ++ object. If the mode-free dialog is not synchronous, it is returned immediately after the function is called, therefore, the user does not know when to delete the C ++ object. When you cancel a window, the workbox calls cwnd: postncdestroy to reset the function and perform cleanup operations, such as deleting the this pointer.
Void csampledialog: postncdestroy ()
{
// Declete the C ++ object that represents this dialog.
Delete this;
}
Finally, create a mode-free dialog. You can call cdialog: domodal to create a mode pair. To create a mode-free dialog, you must call cdialog: create. The following example illustrates how an application creates a mode-free dialog:
Void cmainframe: onsampledialog ()
{
// Allocate a modeless dialog object.
Csampledilog * pdialog = new csampledialog;
Assert_valid (pdialog );
// Create the modeless dialog.
Bool bresult = pdialog-> creste (idd_idalog );
Assert (bresult );
}
31. How to display a bitmap in the dialog box
This is due to Win 32's Advanced static controls and Microsoft's resource editor. It is easy to display bitmaps in the dialog box. You only need to drag the graphical controls into the dialog box and select the appropriate properties, you can also display icons, bitmaps, and Enhanced Meta files.
32. How to change the background color of a dialog or form window
Call cwinapp: setdialogbkcolor to change the background color of all applications. The first parameter specifies the background color, and the second parameter specifies the text color. In the following example, set the application dialog to blue background and yellow text.
Bool csampleapp: initinstance ()
{
...
// Use blue dialog with yellow text.
Setdialogbkcolor (RGB (0, 0,255), RGB (255,255, 0 ));
...
}
When you need to re-draw a dialog (or a sub-control of the dialog), Windows sends the message wm_ctlcolor to the dialog. Generally, you can ask windows to select a paint brush for the background or reset the specified brush for the message. The following example describes how to create a red background dialog.
First, add the one-person member variable cbursh to the dialog base class:
Class cmyformview: Public cformview
{
...
PRIVATE:
Cbrush M _ brush; // background brush
...
};
Second, initialize the brush to the desired background color in the class constructor.
Cmyformview: cmyformview ()
{
// Initialize background brush.
M_brush. createsolidbrush (RGB (0, 0,255 ))
}
Finally, use classwizard to process the wm_ctlcolor message and return a brush handle used to paint the conversation background. Note: The nctlcolor parameter must be checked because this function is also called when you redraw the dialog control.
Hbrush cmyformview: onctlcolor (CDC * PDC, cwnd * pwnd, uint nctlcolor)
{
// Determine if drawing a dialog box. If we are, return + handle
// Our own background brush. Otherwise let windows handle it.
If (nctlcolor = ctlcolor _ DLG)
Return (hbrush) m_brush. getsafehandle ();
Return cformview: onctlcolor (PDC, pwnd, nctlcolor );
}
33. How to obtain the pointer of a dialog control
There are two methods. First, call cwnd: getdlgitem to obtain a cwnd * pointer and call the member function. In the following example, call getdlgitem and pass the returned value to a cspinbuttonctrl * To Call The cspinbuttonctrl: setpos function:
Bool csampledialog: oninitdialog ()
{
Cdialog: oninitdialog ();
// Get pointer to spin button.
Cspinbuttonctrl * pspin-(cspinbuttonctrl *) getdlgitem (idc_spin );
Assert _ valid (pspin );
// Set spin button's default position.
Pspin-> setpos (10 );
Return true;
}
Second, you can use classwizard to associate the control with the member variables. In classwizard, simply select the member variables tag, and then select Add variable... Button. In the dialog resource editor, press Ctrl and double-click the control to go to The add member variable dialog.
34. How to disable and enable controls
Controls are also windows, so you can call cwnd: enablewindow to enable and disable controls.
// Disable button controls.
M_wndok.enablewindow (false );
M_wndapply.enablewindow (false );
35. How to change the control font
Since the control is a window, you can call cwnd: setfont to specify a new font. This function uses a cfont pointer. Make sure that the font object cannot be undone before the control is revoked. In the following example, the font of the press button is changed to the 8-point Arial font:
// Declare font object in class declaration (. h file ).
PRIVATE:
Cfont m_font;
// Set font in class implementation (. cpp file). Note m_wndbutton is
// Member variable added by classwizard. DDX routines hook the Member
// Variable to a dialog button contrlo.
Bool csampledialog: oninitdialog ()
{
...
// Create an 8-point Arial font
M_font. createfont (muldiv (8,-PDC-> getdevicecaps (logpixelsy), 72 ).
0, 0, 0, fw_normal, 0, 0, 0, ansi_charser, out_stroke_precis,
Clip_stroke _ PRECIS, draft _ Quality
Variable_pitch | ff_swiss, _ T ("Arial "));
// Set font for push button.
M_wndbutton. setfont (& M _ font );
...
}
36. How to Use the ole_color data type in the OLE Control
Functions such as colecontrol: getfortcolor and colecontrol: getbackcolor return the color of the OLE _ color data type. The GDI objects such as pens and brushes use the colorref data type and call the colecontrol :: translatecolor can easily change the ole_color type to the colorref type. In the following example, a paint brush with the current background color is created:
Void csamplecontrol: ondraw (CDC * PDC
Const crect & rcbounds, const crect & rcinvalid)
{
// Create a brush of the cuttent background color.
Cbrush brushback (translatecolor (getbackcolor ()));
// Paint the background using the current background color.
PDC-> filllrect (rcbounds, & brushback );
// Other drawin commands
...
}
37. How to display a file list without using a common file to open a dialog
Call cwnd: dlgdirlist or cwnd: dlgdirlistcombobox. Windows will automatically fill the list box or combo box with the available drive name or files in the specified directory, in the following example, the files in the Windows directory are filled in the combo box:
Bool csampledig: oninitdialog ()
{
Cdialog: oninitdialog ()
Tchar szpath [max_path] = {"C: // windows "};
Int nreslt = dlgdirlistcombobox (szpath, idc_combo, idc_curidir,
Ddl_readwrite | ddl_readonly | ddl_hidden |
Ddl_system | ddl_archive );
Return true;
}
38. Why does the rotate button control look reversed?
You need to call cspinctrl: setrange to set the range of the rotate button control. The default upper limit of the rotate button control is 0, and the default lower limit is 100, this means that when the value is increased, the rotation by control value is changed from 100 to 0. In the following example, set the rotation button control range to 0 to 100:
Bool caboutdlg: oninitdialog ()
{
Cdialog: oninitdialog ()
// Set the lower and upper limit of the Spin button
M_wndspin. setrange (0,100 );
Return true;
}
The copise rotation button control in the Visual C ++ 4.0 Print dialog has the same problem: the number of copies decreases when the up button is pressed, and the number of copies increases when the down button is pressed.
39. why can't the rotation button control automatically update the editing controls below it?
If you use the autu buddy feature of the rotate button, you must ensure that the buddy window takes precedence over the rotate button control in the mark sequence of the dialog. Select the tab order menu item from the layout menu (or press crtl + d) to set the tag order of the dialog.
40. How to use a bitmap to display the down button
Windows 95 buttons have several new creation styles, especially bs_bitmap and bs_icon. To have Bitmap Buttons, create buttons and call cbutton: setbitmap or cbutton :: when seticon is used, you must specify the bs_bitmap or bs_icon style.
First, set the icon properties of the button.
Then, call cbutton: seticon when the dialog is initialized. Note: In the following example, use an icon instead of a bitmap. Be careful when using a bitmap because you do not know all the colors of the background-Not everyone uses a light gray color.
Bool csampledlg: oninitdialog ()
{
Cdialog: oninitdialog ();
// Set the images for the push buttons.
M_wndbutton1.seticon (afxgetapp ()-> loadicon (IDI _ iption1 ))
M_wndbutton2.seticon (afxgetapp ()-> loadicon (IDI _ iption2 ))
M_wndbutton3.seticon (afxgetapp ()-> loadicon (IDI _ iption3 ))
Return true;
}
41. How to Create a triplicate button
You can use the new bs_pushbutton style bits, detection boxes, and buttons to create a three-state down button. This is easy. You only need to drag the detection box and button to the dialog box and specify the push-like attribute. A three-state down button can be used without any additional programs.
42. How to dynamically create controls
Allocates an instance of a control object and calls its create member function. Developers can easily ignore two things: Forgetting to specify the ws_visble tag and assigning control objects in the stack. The following example dynamically creates a lower pressure button control:
// In class declaration (. h file ).
PRIVATE:
Cbutton * M _ pbutton;
// In class implementation (. cpp file ).
M_pbutton = new cbutton;
Assert_valid (m_pbutton );
M_pbutton-> Create (_ T ("button title"), ws_child | ws_visible | bs_pushbutton.
Crect (0, 0,100, 24), this, IDC _ mybutton)
43. How to restrict Allowed characters in the editing box
If you can only receive numbers in the editing control, you can use a standard editing control and specify the new sign es_numbers, which is a new sign added in Windows 95, this flag limits the editing control to only accept numeric characters. If you need complex editing controls, you can use Microsoft's shielded editing control, which is a useful OLE custom control.
If you do not want to use the OLE custom control to process characters by yourself, you can derive a cedit class and process the wm_char message, and then filter out specific characters from the Edit Control. First, use classwizard to create a cedit derived class. Second, specify a member variable in the dialog class to classify the editing control in oninitdialog and call cwnd: subclassdlgitem.
// In your dialog class declaration (. h file)
PRIVATE:
Cmyedit m_wndedit; // instance of your new edit control.
// In You dialog class implementation (. cpp file)
Bool csampledialog: oninitdialog ()
{
...
// Subclass the edit lontrod.
M_wndedit. subclassdlgitem (idc_edit, this );
...
}
Use classwizard to process wm_char messages, calculate the nchar parameter, and determine the operation to perform. You can determine whether to modify and transmit characters. The following example shows how to display letter characters. If the character is a letter character, cwnd; onchar is called; otherwise, onchar is not called.
// Only display alphabetic dharacters.
Void cmyedit: onchar (uint nchar, uint nrepcnt, uitn nflags)
{
// Determine if nchar is an alphabetic character.
If (: ischaralpha (tchar) nchar ))
Cedit: onchar (nchar, nrepcnt, nflags );
}
If you want to modify the characters, you cannot simply call cedit: onchar with the modified nchar. Then, cedit: onchar calls cwnd: Default to obtain the original wparam and lparam values, this is not acceptable. To modify a character, you must first modify nchar and then call cwnd: defwindowproc with the modified nchar. The following example shows how to convert a character to uppercase:
// Make all characters uppercase
Void cmyedit: onchar (uint nchar, uint nrepcnt, uint nflags)
{
// Make sure character is uppercase.
If (: ischaralpha (. (tchar) nchar)
Nchar =: charupper (nchar );
// Bypass default onchar processing and directly call
// Default Window Proc.
Defwindproc (wm_char, nchar, makelparam (nrepcnt, nflags ));
}
44. How to change the color of controls
There are two methods. First, you can specify the color of the control in the parent class, or use the new message reflection of mfc4.0 to specify the color in the control class. When the control needs to be re-colored, The workbox calls the cwnd: oncrtlcolor of the parent window (usually the dialog box, you can reset the function in the parent window class and specify the new painting property of the control. For example, the following code changes the text color of all edit controls in the dialog to Red:
Hbrush caboutdig: onctlcolor (CDC * pdcm, cwnd * pwnd, uint nctlcolor)
{
Hbrush HBr = cdialog: onctlcolor (PDC, pwnd, nctlcolor );
// Draw red text for all edit controls.
If (nctlcolor = ctlcolor_edit)
PDC-> settextcolor (RGB (255, 0, 0 ,));
Return HBr;
}
However, since each parent window must process notification messages and specify the painting attributes of each control, this method is not completely object-oriented. Control to process the message and specify the painting attribute. Message reflection allows you to do this. The notification message is sent to the parent window first. If the parent window is not processed, it is sent to the control. To create a custom color list box control, follow these steps.
First, use classwizard to create a clistbox derived class and add the following data members to the class.
Class cmylistbox; publilc clistbox
{
...
Private;
Colorref m_clrfor; // foreground color
Colorref m_clrback; // background color
Cbrush m_brush; // background brush
...
};
Second, in the class constructor, the initialization data.
Cmylistbox: cmylistbox ()
{
// Initialize data members.
M_clrfore = RGB (255,255, 0); // yellow text
M_clrback = RGB (0, 0,255); // blue background
M_brush. createsolidbrush (M _ clrback );
}
Finally, use classwizard to process the reflected wm_ctlcolor (= wm_ctlcolor) message and specify the new painting attribute.
Hbrush cmylistbox: ctlcolor (CDC * PDC, uint nctlcolor)
{
PDC-> settextcolor (m_clrfore );
PDC-> setbkcolor (m_clrback );
Return (hbrush) m_brush.getsafehandle ()
}
Now, the control can decide how to paint it by yourself, and it has nothing to do with the parent window.
45. How to Prevent flickering when multiple items are added to the list box
You can call cwnd: setredraw to clear the redraw flag to disable clistbox (or window) repainting. When you add several items to the list box, you can clear the re-painting mark, add the item, and restore the re-painting mark. To ensure that the new item in the redraw list box is called, call setredraw (true) and then call cwnd: invalidate.
// Disable redrawing.
Plistbox-> setredraw (false );
// Fill in the list box Gere
// Enable drwing and make sure list box is redrawn.
Plistbox-> setredraw (true );
Plistbox-> invalidate ();
46. How to add text to the editing Control
Because there is no cedit: appendtext function, you have to do this on your own. Call cedit: setsel to move to the end of the editing control, and then call cedit: replacesel to add text. The following is an implementation method of appendtext:
Void cmyedit: appendtext (lpcstr ptext)
{
Int nlen = getwindowtextlength ();
Setfocus ();
Setsel (nlen, nlen );
Replacesel (ptext );
}
47. How to access a predefined GDI object
You can call CDC: slectstockobject to use several predefined windows objects, such as brushes, pens, and fonts. The following example uses a pre-defined pen and brush for Windows. The GDI object draws an ellipse in the window.
// Draw Ellipse using stock black pen and gray brush.
Void csampleview: ondraw (CDC * PDC)
{
// Determine size of view.
Crect rcview;
Getclientrect (rcview );
// Use stock black pen and stock gray brush to Draw Ellipse.
PDC-> selectstockobject (black_pen );
PDC-> selectstockobject (gray_brush)
// Draw the ellipse.
PDC-> ellipse (review );
}
You can also call the new SDK function getsyscolorbrush to obtain a system color brush. The following example uses the background color to draw an ellipse in the window:
Void csampleview: ondraw (CDC * PDC)
{
// Determine size of view.
Crect rcview;
Getclientrect (rcview );
// Use background color for tooltips brush.
Cbrush * porgbrush = PDC-> SelectObject (
Cbrush: fromhandle (: getsyscolorbrush (color_infobk )));
// Draw the ellipse.
PDC-> ellipse (rcview );
// Restore original brush.
PDC-> SelectObject (porgbrush );
}
48. How to obtain the property information of a GDI object
You can call gdiobject: GetObject. This function writes messages from the specified chart device to the buffer zone. The following example creates several useful auxiliary functions.
// Determine if font is bold.
Bool isfontbold (const cfont & font)
{
Logfont stfont;
Font. GetObject (sizeof (logfont), & stfont );
Return (stfont. lfbold )? True: false;
}
// Return the size of a bitmap.
Csize getbitmapsize (const cbitmap & Bitmap)
{
Bitmap stbitmap;
Bitmap. GetObject (sizeof (Bitmap), & stbitmap );
Return csize (stbitmap. bmwidth, stbitmap. bmheight );
}
// Create a pen with the same color as a brush.
Bool createpenfrombrush (cpen & pen, cost cbrush & brush)
{
Logbrush stbrush;
Brush. GetObject (sizeof (logbrush), & stbrush );
Return pen. createpen (ps_solid, 0, stbrush. ibcolor );
}