Visual c ++ programming skills (II)

Source: Internet
Author: User
Tags drawtext format message
49. How to implement a rubber rectangle

Crecttracker is a very useful class. You can call crecttracker: trackrubberband to respond to the wm_lbuttondown message to create a rubber rectangle. The following example shows that it is easy to use crecttracker to move and reset the blue oval size in the window.

First, declare a crecttracker data member in the file:

Class csampleview: Public cview

{

...

Public:

Crecttracker m_tracker;

...

};

Second, initialize the crecttracker object in the constructor of the document class:

Csampledoc: csampledoc ()

{

// Initialize tracker position, size and style.

M_tracker.m_rect.setrect (0, 0, 10, 10 );

M_tracker.m_nstyle = crecttracker: resizeinside |

Crecttracker: dottedline;

}

Then, draw an ellipse and a trace rectangle in the ondraw function:

Void csampleview: ondraw (CDC * PDC)

{

Csampledoc * pdoc = getdocument ();

Assert_valid (pdoc );

// Select blue brush into device context.

Cbrush brush (RGB (0, 0,255 ));

Cbrush * poldbrush = PDC-> SelectObject (& brush );

// Draw Ellipse in tracking rectangle.

Crect rcellipse;

Pdoc-> m_tracker.gettruerect (rcellipse );

PDC-> ellipse (rcellipse );

// Draw tracking rectangle.

Pdoc-> m_tracker.draw (PDC );

// Select blue brush out of device context.

PDC-> SelectObject (poldbrush );

}

Finally, use classwizard to process the wm_lbuttondown message and add the following code. The code can be dragged, moved, or reset Based on mouse clicks.

Void csampleview: onlbuttondown (uint nflags, cpoint point)

{

// Get pointer to document.

Csampledoc * pdoc = getdocument ();

Assert_valid (pdoc );

// If clicked on ellipse, drag or resize it. Otherwise create

// Rubber-band rectangle nd create a new ellipse.

Bool bresult = pdoc-> m_tracker.hittest (point )! =

Crecttracker: hitnothing;

// Tracker rectangle changed so Update views.

If (bresult)

{

Pdoc-> m_tracker.track (this, point, true );

Pdoc-> setmodifiedflag ();

Pdoc-> updateallviews (null );

}

Else

Pdoc-> m-tracker.TrackRubberBand (this, point, true );

Cview: onlbuttondown (nflags, point );

}

50. Update the text of the flipped background color

Call CDC: setbkmode and send opaque to fill the background with the current background color, or call CDC: setbkmode and send transpaarent to keep the background unchanged. You can set the background mode either. In the following example, the background mode is set to transparent. You can update the string twice and update the text with a flower belt and a black shadow. The black string is behind the red string, but the background mode is still visible.

Void csampleview: ondraw (CDC * PDC)

{

// Determint size of view.

Crect rcview;

Getclientrect (rcvieew );

// Create sample string to display.

Cstring STR (_ T ("awesome shadow text ..."));

// Set the background mode to transparent.

PDC-> setbkmode (transparent );

// Draw black shadow text.

Rcview. offsetrect (1, 1 );

PDC-> settextcolor (RGB (0, 0, 0 ));

PDC-> drawtext (STR, str. getlength (), rcview,

Dt_singleline | dt_center | dt_vcenter );

// Draw red text.

Rcview. offsetrect (-1,-1 );

PDC-> settextcolor (RGB (255, 0, 0 ));

PDC-> drawtext (STR, str. getlength (), rcview,

Dt_singleline | dt_center | dt_vcenter );

}

51. How to Create a font with a specific vertex size

You can specify the logical unit of the font, but it is more convenient to specify the font point size. You can convert the font point to the font height as follows:

Int nheigth = muldiv (npointsize,-DC. getdevicecaps (logpixelsy), 72 );

In the following example, an apial font at is created:

Cclientdc DC (aqfxgetmainwnd ());

M_font. createfont (muldiv (8,-DC. getdevicecaps (logpixelsy ),

72), 0, 0, 0, fw_normal, 0, 0, ansi_charset,

Out_stroke_precis, clip_stroke_precis, draft_quality,

Variable_pitch | FF-SWISS, _t ("Arial "));

52. How to calculate the size of a string

