MFC skills 4

Source: Internet
Author: User
Tags drawtext
31. How do I add characters to the editing control by appending them?

[Question]
Setdlgitemtext can be used to enter characters in the edit control and send updated messages. However, the Edit Control displays the values of the variables associated with the change. What should I do if I append a character to an existing edit character?
[Program Implementation]
Create a dialog project named my, add an edit and a button control. Edit ID = idc_edit1, button id = idc_button1. Create and idc_button1 response function: onbutton1 ()
Void cmydlg: onbutton1 ()
{
Cstring ptext = "hello ";
Cedit * m_edit = (cedit *) getdlgitem (idc_edit1 );
Int nlen = m_edit-> getwindowtextlength ();
M_edit-> setfocus ();
M_edit-> setsel (nlen, nlen );
M_edit-> replacesel (ptext );
}
Enter a character in the edit control and press the idc_button1 button to append the object.

32. Rename the title of the property page

I use cpropertysheet to create an attribute page. Only one cpropertypage object is used, that is, the content of each attribute page is the same. the problem is that the title of each property page is the same as that of the dialog box! How can I dynamically change the title so that the names of tags on each property page are different ??

Ctabctrl * pctrl = psheet-> gettabcontrol ();
Tcitem TC;
TC. Mask = tcif_text;
TC. psztext = "New title ";
Pctrl-> setitem (0, & TC); // 0 is the index of the tab you want to change

33. How do I remove the apply and help buttons on the property page?

// Remove help
M_psh.dwflags | = psh_hashelp;
M_psh.dwflags & = ~ Psh_hashelp;
// Remove the application button m_psh.dwflags | = psh_noapplynow;

34. How to add a tooltip to the tree control

1. First add the tvs_infotip attribute style to the tree control, as shown below:

If (! M_ctrltree.create (ws_child | ws_visible |
Tvs_haslines | tvs_hasbuttons | tvs_linesatroot | tvs_showselalways | tvs_infotip, // Add the prompt tvs_infotip, jingzhoxu (tree control ID: 100)
Crect (0, 0, 0, 0), & m_wndtreebar, 100 ))
{
Trace0 ("failed to create instant bar child/N ");
Return-1;
}

2. Add the ing message declaration as follows:

Afx_msg void ongetinfotip (nmhdr * pnmhdr, lresult * presult); // Add the prompt message to the tree control, Jingzhou Xu

On_notify (tvn_getinfotip, 100, ongetinfotip) // Add a prompt to the tree control entry, Jingzhou Xu

3. Add echo Han number processing:

Void ccreatetreedlg: ongetinfotip (nmhdr * pnmhdr,
Lresult * presult)
{
* Presult = 0;
Nmtvgetinfotip * ptvtipinfo = (nmtvgetinfotip *) pnmhdr;
Lparam itemdata = (DWORD) ptvtipinfo-> lparam;
// Data of each entry
Htreeitem hitem = ptvtipinfo-> hitem;
Cstring tip;
Htreeitem hrootitem = m_chassistree.getrootitem ();
If (hrootitem! = Ptvtipinfo-> hitem)
{
Tip = "Tree node prompt ";
}
Else
{
Tip = "tips on the root ";
}
Strcpy (ptvtipinfo-> psztext, (lpctstr) tip );
}

35. How do I add icons in treelist?

[Question]
What are the differences between the Treeview control and treectrl control? How can I add images to the imagelist control?
[Solution]
1)
Hicon [8];
M_imagelist.create (16, 16, 0, 8 );
Hicon [0] = afxgetapp ()-> loadicon (idi_icon0 );
Hicon [1] = afxgetapp ()-> loadicon (idi_icon1 );
Hicon [2] = afxgetapp ()-> loadicon (idi_icon2 );
Hicon [3] = afxgetapp ()-> loadicon (idi_icon3 );
Hicon [4] = afxgetapp ()-> loadicon (idi_icon4 );
Hicon [5] = afxgetapp ()-> loadicon (idi_icon5 );
Hicon [6] = afxgetapp ()-> loadicon (idi_icon6 );
Hicon [7] = afxgetapp ()-> loadicon (idi_icon7 );
For (INT n = 0; n <8; n ++)
M_imagelist.add (hicon [N]);

Ctreectrl * ptree = (ctreectrl *) getdlgitem (idc_tree );
Ptree-> setimagelist (& m_imagelist, tvsil_normal );

