Window Programming Guide (2)

Source: Internet
Author: User
Tags drawtext format message

51. How to Create a font with a specific vertex size
 
You can specify the size of the logical unit of the font, but sometimes it is easier to specify the font point size.
Some. 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.
Degree. If the system font is used instead of other fonts
It is very important to select the body into the device context. 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 press when the title of the down button is changed
The size of the button. The size of the button depends on the font of the button and the title. When responding to the Message wm_settext
Call onsettext, which 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
 
As long as the user uses TrueType or GDI pen or font, the rotated text can be displayed (some hardware devices also
Supports rotating grating fonts ). The ifescapement member in the logfont structure specifies the angle between the text line and the X axis.
Degrees, and the angle is measured in a tenth rather than a degree. For example, if ifescapement is 450, the font is rotated.
45 degrees. To ensure that all fonts rotate in the Same Direction of the coordinate system, you must set ifescapement
Clip_lh_angles bits; otherwise, Some fonts may be rotated in reverse order. The following example uses the 14-point Arial font.
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
 
To call the GDI text painting function, expand the label characters.
CDC: tabbedtextout or CDC: drawtext and specify the dt_expandtabs flag.
. The tabbedtextout function allows you to specify an array of tag bits. In the following example, each 20 devices are displayed.
Open a tag:
 
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
 
Call the CDC: drawtext and specify the dt_end_ellipsis flag.
The character at the end of the generation string makes it suitable for the specified boundary rectangle. To display path information, specify
Dt_end_ellipsis flag and ellipsis to replace the character 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, which 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?
 
Set cframewnd: m_bautomenuenable to false.
Is true (default). The workbox will automatically disable the absence of on_update_command_ui or
On_command menu item.
 
// 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 add menu items to the menu. In the following example, add two new
Menu item:
 
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 be displayed in the status bar when the system menu item is highlighted.
A help information, which 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 frame window.
Degree and customer area. Second, the height of the customer area, box boundary, and title is subtracted 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 rows occupied by the Main Box menu.
Code implementation.
 
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
Call this function in the MFC function cmainframewnd: onncpaint to set the title Color of the window.
 
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.
To query and set system parameters, such as repeat rate setting of keys, double-click Delay Time, icon font
And 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 windows display information, such
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.
Check TMP environment variable: If TMP 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 the MFC
Function cframewnd: beginmodalstae: how to use 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 );
}
...
}
 
68,
12. How can I maximize and minimize windows and MDI windows as soon as they are started?
The two are merged into one.

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.