Function CDC: det text extent calculates the height and width of a string based on the selected font. If the system font is used instead of other fonts, it is important to select the font into the device context before calling gettextextent. Otherwise, the height and width are calculated based on the system font, of course, the result is incorrect. The following sample program dynamically adjusts the button size when the title of the down button is changed. The size of the button depends on the font and title of the button. Onsettext is called when the message wm_settext is returned. The message is a custom message defined by the on_messae macro command.

Lresult cmybutton: onsettext (wparam, lparam)

{

// Pass message to window procedure.

Lresult bresult = callwindowproc (* getsuperwndprocaddr (),

M_hwnd, getcurrentmessage ()-> message, wparam, lparam );

// Get title of push button.

Cstring strtitle;

Getwindowtext (strtitle );

// Select current font into device context.

CDC * PDC = getdc ();

Cfont * pfont = getfont ();

Cfont * poldfont = PDC-> SelectObject (pfont );

// Calculate size of title.

Csize size = PDC-> gettextexent (strtitle, strtitle. getlength ());

// Adjust the button's size based on its title.

// Add a 5-pixel border around the button.

Setwindowpos (null, 0, 0, size. cx + 10, size. Cy + 10,

Swp_nomove | swp_nozorder | swp_noactivate );

// Clean up.

PDC-> selectfont (poldfont );

Releasedc (PDC );

Return bresult;

}

53. How to display rotated text

Rotating text can be displayed as long as you use TrueType or GDI pen or font (some hardware devices also support rotating grating fonts ). The ifescapement member in the logfont structure specifies the angle of the text line and the X axis. The angle is measured in a tenth rather than a degree. For example, if ifescapement is 450, the font rotation is 45 degrees. To ensure that all fonts are rotated in the Same Direction of the coordinate system, you must set the clip_lh_angles bit of the ifescapement member. Otherwise, some fonts may be rotated in reverse direction. The following example uses the 14-point Arial font to draw a string every 15 degrees.

Void csampleview: ondraw (CDC * PDC)

{

// Determine the size of the window.

Crect rcclient;

Getclientrect (rcclient );

// Create sample string.

Cstring STR (_ T ("Wheeee... I am rotating! "));

// Draw transparent, red text.

PDC-> setbkmode (transparent );

PDC-> settextcolor (RGB (255, 0, 0 ));

Cfont font; // font object

Logfont stfont; // font Definition

// Set Font attributes that will not change.

Memset (& stfont, 0, sizeof (logfont ));

Stfont. ifheight = muldiv (14,-PDC-> getdevicecaps (logpixelsy), 72 );

Stfont. ifweight = fw_normal;

Stfont. ifclipprecision = lcip_lh_angles;

Strcpy (stfont. lffacename, "Arial ");

// Draw text at 15 degree intervals.

For (INT nangle = 0; nangle <3600; nangle + = 150)

{

// Specify new angle.

Stfont. lfescapement = nangle;

// Create and select font into DC.

Font. createfontindirect (& stfont );

Cfont * poldfont = PDC-> SelectObject (& font );

// Draw the text.

PDC-> SelectObject (poldfont );

Font. delectobjext ();

}

}

54. How to correctly display strings containing tag characters

When calling the GDI text painting function, you need to expand the label characters. This can be done by calling the CDC: tabbedtextout or CDC: drawtext and specifying the dt_expandtabs flag. The tabbedtextout function allows you to specify an array of tag bits. In the following example, you can specify a tag for every 20 device units:

Void csampleview: ondraw (CDC * PDC)

{

Ctestdoc * pdoc = getdocument ();

Assert_valid (pdoc );

Cstring STR;

Str. Format (_ T ("Cathy/tnorman/Toliver "));

Int ntabstop = 20; // tabs are every 20 pixels

PDC-> tabbedtextout (10, 10, STR, 1, & ntabstop, 10 );

}

55. How to display a ellipsis at the end of a string that is too long

You can call the CDC: drawtext and specify the dt_end_ellipsis flag to replace the character at the end of the string with a small dot so that it is suitable for the specified boundary rectangle. If you want to display the path information, specify the dt_end_ellipsis flag and ellipsis to replace the characters in the middle of the string.

Void csampleview: ondraw (CDC * PDC)

{

Ctestdoc * pdoc = getdocument ();

Assert_valid (pdoc );

// Add ellpsis to end of string if it does not fit

PDC-> drawtext (cstring ("this is a long string "),

Crect (10, 10, 80, 30), dt_left | dt_end_ellipsis );

// Add ellpsis to middle of string if it does not fit

PDC-> drawtext (afxgetapp ()-> m_pszhelpfilepath,

Crect (10, 40,200, 60), dt_left | dt_path_ellipsis );

}