2)
Cimagelist cil1;
Cil1.create (32, 32, true, 2, 2 );
Cil1.add (PAPP-> loadicon (idi_dao1 ));
Cil1.add (PAPP-> loadicon (idi_dao2 ));
Cil1.add (PAPP-> loadicon (idi_dao3 ));
Cil1.add (PAPP-> loadicon (idi_dao4 ));
Cil1.add (PAPP-> loadicon (idi_dao5 ));
Cil1.add (PAPP-> loadicon (idi_dao6 ));
Cil1.add (PAPP-> loadicon (idi_dao7 ));
Cil1.add (PAPP-> loadicon (idi_dao8 ));
Cil1.add (PAPP-> loadicon (idi_dao9 ));
  
// Set the image list
M_list.setimagelist (& cil1, lvsil_normal );

36. How to double-click the list box item to start a program associated with the file?

Someone asked me how to double-click the list box item to start a program? In fact, this problem is very simple. There is an API function in Windows that can open any type of files:

ShellExecute (null, "open", lpfilename, null, null, sw_shownormal );

Parameter lpfilename
Is the full path name of the file. With this variable you can pass startup like "C: // myexcelfile.xls" or "http://www.vckbase.com"
Excel or browser programs. If you only want to get the program name associated with the file, instead of running the program, you can call: findexecutable.

37. How can I prevent the constant refreshing of a large amount of data added to the ListBox?

[Question]
When adding a lot of data to the ListBox, the control is constantly refreshed, causing flashes. How can this problem be solved?
[Solution]
Before adding data, do not refresh the control. After adding the data, refresh the control again.
[Program Implementation] (m_listbox is the control type variable of clistbox)
M_listbox.lockwindowupdate (); // This ListBox cannot be refreshed.
For (INT I = 0; I <9999; I ++)
{
M_listbox.addstring ("test ");
} // Add data.
This-> redrawwindow (null, null, rdw_invalidate | rdw_updatenow | rdw_erase );

38. How do I get the string of the selected clistbox item?

[Question]
How to obtain the string of the selected clistbox item
[Solution]
Used: clistbox: gettext ()
[Program Implementation]
Cstring scinfo;
Plist-> gettext (getcursel (), scinfo );

39. A simple method to move a dialog box without a title bar program with the mouse

Void cvctestdlg: onlbuttondown (uint nflags, cpoint point)
{
// Solve the problem in one sentence
Sendmessage (wm_syscommand, 0xf012, 0 );
Cdialog: onlbuttondown (nflags, point );
}

40. How to change the background color of a dialog box or 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 );
}

41. how to disable the system menu on the button and floating toolbar in the dialog box

1. There are two methods to close the button in the disallow dialog box.
The first method is implemented by using the number of modiftmenu () Han:

Cmenu * pmenu = This-> getsystemmenu (false );
Pmenu-> modifymenu (SC _close, mf_bycommand | mf_grayed );

The second method is implemented using the enablemenuitem () Han Number:

Cmenu * pmenu = This-> getsystemmenu (false );
Pmenu-> enablemenuitem (SC _close, mf_bycommand | mf_grayed );

2. disable the system menu on the floating toolbar.
Create a ctoolbar derived class cxxtoolbar, and double-click the left button in the new class (cxxtoolbar: onlbuttondblclk (...))
And the following code can be added to the left-click (cxxtoolbar: onlbuttondown (...) Han numbers respectively:
If (isfloating () // The toolbar is floating
{
Cwnd * pminiframe;
Cwnd * pdockbar;

Pdockbar = getparent ();
Pminiframe = pdockbar-> getparent ();

// Remove the system menu from it
Pminiframe-> modifystyle (ws_sysmenu, null );

// Repaint Toolbar
Pminiframe-> showwindow (sw_hide );
Pminiframe-> showwindow (sw_show );
}

3. Disable window maximization button
Remove the ws_maximizebox style display in the precreatewindow () Han number.
Bool cxxframewnd: precreatewindow (createstruct & CS)
{
CS. Style & = ~ Ws_maximizebox;
Return cframewnd: precreatewindow (CS );
}

42. How do I copy the resources of a project dialog box to another project?

There are two ways to achieve this:
 
1) You can directly copy the resource, use VC ++ to open the. RC file in text mode or directly use a text editor
Copy a project to another project. You can find the following snippets (this snippet is used to define dialog box resources) to copy
Section:
 
Idd_mydialog_id dialog discardable 0, 0,235, 55
 
Here, idd_mydialog_id is the ID of your dialog box. Copy all the parts at the end of this clip. Generally, you need to give the new project
Add an ID (use the devstudio tool or directly modify the resource. h file ).

2) You can use the copy/paste function of devstudio. First, open the. RC file in "Auto" mode in the editor.
Correctly displayed. Then, select the ID of the dialog box to be copied, select copy in the edit menu, or press Ctrl + C. Then open the target
Resource file, select Paste in the edit menu or press Ctrl + v.

43. How to automatically hide the dialog box by clicking the area outside the dialog box?

[Question]
What should I do if I want to close the dialog box outside the dialog box?

[Solution]
Try the following code. The principle is to capture the mouse action when activating the dialog box. When you click the mouse, determine whether to click it outside the dialog box. If yes, release the dialog box.

[Program Implementation]
Create a dialog box program named my. perform the following steps:
Add the following to mydlg. h:

Class cshowwindow1dlg: Public cdialog
{
// Construction
Public:
Int m_cx;
Int m_cy;
......
};

In mydlg. cpp:

// Define the message image, process mouse clicks and Activation
Begin_message_map (cmydlg, cdialog)
// {Afx_msg_map (cmydlg)
On_wm_lbuttondown ()
On_wm_activate ()
//} Afx_msg_map
End_message_map ()

Void cmydlg: onlbuttondown (uint nflags, cpoint point)
{
Crect rect;
Getclientrect (& rect );
Rect. inflaterect (m_cx, m_cy );
 
// Release dialog if the user click outside it.
If (! Rect. ptinrect (point ))
{
Enddicel (idcancel );
}

Cdialog: onlbuttondown (nflags, point );
}

Void cmydlg: onactivate (uint nstate, cwnd * pwndother, bool bminimized)
{
Cdialog: onactivate (nstate, pwndother, bminimized );

If (nstate = wa_active | nstate = wa_clickactive)
Setcapture ();
Else
Releasecapture ();
}

Bool cmydlg: oninitdialog ()
{
Cdialog: oninitdialog ();
.....
    
Osversioninfo Info;
Memset (char *) & info, 0, sizeof (osversioninfo ));
Info. dwosversioninfosize = sizeof (osversioninfo );
If (getversionex (& info ))
{// We don't run on win32s, so check only two values
If (info. dwplatformid = ver_platform_win32_windows)
{// On Windows 95
M_cx = getsystemmetrics (sm_cxfixedframe );
M_cy = getsystemmetrics (sm_cyfixedframe );
}
Else
{// On NT
M_cx = getsystemmetrics (sm_cxdlgframe );
M_cy = getsystemmetrics (sm_cydlgframe );
}
}
}

Note:
1) The wm_activate message does not exist in classwizard. Add the message as follows, right-click the cmydlg class, and select add windows
Message handle, and then select Window in filter for messages available to, in new windows
Wm_activate will appear in the messages/events list. Select and click Add handler.
2) sm_cxdlgframe, sm_cydlgframe NT has been discarded in the 95th (WXH) and 95th (WXH) windows with ws_dlgframestyle. sm_cx_fixedframe and sm_cyfixedframe are used.

44. initialize the application size

If you want the application interface (document) to be displayed on the screen at the start of running,
Add the following code:
Bool cmainframe: precreatewindow (createstruct & CS)
{
Int xsize =: getsystemmetrics (sm_cxscreen );
Int ysize =: getsystemmetrics (sm_cyscreen );
CS. Cx = x size * 5/10;
CS. Cy = ysize * 5/10;
CS. x = (xsize-cs.cx)/2;
CS. Y = (ysize-cs.cy)/2;

}
5/10 is the percentage of your initial interface on the screen. You can modify it by yourself. If you want to fix the application size, add CS. Style & = ~ Ws_thickframe;

45. How to get the view pointer?

[Question]
Now you have a multi-threaded demo. If you want to process the function in the view pointer in multiple threads, let's name this function: Put (); how should we implement it?
// There are two ways to meet your requirements:
// 1) Method 1:
// If multithreading does not appear in APP. cpp, add extern cyourapp theapp to multithreading. cpp;
// Obtain the document template:
Position curtemplatepos = theapp. getfirstdoctemplateposition ();
Cdoctemplate * m_doc = theapp. getnextdoctemplate (curtemplatepos );

// Obtain the document:
Curtemplatepos = m_doc-> getfirstdocposition ();
Cyourdoc * m_pdoc = (ca8doc *) m_doc-> getnextdoc (curtemplatepos );
 