56. How to quickly format A cstring object

Call cstring: format. This function has the same parameters as the printf function. The following example shows how to use the format function:

// Get size of window.

Crect rcwindow;

Getwindowrect (rcwindow );

// Format message string.

Cstring strmessage;

Strmessage. Format (_ T ("window size (% d, % d )"),

Rcwindow. Width (), rcwindow. Height ());

// Display the message.

MessageBox (strmessage );

57. Why is the menu item still disabled even after the enablemenuitem menu item is called?

You need to set cframewnd: m_bautomenuenable to false. If the data member is true (default), the Work box will automatically Disable menu items without on_update_command_ui or on_command.

// Disable MFC from automatically disabling menu items.

M_bauomenuenable = false;

// Now enable the menu item.

Cmenu * pmenu = getmenu ();

Assert_valid (pmenu );

Pmenu-> enablemenuitem (id_menu_item, mf_bycommand | mf_enabled );

58. How to add a menu item to the System Menu

To add a menu item to the system menu, perform the following three steps:

First, use the resource symbols Dialog (in the View menu, select resource symbols...

Can display this dialog box) define the menu item ID, which should be greater than 0x0f and less than 0xf000;

Next, call cwnd: getsystemmenu to obtain the pointer of the System menu and call cwnd: appendmenu to add the menu item to the menu. In the following example, two new menu items are added to the system menu:

Int cmainframe: oncreate (maid)

{

...

// Make sure system menu item is in the right range.

Assert (idm_mysysitem & 0xfff0) = idm_mysysitem );

Assert (IDM-MYSYSITEM <0xf000 );

// Get pointer to system menu.

Cmenu * psysmenu = getsystemmenu (false );

Assert_valid (psysmenu );

// Add a separator and our menu item to system menu.

Cstring strmenuitem (_ T ("new menu item "));

Psysmenu-> appendmenu (mf_separator );

Psysmenu-> appendmenu (mf_string, idm_mysysitem, strmenuitem );

...

}

Now, when selecting the system menu item, the user should perform detection. Use classwizard for processing

Wm_syscommand:

Void cmainframe: onsyscommand (uint NID, lparam)

{

// Determine if our system menu item was selected.

If (NID & 0xfff0) = idm_mysysitem)

{

// Todo-Process System menu item

}

Else

Cmdiframewnd: onsyscommand (NID, lparam );

}

Finally, a well-designed UI application should display a help message in the status bar when the system menu item is highlighted, this can be achieved by adding an entry to the string table containing the system menu base ID.

59. How to determine the number of menu lines occupied by top-level menus

This can be achieved through simple subtraction and division. First, you need to calculate the height of the main box window and the customer area. Second, subtract the height of the customer area, box border, and title from the height of the main box window. Finally, divide it by the height of the menu bar. In the following example, a member function is used to calculate the number of lines occupied by the Main Box menu.

Int cmainframe: getmenurows ()

{

Crect rcframe, rcclient;

Getwindowrect (rcframe );

Getclientrect (rcclient );

Return (rcframe. Height ()-rcclient. Height ()-

: Getsystemmetrics (sm_cycaption )-

(: Getsystemmetrics (sm_cyframe) * 2 ))/

: Getsystemmetrics (sm_cymenu );

}

60. How to determine the color of the system display element in the user environment

Call the SDK function getsyscolor to obtain the color of a specific display element. The following example shows how to set the title Color of the window by calling the function cmainframewnd: onncpaint In the MFC function.

Void cminiframewnd: onncpaint ()

{

...

DC. settextcolor (: getsyscolor (m_bactive?

Color_captiontext: color_inactivecaptiontext ));

...

}

61. How to query and set System Parameters

We have introduced the SDK function systemparametersinfo in the Windows 3.1 SDK. You can call this function to query and set system parameters, such as the repeat rate setting of buttons, the delay time of double-clicking the mouse, the icon font, and the desktop overlay bitmap.

// Create a font that is used for icon titles.

Logfont stfont;

: Systemparametersinfo (spif_geticontitlelogfont,

Sizeof (logfont), & stfont, spif_sendwininichange );

M_font.createfontindirect (& stfont );

// Change the wallpaper to leaves.bmp.