// Obtain the View:
Curtemplatepos = m_pdoc-> getfirstviewposition ();
Cyourview * m_pview = (cyourview *) m_pdoc-> getnextview (curtemplatepos );

// Call the view function:
M_pview-> put ();

// 2) Method 2:
// Obtain the form pointer:
Cmainframe * pframe = (cmainframe *) afxgetapp ()-> m_pmainwnd;

// Obtain the view that matches the form:
Cyourview * m_pview = (cyourview *) pframe-> getactiveview ();

// Call the view function:
M_pview-> put ();

46. How can I prevent my program from creating a new document at startup?

[Problem]
How can I prevent my program from creating a new document at startup?
[Answer]
Before the processshellcommand function in the initinstance of the program, add: cmdinfo. m_nshellcommand = ccommandlineinfo: filenothing.

47. How can I shield the right-click menu on the title bar?

[Solution]
Right-click the system menu and remove the ws_sysmenu attribute.
[Program Implementation]
Int cmainframe: oncreate (maid)
{
........
Long style = getwindowlong (m_hwnd, gwl_style );
Style & = ~ Ws_sysmenu;
Setwindowlong (m_hwnd, gwl_style, style );

Return 0;
}

48. How to display in full screen (no title, no menu, no toolbar)

[Solution]
The activateframe function of cmainframe is reloaded:
Void cmainframe: activateframe (INT ncmdshow)
{
Crect crectdesktop;
Windowplacement;
: Getwindowrect (: getwindowtopwindow (), & crectdesktop );
: Adjustwindowrectex (& crectdesktop, getstyle (), true, getexstyle ());
Windowplacement. rcnormalposition = crectdesktop;
Windowplacement. showcmd = sw_shownormal;
Setwindowplacement (& windowplacement );

Cframewnd: activateframe (ncmdshow );
}

49. How to set text with background color

(1) [solution]
CDC: setbkmode ();
 
[Program Implementation]
Void cmyview: ondraw (CDC * PDC)
{
Cmydoc * pdoc = getdocument ();
Assert_valid (pdoc );
Crect rcview; // Add these two sentences
Getclientrect (rcview );
// Todo: Add draw code for native data here
Cstring STR (_ T ("perfect text ..."));
PDC-> setbkmode (transparent );
Rcview. offsetrect (1, 1 );
PDC-> settextcolor (RGB (0, 0, 0 ));
PDC-> drawtext (STR, str. getlength (), rcview, dt_singleline | dt_center | dt_vcenter );
Rcview. offsetrect (-1,-1 );
PDC-> settextcolor (RGB (255, 0, 0 ));
PDC-> drawtext (STR, str. getlength (), rcview, dt_singleline | dt_center | dt_vcenter );
}
(2) create an SDI or MDI named my and respond to wm_erasebkgnd.
Bool cmyview: onerasebkgnd (CDC * PDC)
{
// Todo: add your message handler code here and/or call default
Cbrush brush (RGB (114,147,171 ));
// Select the brush into the device context.
Cbrush * poldbrush = PDC-> SelectObject (& brush );
// Get the area that needs to be erased.
Crect viewclip;
PDC-> getclipbox (& viewclip );
// Paint the area.
PDC-> patblt (viewclip. Left, viewclip. Top, viewclip. Width (), viewclip. Height (), patcopy );
// Unselect brush out of device context.
PDC-> SelectObject (poldbrush );
// Return nonzero to half fruther processing.

Return true;
Return cview: onerasebkgnd (PDC );
}
This method is also applicable when the base class is editview SDI or MDI, but the font color and background color are not good. We recommend that you use wm_ctlcolor.

50. If the string is too long, display a ellipsis (in the SDI or MDI view) at the end of it)

[Question]
How can I display a ellipsis (in the SDI or MDI view) at the end of a string when it is too long )?
[Program Implementation]
Create an SDI or MDI project named my.
Void cmyview: ondraw (CDC * PDC)
{
Cmydoc * pdoc = getdocument ();
Assert_valid (pdoc );
// Todo: Add draw code for native data here
PDC-> drawtext (cstring ("it's a long string, so we will add '...'
At the end. "), crect (110,110,180,130), dt_left | dt_end_ellipsis );
// Add ellpsis to middle of string if it does not fit
PDC-> drawtext (cstring ("it's a long string, so we will add '...'
At the end. "), crect (110,140,300,160), dt_left | dt_path_ellipsis );
}

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.