: Systemparametersinfo (spi_set1_wallpaper, 0,

_ T ("forest.bmp"), spif_updateinifile );

62. How to use a predefined windows cursor

Call cwinapp: loadstandardcursor and send the cursor identifier.

Bool csampledialog: onsetcursor (cwnd * pwnd, uint nhittest, uint message)

{

// Display wait cursor if busy.

If (m_bbusy)

{

Setcursor (afxgetapp ()-> loadstandardcursor (idc_wait ));

Return true;

}

Return cdialog: onsetcursor (pwnd. nhittest, message );

}

63. How to determine the current screen resolution

Call the SDK function getsystemmetrics to retrieve information about Windows display, such as the title size, boundary size, and scroll bar size.

// Initialize csize object with screen size.

Csize sizescreen (getsystemmetrics (sm_cxscreen ),

Getsystemmetrics (sm_cyscreen ));

64. How to retrieve the task list used by the original Task Manager Application

The previous Task Manager application displays the list of top-level windows. To display the list

Must be visible, contain a title, and cannot be owned by other windows. You can call cwnd: getwindow.

To retrieve the list of top-level windows, call iswindowvisible, getwindowtextlength, and getowner

You can determine whether the window should be in the list. In the following example, the title of the TaskManager window is filled in the list.

Void gettadklist (clistbox & List)

{

Cstring strcaption; // caption of window.

List. resetcontent (); // clear list box.

// Get first window in window list.

Assert_valid (afxgetmainwnd ());

Cwnd * pwnd = afxgetmainwnd ()-> getwindow (gw_hwndfirst );

// Walk window list.

While (pwnd)

{

// I window visible, has a caption, and does not have an owner?

If (pwnd-> iswindowvisible ()&&

Pwnd-> getwindowtextlength ()&&! Pwnd-> getowner ())

{

// Add caption o window to list box.

Pwnd-> getwindowtext (strcaption );

List. addstring (strcaption );

}

// Get next window in window list.

Pwnd = pwnd-> getwindow (gw_hwndnext );

}

}

65. How to Determine windows and Windows Directories

There are two SDK functions to complete this function. Getwindowsdirectory and getsystemdirectory. The following example shows how to use these two functions:

Tchar szdir [max_path];

// Get the full path of the Windows directory.

: Getwindowsdirectory (szdir, max_path );

Trace ("Windows Directory % s/n", szdir );

// Get the full path of the Windows System directory.

: Getsystemdirectory (szdir, max_path );

Trace ("Windows System directory % s/n", szdir );

66. Where can I create a temporary file?

Call the SDK function gettempath to determine the directory of the temporary file. This function first detects the TMP environment variable for the temporary path: If the TMP environment variable is not specified, check the TMP environment variable and return it to the current directory. The following example shows how to create a temporary file.

...

// Get unique temporary file.

Cstring strfile;

Getuniquetempname (strfile );

Try

{

// Create File and write data. Note that file is closed

// In the destructor of the cfile object.

Cfile file (strfile, cfile: modecreate | cfile: modewrite );

// Write data

}

Catch (cfileexception, E)

{

// Error opening file

}

End_catch

...

Void getuniquetempname (cstring & strtempname)

{

// Get the temporary files directory.

Tchar sztemppath [max_path];

DWORD dwresult =: gettemppath (max_path, sztemppath );

Assert (dwresult );

// Create a unique temporary file.

Tchar sztempfile [max_path];

Uint nresult = gettempfilename (sztemppath, _ T ("~ Ex "), 0, sztempfile );

Assert (nresult );

Strtempname = sztempfile;

}

67. How to access the desktop window

The static function cwnd: getdomaintopwindow returns the pointer of the desktop window. The following example illustrates how the MFC function cframewnd: beginmodalstae uses this function to enter the internal window list.

Void cframewnd: beginmodalstate ()

{

...

// First count all windows that need to be disabled

Uint ncount = 0;

Hwnd =: getwindow (: get1_topwindow (), gw_child );

While (hwnd! = NULL)

{

If (: isw.wenabled (hwnd )&&

Cwnd: fromhandlepermanent (hwnd )! = NULL &&

Afxisdescendant (pparent-> m_hwnd, hwnd )&&

: Sendmessage (hwnd, wm_disablemodal, 0, 0) = 0)

{

++ Ncount;

}

Hwnd =: getwindow (hwnd, gw_hwndnext );

}

...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.