(1) How to get the pointer of the application main window through the code? The pointer of the main window is saved in CwinThread :: m_pmainwnd, call the AFXGETMAINWND implementation. AfxgetMainWnd () -> showwindow (sw_showmaxmize) // maximizes the program.
(2) Determine the path of the application USE getModuleFileName to get the path to the application, then remove the executable file name. Example: tchares // max_path is defined in the API, as if it is 128GetModuleFileName (null, exefullpath, max_path)
(3) How to get an icon for other programs in the program? Two methods: (1) SDK function SHGETFILEINFO or use Extractic to get the Handle of the icon resource, (2) SDK functions SHGETFILEINFO Get a lot of information about files, such as size icons, properties , Type, etc.Example (1): Display the NotePad icon in the upper left corner of the program window .void csampleview: onDraw (CDC * PDC) {if (: shGetfileinfo (_t ("c: //pwin95/notepad.exe"), 0, & stfileinfo, sizeof (stfileinfo), shgfi_icon) {PDC -> Drawicon (10, 10, stfileinfo.hicon)}} EXAMPLE (2): The same function, Use Extracticon Functionvoid CsampleView :: Ondraw (CDC * PDC) {Hicon Hicon = :: Extracticon (AFXGetInstanceHandle (), _ T ("NOTEPAD.EXE"), 0) IF (HiCon && HiCon! = (Hicon) -1) PDC-> Drawicon (10, 10, hicon)} Description: Get NotePad. The path to the EXE is in normal ways with the getWindowsDirectory function. If it is a brush to call Win95, you should use the way to access the registry to get its path. To make a more elegant program, consider should comprehensively.
(4) Get various directory information Windows directory: Use "getWindowsDirectory" System directory under Windows: Use "getTemDirectory" Temp Directory: Use "getTemppath" Current Directory: Use "getcurrentdirectory" Please note the first parameters of the first two functions For the directory variable name, the latter is reversed to the buffer.
(5) How to customize the message 1) Manually define the message, can you write #define WM_MY_MESSAGE (WM_USER 100), the MS recommended at least WM_USER 100 (2) Write message processing function, use wparam, LPARAM Return LRESULT.LRESULT CMAINFRAME :: ONMYMESSAGE (WPARAM WPARAM, LPARAM LPARAM) {Temp Directory: Use "getTemppath" // Add your handler IRECTORY "}
(6) How to change the icon of the window? Send a WM_SECTION message to the window. Example: Hicon Hicon = AFXGetApp () -> Loadicon (idi_icon) Assert (HICON) AFXGETMAINWND () -> SendMessage (WM_SECTION, TRUE, (LPARAM) HICON)
? (7) How to change the default window style overloaded CWnd :: PreCreateWindow and modify CREATESTRUCT structure to specify the window style and other information to create .Example: Delete "Max" Button and Set OriginalWindow's Position and SizeBOOL CMainFrame :: PreCreateWindow (CREATESTRUCT & cs ) {cs.style & = ~ WS_MAXINIZEMOXcs.x = cs.y = 0cs.cx = GetSystemMetrics (SM_CXSCREEN / 2) cs.cy = GetSystemMetrics (SM_CYSCREEN / 2) return CMDIFramewnd :: PreCreateWindow (cs)} (8)
How to display the window in the window?
Call function CWnd ::
Center Windows
EXAMPLE (1):
Center window () // relative to it's parent
// Relative
TO Screen
EXAMPLE (2):
Center window (CWnd :: getDesktopWindow ())
// relative to
Application's mainwindow
AFXGETMAINWND () ->
Center window ()
(9) How to maximize and minimize windows and MDI windows? Let's talk about the window. M_nCmdShow set in InitStance function values .m_nCmdShow = SW_SHOWMAXMIZED // maximize m_nCmdShow = SW_SHOWMINMIZED // minimize m_nCmdShow = SW_SHOWNORMAL // normal mode MDI window: If you are creating a new application, you can use the Advanced button in MFC AppWizard And to detect or minimize the MDI Sub-window style group, you can also overload the MDI WINDOW PRECREATEWINDOW function, set WS_MAXMIZE or WS_MINMIZE if you are derived from cmdichildwnd, call the CWnd :: Show Window in the OnInitialUpdate function from cmdichildwnd, specify the style of MDI Child Window
(11) How to make the window are invisible? Very simple, hidden with SW_HIDE, you can combine FindWindow, ShowWindow control.
(12) How to create a word rounded CEDITVIEW Rebond :: PrecreateWindow and modify the CreateStruct structure, close the ES_AUTOHSCROLL and WS_AUTOHSCROLL and WS_HSCROLL style bits of the CEDITVIEW object, due to the CEDITVIEW:: PrecreateWindow display settings CS. Style, call the base class function to modify the CS after calling the base class function STYLE. BOOL CSampleEDitView:: PreCreateWindow (CREATESTRUCT & cs) {// First call basse class function .BOOL bResutl = CEditView:: PreCreateWindow (cs) // Now specify the new window style .cs.style & = ~ (ES_AUTOHSCROLL | WS_HSCROLL) return bResult}
(13) How to keep the program so small? Do this: When the recovery program form is large, Windows will send a WM_QUERY-OPEN message, set the member function with ClassWizard ONQUERYOPEN () () (), add following code: Bool CMAINFRAME :: ONQUERYOPEN () {RETURN FALSE} (14) Mobile window calls CWnd:: setWindowPOS and specify the SWP_NOSIZE flag. The purpose location is related to the parent window (the top window is related to the screen). Call CWnd:: MoveWindow must specify the size of the window. //Move Window to Positoin 100, 100 of Its Parent Window .SetWindowPos (NULL, 100, 100, 0, 0, SWP_NOSize | SWP_NOAORDER)
(15) Display window MFC provides several CView derived window classes, encapsulating the functionality of the general control, but still uses a workfall document display window architecture: CeditView encapsulates the editing control, CTREEVIEW keeps tree list controls, ClistView encapsulates a list display window control, CRICHEDITVIEW can handle multiple editing controls.
(16) Reset the size of the window CWnd:: setWindowPOS and specify the SWP_Nomove flag, or call CWnd:: MoveWindow but must specify the location of the window. // get the size of the window .cRect RewindowGetWindower (ReWindow) // make the window Tower as Wide and Twice as Tall .SetWindowPos (NULL, 0, 0, REWINDOW. Width () * 2, Rewindow. Height () * 2 , SWP_NOMOVE | SWP_NOZORDER)
(17) How to click the area other than the window title bar allows the window to move when the window needs to determine the mouse position, Windows sends WM_NCHITTEST information to the window, which can handle Windows to consider the mouse on the window title. For dialogs and dialog-based applications, you can use ClassWizard to process this information and call the base class function. If the function returns htclient, the mouse is in the room area, returning to HTCAPTION indicates that the mouse is in the title bar of the Windows. Uint Csampledialog:: onnchittest (cpoint point) {uint nhittest = cdialog:: onnchittest (point) Return (nhittest = = htclient)? HTCAPTION: NHITTEST} The above technology has two unfavorable points, one is to double click on the window of the window. When the window will be extremely; it is not suitable for the main frame window of several windows. There is also a method, when the user presses the left mouse button to consider the mouse on its window title, use ClassWizard to handle WM_LBUTTODOWN information in the window and send a WM_NCLBUTTONDOWN information to the main box window and a click to test HTCAption. void CSampleView:: OnLButtonDown (UINT nFlags, Cpoint point) {CView:: OnLButtonDow (nFlags, pont) // Fool frame window into thinking somene clickedonits caption bar .GetParentFrame () -> PostMessage (WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM (poitn .x Point .y)} This technology also applies to dialogs and pair-based applications, just do not have to call CWnd:: getParentFrame. void CSampleDialog:: OnLbuttonDown (UINT nFlags, Cpoint point) {Cdialog::. OnLButtonDow (nFlags, goint) // Fool dialog into thinking simeone clicked on itscaption bar .PostMessage (WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARM (point.x, point y) }
(18) How to change the background color of the window to send a WM_ERASEBKGND message to the window to inform the window erase background, you can use ClassWizard to overload the default handler of the message to erase the background (actually painting) and return True to prevent Windows erase window. // Paint area truempleview:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :::: CBrush * pOldBrush = pDC-> SelcetObject (& brush) // Get the area that needs to be erased .CRect reClippDC-> GetCilpBox (& rcClip) // Paint the area.pDC-> PatBlt (rcClip.left, rcClip.top, rcClip .Width (), rcclip.height (), patcopy) // unselect brush out of device context .pdc-> selectobject (Poldbrush) // Return Nonzero to half fruther processing .Return true}
(19) How to change the window title call CWnd:: SETWINDOWText can change any window (including controls). // Set title for application's main frame window .AfxGetMainWnd () -> SetWindowText (_T ( "Application title")) // Set title for View's MDI child frame window .GetParentFrame () -> SetWindowText ( "_T (" MDI Child Frame New title ")) // set title for Dialog's Push Button Control.getdigItem (IDC_Button) -> SetWindowText (_T (" Button New Title ")) If you need to modify the title of the window (Note: Control is also a window), you should consider use Half-text filematics AFXSetWindowText. This function is described in AfxPriv.h, implemented in Winutil.cpp, can't find it in online help, it is in the middle half of AFXPriv.h, in the future MFC, the documentation .AfxSetWindowText realization of the following: voik AFXAPI AfxSetWindowText (HWND hWndCtrl, LPCTSTR IpszNew) {itn nNewLen = Istrlen (Ipaznew) TCHAR szOld [256] // fast check to see if text really changes (reducesflash in thecontrols) if (nNewLen> _contof (Szold) ||:: getWindowText (hwndcrtl, szold, _countof (szold)! = nnewlen || istrcmp (szold, ipsznew)! = 0 {// change it:: setWindowText (hwndctrl, ipsznew)}} (20) Prevent the main box window from displaying the active document name in its description Creating the main box window and the MDI sub-window to usually have a fws_addtotitle-style bit, if you do not want to automatically add a document name in the description, you must ban the style, you can use ClassWizard reset CWnd :: PrecreateWindow and close FWS_ADDTOTO ITLE style. BOOL CMainFrame:: PreCreateWindow (CREATESTRUCT & cs) {// Turn off FWS_ADDTOTITLE in main frame .cs.styel & = ~ FWS_ADDTOTITLE return CMDIFrameWnd:: PreCreateWindow (cs)} Close MDI child window FWS _ADDTOTITLE style window having a title to create empty You can call CWnd:: setWindowText to set the title. Remember to set the title guide when you set your title.
(21) How to get information about the current message on the window is processing CWnd:: getCurrentMessage can get an MSG pointer. For example, you can use ClassWizard to map several menu items to a function, then call GetCurrentMessage to determine the selected menu item. VIOD CMAINFRAME:: OnCommonMenuHandler () {// Display Selected Menu Item in Debug WINDOW .TRACE ("Menu Item% U WAS SELECTED. / N", (22) How to get the pointer to the toolbar and status bar in the code When the workflock creates status strips and tools, they use an AFX_IDW_STATUS_BAR identifier when the status bar is available. The toolbar has an AFX_IDW_TOOLBAR identifier. The following example describes how to call CWnd:: getDescendantWindow and AFXGETMAINWND to get a pointer to the sub-windows: // 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)
(23) How to enable and prohibit the toolbar Tips If you set the CBRS_ToolTips style bit, the toolbar will display the tooltip, to enable or disable the tooltip, you need to set or clear the style. The following example by calling CControlBar:: GetBarStyle and CControlBar:: SetBarStyle member function to establish a complete this function: void CMainFrame:: EnableToolTips (BOOL bDisplayTips) {ASSERT_VALID (m_wndToolBar) DWORD dwStyle = m _wndToolBar.GetBarStyle () if (bDisplayTips) dwStyle | = CBRS_TooltipselsedWStyle & = ~ CBRS_Tooltipsm_WndtoolBar.SetbarsTyle (DWStyle)}
(24) How to create an irregular shape window can use the new SDK function setWindowRGN. This function defines the drawing and mouse message to a specified area of the window, in fact, enables the window to be a specified irregular shape. Create a pair-based application with AppWizard and use the Resource Editor to remove the default controls, titles, and boundaries of the default controls, titles, and boundaries. Add a CRGN data member to the dialogue, and then use the data member to establish a window area. Class CRoundDlg: public CDialog {... private: Crgn m_rgn: // window region ...} OnInitDialog function creates a modified elliptical area and call SetWindowRgn allocations of the window: BOOL CRoundDlg:: OnInitDialog () {CDialog:: OnInitDialog () / / Get size of dialog .CRect rcDialogGetClientRect (rcDialog) // Create region and assign to window .m_rgn. CreateEllipticRgn (0, 0, rcDialog.Width (), rcDialog.Height ()) SetWindowRgn (GetSafeHwnd (), (HRGN) m_ RGN, TRUE) RETURN TRUE} The window of an irregular shape has been established by establishing a region and calling setWindowRGN. The following example is a modified ONPAINT function to make the window shape look like a sphere.
voik CRoundDlg:: OnPaint () {CPaintDC de (this) // device context for painting.//draw ellipse with out any borderdc SelecStockObject (NULL_PEN) // get the RGB colour components of the sphere colorCOLORREF color = RGB (0,. 0, 255) BYTE byRed = GetRValue (color) BYTE byGreen = GetGValue (color) BYTE byBlue = GetBValue (color) // get the size of the view windowCrect rectGetClientRect (rect) // get minimun number of unitsint nUnits = min (rect .right, rect.bottom) // calculate he horiaontal and vertical step sizefloat fltStepHorz = (float) rect.right / nUnitsfloat fltStepVert = (float) rect.bottom / nUnitsint nEllipse = nUnits / 3 // calculate how many todrawint nIndex // current ellipse that is being drawCBrush brush // bursh used for ellipse fill colorCBrush * pBrushOld // previousbrush that was selected into dc // draw ellipse, gradually moving towards upper-rightcornerfor (nIndex = 0 nIndes < nEllipse nIndes ) {// creat Solid Brushbrush. CreatSolidbrush (RGB ((Nindex * Byred) / Nellipse. ((Nind ex * byGreen) / nEllipse), ((nIndex * byBlue) / nEllipse))) // select brush into dcpBrushOld = dc .SelectObject (& brhsh) // draw ellipsedc .Ellipse ((int) fltStepHorz * 2, (int) fltStepVert * Nindex, Rect. Right - (int) Fltstephaz * Nindex) 1, Rect. Bottom - (INT) FltStepvert * (Nindex * 2)) 1) // delete the brushbrush.deelecteObject ()} Last, Process the WM_NCHITTEST message to move the window when you hit the window. UINT CRoundDlg:: OnNchitTest (Cpoint point) {// Let user move window by clickign anywhere on thewindow .UINT nHitTest = CDialog::? OnNcHitTest (point) rerurn (nHitTest = = HTCLIENT) HTCAPTION: nHitTest}
(25) How do I get an instance handle of the application? The instance handle of the application is saved in CWINAPP M_HINSTANCE, which can call the AFXGetInstancDHandle to get the handle .example: handle hinstance = AFXGETITINSTANCEHANDLE = AFXGETInstanceHandle () (26) How to program the application? This is a very simple It is also the problem that is often encountered in the program. Send a WM_CLOSE message to the window, call the CWnd :: ONCLOSE member function. Allow the user to prompt whether the modified data is saved .Example: AFXGETMAINWINDOW () -> sendMessage (wm_close) can also be created A custom function Terminate Windowvoid Terminate WINDOW (LPCSTR PCAPTION) {CWND * PWND = CWnd :: FindWindow (Null, PCAPTION) IF (PWND) PWnd -> SendMessage (wm_close)}: The FindWindow function is not advocated, because it Unable to handle the title bar automatically change, such as we have to detect notepad is not running, do not know the title bar of NOTEPAD in advance, and FindWindow can be implemented by enumerating the WINDOWS task list. In the Mechanical Press, "Windows 95 API Developer Guide" has a more detailed introduction, this is no longer speaking.
(27) How to create and use the Modeless dialog box MFC to encapsulate the mode and no mode dialog in the same class, but several dialogging requires several balances that require several dialogies. First, use the resource editor to establish a dialogue and create a CDIALOG derived class using ClassWizard. Mode and non-mode dialogue is different: Mode dialog is aborted by calling cdialog:: enddialog, and no mode dialog is called CWnd:: destroyWindow Surperse, function cdialog:: onok and cdialog:: oncancel call EndDialog, So you need to call DESTROYWINDOW and reset the function of the modified dialog. void CSampleDialog:: OnOK () {// Retrieve and validate dialog data .if (! UpdateData (TRUE)) {// the UpdateData rountinewill 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, the C object indicating the conversation is required to properly delete. For mode pair, this is easy, you need to create a function to return to the C object; no mode dialog is not synchronized, then return to the function call, so the user does not know when to delete the C object. Workframe call CWnd: postncdestroy when the window is revoked: postncdestroy can reset the function and perform a clear operation, such as deleting the THIS pointer. Void csampledialog:: postncdestroy () {// Declete The C Object That Repesents this Dialog.delete this Finally, you want to create a modeless dialog. You can call CDIALOG:: Domodal Create a mode alignment, to create a non-mode dialog, call CDIALOG:: CREATE. The following example illustrates how the application creates a modeless conversation: icon; no mode dialogue is not synchronized, return immediately after creating a function call, void cmainframe:: onsampledialog () {// allocate a modeless Dialog Object .csampledilog * PDIALOG = New csampledialogassert_valid (pdialog) destroy () // Create The mode Dialog. Represents this dialog.Bool Bresult = PDIALOG -> Creste (IDD_IDALOG) Assert (BRESULT)}
(28) How to prevent the main box window from displaying the active document name in its description Creating the main box window and the MDI sub-window to usually have a fws_addtotitle-style bit, if you do not want to automatically add a document name in the description, you must ban the style, you can Use ClassWizard to reset CWnd:: PrecreateWindow and close the fws_addtotitle style. BOOL CMainFrame:: PreCreateWindow (CREATESTRUCT & cs) {// Turn off FWS_ADDTOTITLE in main frame .cs.styel & = ~ FWS_ADDTOTITLE return CMDIFrameWnd:: PreCreateWindow (cs)} Close MDI child window FWS _ADDTOTITLE style window having a title to create empty You can call CWnd:: setWindowText to set the title. Remember to set the title guide when you set your title. (29) How to get the pointer to the toolbar and status strip in the code, when the workflock creates a status bar and the toolbar, the sub-window of the mainframe window, the status bar has an AFX_IDW_STATUS_BAR identifier, the toolbar has one AFX_IDW_TOOLBAR identifier, the following example illustrates how to call CWnd together:: acquiring GetDescendantWindow and these sub-window pointer AfxGetMainWnd: // 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)
(30) How to load other applications? Three SDK functions WINEXEC, Shellexecute, CreateProcess can be used. Winexec is the simplest, two parameters, the previous specified path, the latter specified display mode. The latter parameter is worth mentioning, such as the mud with sw_showmaxmized mode to load a program without maximizing the button, it is NETERM, CALC, etc. There will be a normal form, but it has been added to the task list. Shellexecute is flexible than Winexex, you can specify a work directory, the following example is to open C: /TEMP/1.txt, without loading an application associated with TXT files, many installations will open a window after completion, to display readme OR FAQ, I guess it is this. SHELLEXECUTE (NULL, NULL, _T ("1.txt"), NULL, _T ("C: // Temp"), sw_showmaxmized) CreateProcess is the most complicated, a total of ten parameters However, most of them can be replaced with null, which can specify the security attributes of the process, inherit information, priority of the class, and more. Let's see a very simple EXAMPLE: StartupInfo Stinfo // Start window information ProcessInfo procinfo // process Information CreateProcess (NULL, _T ("NOTEPAD.EXE"), NULL, NULL.FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, & Stinfo, & Procinfo)
(31) How to get a pointer to the toolbar and status strip in the code, when the workflock creates a status strip and toolbar, the sub-window of the main box window, the status bar has an AFX_IDW_STATUS_BAR identifier, the toolbar has one AFX_IDW_TOOLBAR identifier, the following example illustrates how to call CWnd together:: acquiring GetDescendantWindow and these sub-window pointer AfxGetMainWnd: // Get pointer to status bar .CStatusBar * pStatusBar = (CStatusBar *) AfxGetMainWnd () -> GetDescendantWindow (AFX_IDW_STUTUS_BAR (32) How to enable and prohibit the toolbar, if the CBRS_Tooltips style bit is set, the toolbar will display the tooltip, to enable or disable the tooltip, you need to set or clear the style. The following example by calling CControlBar:: GetBarStyle and CControlBar:: SetBarStyle member function to establish a complete this function: void CMainFrame:: EnableToolTips (BOOL bDisplayTips) {ASSERT_VALID (m_wndToolBar) DWORD dwStyle = m _wndToolBar.GetBarStyle () if (bDisplayTips) dwStyle | = CBRS_TOOLTIPSelsedwStyle & = ~ CBRS_TOOLTIPSm_wndToolBar.SetBarStyle (dwStyle)} // Get pointer to toolbar .CToolBar * pToolBar = (CToolBar *) AfxGetMainWnd () -> GetDescendantWindow (AFX_IDW_TOOLBAR)
(33) How to set the toolbar title tool strip is a window, so you can set the title in calling CWnd:: setWindowText, as follows: int CMAINFRAME:: oncreate (lpcreatestruct lpcreatestruct) {... // set the caption of the toolbar .m_wndtoolbar .SetWindowText (_T "standdard")
(34) How to keep the window in the forehead? BringWindowTotop (Handle) SetwindowPos function, the top style of the specified window, using the WS_EX_TOPMOST Extended Window Style EXAMPLE: Void Toggletopmost (CWND * PWND) {Assert_Valid (PWND) PWND -> SetWindowPOS PWND-> getStyle () & WS_EX_TOPMOST? & WNDNOTOPMOST: & WNDTOPMOST, 0, 0, 0, 0, SSP_NOSIZE | WSP_NOMOVE)}
(35) How to display a bitmap in the dialog This is to be attributed to Win 32 Advanced Static Controls and Microsoft Resources Editor, which is easy to display bitmaps in the dialog, just drag the graphic control to the conversation. And select the appropriate properties, the user can display icons, bitmaps, and enhanced metad files.
(36) How to change the background color of the conversation or form window CWINAPP:: setDialogbkcolor can change the background color of all applications. The first parameter specifies the background color, and the second parameter specifies the text color. The following example sets the application dialog to a blue background and yellow text. Bool csampleapp:: initInstance () {... // use blue dialog with Yellow text .SetDialogbkcolor (RGB (0, 0, 255), RGB (255, 255, 0)) ...} Need to Heavy Picture (Or Sub-control) When Windows sends a message WM_CTLCOLOR to a dialog, usually the user can make Windows select the brush of the painting background, or reset the message to specify the brush. The following example shows the steps to create a red background dialog. First, add one-person member variable for the dialogue class CBursh: Class CMYFORMVIEW: PUBLIC CFORMVIEW {... private: CBRUSH M_ Brush // Background Brush ...} This is followed, and the brush is initialized to the desired background color in the class constructor. CMYFORMVIEW:: CMYFORMVIEW () {// Initialize Background Brush .m_brush .createsolidbrush (RGB (0, 0, 255))} Finally, using ClassWizard to process the WM_CTLCOLOR message and return a brush handle for painting dialogue background. Note: This function is to be called because it is also called the dialog control, so it is necessary to detect NCTLCOLOR parameters. HBRUSH CMyFormView:: OnCtlColor (CDC * pDC, CWnd * pWnd, UINT nCtlColor) {// Determine if drawing a dialog box If we are, return handle to // our own background brush Otherwise let windows handle it .if (.. Nctlcolor = = CTLCOLOR _ DLG) Return (HBrush) m_brush.getsafehandle () Return CFormview:: OnctLcolor (PDC, PWND, NCTLCOLOR)} (37) How to get a pointer to a dialog control has two methods. First, call CWnd:: getdlgitem, get a CWND * pointer call member function. The following example call GetDlgItem, the return value is passed to call a CSpinButtonCtrl * CSpinButtonCtrl:: SetPos function: BOOL CSampleDialog:: OnInitDialog () {CDialog:: OnInitDialog () // Get pointer to spin button .CSpinButtonCtrl * pSpin - (CSpinButtonCtrl * ) Getdlgitem (idc_spin) assert _ value default position .pspin -> setpos (10) Return True} It can use ClassWizard to link controls and member variables. Simply select the MEMBER VARIABLES tab in ClassWizard and select the Add Variable ... button. If you press the CTRL key and double-click the control in the dialog resource editor and you can go to the Add Member Variable conversation.
(38) How to prohibit and enable control controls is also a window, so you can call CWnd:: EnableWindow enable and disable controls. // disable button controls .m_wndok.enableWindow (false) m_wndapply.enableWindow (59) How to change the control of the control Since the control is also a window, the user can call CWnd:: setFont Specify new fonts. This function uses a CFont pointer to ensure that the font object cannot be revoked before the control is canceled. The following example change the font of the lower pressure button to 8 points 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 A // member variable added by ClassWizard.DDX routines hook the member // variable to a dialog button contrlo.BOOL CSampleDialog:: OnInitDialog () {... // Create an 8-point Arial fontm_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 _QUALITYVARIABLE_PITCH |. FF_SWISS, _T ( "Arial")) // Set font for push button. M_WndButton. setfont (& m _font) ...}
(40) How to use OLE_COLOR data types such as ColeControl:: GetforTColor and ColeControl: GetBackColor, etc. in OLE controls, while GDI objects such as pen and brushes are used by ColorRef data types, calling Colecontrol::: TranslateColor can easily change the OLE_COLOR type to the ColorRef type. The following example creates a current background color brush: void CSampleControl:: OnDraw (CDC * pdcconst Crect & rcBounds, const Crect & rcInvalid) {// Create a brush of the cuttent background color.CBrush brushBack (TranslateColor (GetBackColor ())) / / Paint The Background Using The Current BackgroundColor .pdc-> FillLRect (RcBounds, & Brushback) // Other Drawign Commands ...}
(41) How to display a file list in the case of opening a dialog:: DLGDIRLIST or CWND:: DLGDIRLISTCOMBOX:: DLGDIRLISTCOMBOX:: DLGDIRLISTCOMBOX: DLGDIRLISTCOMBOX: DLGDIRLISTCOMBOX, Windows will automatically populate the file name or specified directory to the list box or combo box Next example populates files in the Windows directory in the combo box: BOOL CSAMPLEDIG:: OnNInitDialog () {cdialog:: onInitdialog () tchar szpath [max_path] = {"c: // windows"} int Nreslt = DLGDIRLISTCOMBOX (Szpath , IDC_COMBO, IDC_CURIDIR, DDL_READWRITE | DDL_READONLY | DDL_HIDDEN | DDL_SYSTEM | DDL_ARCHIVE) return TRUE} (42) Why spin button control appears to reverse the need to call CSpinCtrl:: SetRange setting range spin button control, the default upper limit is zero spin button control The lower limit of the default is 100, which means that the value of rotation according to the control is generated from 0 when it increases. The following example sets the range of rotation button controls to 0 to 100: bool caboutdlg:: oninitdialog () {cdialog:: oninitdialog () // set the Lower and Upper limit of the spin buttonm_wndspin. Set runm_wndspin. SetRange (0, 100) Return True} The COPISE rotation button control in the Visual C 4.0 PRINT dialog is also the same problem: the number of copies when the UP button is pressed, and the number of copies when the DOWN button is pressed.
(43) Why rotating button controls cannot automatically update the following editing controls If the autu buddy feature of the rotation button, the Buddy window must be guaranteed to take precedence over the rotation button control in the marking order of the conversation. Select Tab ORDER menu items from the Layout menu (or press CRTL D) to set the tag order of the dialog.
(44) How to display the downstream button Windows 95 buttons with a new creation style, especially BS_bitmap, and BS_ICON, want to have a bitmap button, create buttons, and call CButton:: setBitmap or CButton:: Seticon Specify the BS_bitmap or BS_ICON style. First, set the icon properties of the button. Then, call CButton when the dialog is initialized:: Seticon. Note: The next example uses icons to replace the bitmap. Be careful when using a bitmap, because you don't know all colors - not everyone uses light gray. BOOL CSampleDlg:: OnInitDialog () {CDialog:: OnInitDialog () // set the images for the push buttons .BOOL CSampleDlg:: OnInitDialog () {CDialog:: OnInitDialog () // set the images for the push buttons .m_wndButton1. Seticon (AFXGetApp () -> LoadCon (iPtion1)) m_wndbutton2.seticon (AFXGetApp () -> Loadicon (IPTION2)) m_wndbutton3.seticon (AFXGetApp () -> Loadicon (iPtion3)) Return True} ( 45) How to create a three-state lower pressure button can create a three-state lower pressure button using the new BS_PushButton style bit and detection box and buttons. This is easy, just drag the detection box and buttons to the dialog and specify the property push-like. You can become a three-state lower pressure button without any additional programs.
(46) How to dynamically create a control allocated an instance of a control object and call its CREATE member function. Developers easily ignore two things: Forget to specify the WS_VISBLE tag and assign control objects in the stack. The following example dynamically creates a down voltage button control: // in class declaration (.h file) .private: cbutton * m _pButton // in class.m_pbutton = new cbuttonassert_valid (m_pbutton) m_pbutton -> Create (_T ("Button Title"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON. CRECT (0, 0, 100, 24), This, IDC_Mybutton)
(47) How to limit the graphics in the edit box If the user only allows the number to receive numbers in the editing control, you can use a standard editing control and specify a new creation flag ES_NUMBERS, which is a newly added flag of Windows 95, which restricts editing The control is only collected by the column. If the user needs a complex editing control, you can use Microsoft's mask editing control, which is a very useful OLE custom control. If you want to use the OLE custom control to handle the character, you can derive a CEDIT class and process the WM_CHAR message, and then filter out specific characters from the editing control. First, create a CEDIT derive class using ClassWizard, secondly, specifying a member variable in the dialogue class to call the editor control in the OnInitDialog 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) ...} process using ClassWizard WM_CHAR messages, calculate NCHAR parameters and decide the operation performed, and the user can determine whether to modify, transmit characters. The following example shows how to display alphabet characters, if the character is alphabetical character, call CWnd onchar, otherwise INCHAR.//only display alphabetic dharacters .void CMYDIT:: onchar (uint nchar, uint nrepcnt, uitn nflags) {// DETERMINE IF NCHAR IS An Alphabetic Character.if (: ischaralpha) nchar) CEDIT:: OnChar (nchar, nrepcnt, nflags)} If you want to modify the character, you cannot simply use the modified NCHAR call CEDIT: : OnChar, then CEDIT:: OnChar call CWnd:: Default Gets the value of the original WPARAM and LPARAM, which is not. To modify a character, you need to modify NCHAR first, then call CWnd:: DefWindowProc with modified NCHAR. The following example shows how to transform characters to uppercase: // Make All Characters Uppercasevoid CMYEDIT:: OnChar (uint nchar, uint nrepcnt, uint nflags) {// make sure character is Uppercase .if (:: ischaralpha)) Nchar =:: charupper (nchar) // bypass default onchar processing and directly call // default window proc.defwindproc (WM_CHAR, NCHAR, MAKELPARAM (NREPCNT, NFLAGS))}
(48) How to change the color of the control has two methods. First, you can specify the color of the control in the parent class, or use the MFC4.0 new message to specify the color in the control class. When the control needs to be reatched, the Workflow calls the parent window (usually the dialog) CWnd:: OnCrtLColor, you can reset the function in the parent window class and specify the new painting properties of the control. For example, the following code is changed to 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 each The painting attribute of the control, so this method is not a completely object-oriented method. The control handles the message and specifies that the painting attribute is more reasonable. Message reflections allow users to do so. The notification message is first sent to the parent window, and if the parent window is not processed, it is sent to the control. Creating a custom color list box control must follow the steps below. First, create a CLISTBOX derived class using ClassWizard and add the following data to this class. Class Cmylistbox Publilc ClistBox {... privatecolorRef m_clrfor // Foreground ColorColorRef m_clrback // background colorcbrush m_brush // background brush ...} This is followed, in the constructor of the class, in the initialization data. CMyListBox:: CMyListBox () {. // Initialize data members .m_clrFore = RGB (255, 255, 0) // yellow textm_clrBack = RGB (0, 0, 255) // blue backgroundm_brush CreateSolidBrush (m _clrBack)} Finally, ClassWizard processes the reflected WM_CTLCOLOR message and specifies 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, controls can decide for themselves how to paint, and the parent window Not related.
(49) How to prevent flashing calls CWnd :: setRAW Clear Heavy Picture When adding multiple items to the list box, CLISTBOX is disabled. When you add a few items to the list box, the user can clear the heavy-in flag, then add the item, and finally restore the heavy painting flag. To ensure the new item of the redraw list box, call SetREDRAW (TRUE) to call CWnd :: Invalidate. // disable redrawing.plistbox-> setRAW (false) // Fill in the list box gere // enable drwing and make sure // enabledrawn.plistbox-> setredraw (true) PListbox-> Invalidate () (50) How to Add text to the editor control Since there is no CEDIT :: AppendText function, users have to do this work. Call CEDIT :: Setsel Move to the end of the edit control, then call Cedit :: ReplaceSel to add text. The following example is an implementation method of appendtext: void cmyedit :: appendtext (lpcstr ptext) {int Nlen = getWindowTextLength () setfocus () setsel (Nlen, Nlen) ReplaceSel (PTEXT)}
(51) How to access a predefined GDI object can use Windows's predefined objects by calling CDC :: SlectStockObject, such as a brush, pen, and font. The following example uses the Windows predefined pen and the brush GDI object to draw an ellipse in the window. // Draw ellipse using stock black pen and gray brush.void CSampleView :: OnDraw (CDC * pDC) {// Determine size of view.CRect rcViewGetClientRect (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 new SDK functions GetsysColorbrush Get a system color brush, the following example uses the background color in the window an ellipse: void CsampleView :: OnDraw (CDC * pDC) {// Determine size of view.CRect rcViewGetClientRect (rcView) // Use background color for tooltips brush.CBrush * pOrgBrush = pDC-> SelectObject (CBrush :: FromHandle (: : Getsyscolorbrush (color_infobk)) // Draw the elipse.pdc-> Ellipse (rcview) // restore original brush.pdc-> selectobject (porgbrush)}
(52) How to get the property information of the GDI object can call GDIOBJECT::: GetObject. This function writes the message of the specified chart device to the buffer. The following example creates several useful auxiliary functions. // Determine if font is bold.BOOL IsFontBold (const CFont & font) {LOGFONT stFontfont.GetObject (sizeof (LOGFONT), & stFont) return (stFont.lfBold) TRUE:? FALSE} // Return the size of a bitmap.CSize GetBitmapSize ( const CBitmap & bitmap) {BITMAP stBitmapbitmap.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 Stbrushbrush.GetObject (Sizeof (Logbrush), & Stbrush Return Pen. Createpen (ps_solid, 0, stbrush.ibcolor)}
(53) How to implement a rubber area rectangular CRECTRACKER is a useful class that can create a rectangle by calling CRECTRACKER :: TrackRubberband to respond to WM_LBUTTONDOWN messages. The following example shows that the size of the blue ellipse in the window using CRECTRACKER is easy. First, declare a data member in the file CRectTracker profile: class CSampleView: Public CView {... public: CrectTracker m_tracker ...} Secondly, in the constructor to initialize the object CRectTracker 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 rectangle OnDraw trace 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 rcEllipsepDoc-> 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 the ClassWizard to process the WM_LBUTTONDOWN message and add the following code. This section can drag and drop, move, or reset the size of the ellipse according to the mouse button. 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 a // 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)} elsepdoc-> m-tracker.trackrubberband (this, point, true) cview :: ONLBUTTONDOWN (NFLAGS, POINT)}
(54) How to update the text of the flip background color Call CDC :: SetBkmode and transfer Opaque with the current background color fill background, or call CDC :: setBkmode and transfer Transpaarent keep the background unchanged, both methods can set the background mode . The following example sets the background mode to transparent, you can update the string twice, with a black shadow to update the text with a flower color. The black string after the red string, but because the background mode is still visible. void CSampleView :: OnDraw (CDC * pDC) {// Determint size of view.CRect rcViewGetClientRect (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_SINGLINE | 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)} (55) How to create a font with a specific point size can specify the size of the font logic unit, but sometimes the size of the point of the specified font may be more convenient. You can convert the point of the font to the height of the font: int NHEIGTH = MULDIV (NpointSize, -dc.getDeviceCaps (Logpixelsy), 72) The following example creates an 8-point APIAL font: ... CclientDC DC (AQFXGetMainWnd ()) m_font. CreateFont (MulDiv (8, -dc.GetDeviceCaps (LOGPIXELSY), 72), 0, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, OUT_STROKE_PRECIS, CLIP_STROKE_PRECIS, DRAFT_QUALITY, VARIABLE_PITCH | FF-SWISS, _T ( "Arial" ))
(56) How to calculate a string of the size function CDC :: DET text extent calculates a string and calculates the height and width of a string according to the currently selected font. If not the system font but other font, it is important to select the font to select the device context before calling GetTexTextent, otherwise calculate the height and width, according to the system font, the result of this is of course incorrect. . The following sample program When changing the title of the lower pressure button, the size of the dynamic adjustment button is changed by the size of the button by the font and the size of the button. Turn ONSETTEXT when responding to WM_SETTEXT, which uses the user-defined message defined by the ON_MESSAE macro. LRESULT CMyButton :: OnSettext (WPARAM wParam, LPARAM lParam) {// Pass message to window procedure.LRESULT bResult = CallWindowProc (* GetSuperWndProcAddr (), m_hWnd, GetCurrentMessage () -> message, wParam, lParam) // Get title of push button.CString strTitleGetWindowText (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}
(57) How to display the rotation text As long as the user uses TrueType or GDI pen or font, it can display rotation text (some hardware devices also support rotary raster fonts). The IFESCAPEMENT member in the logfont structure specifies the angle of the text line and the X-axis, the unit of the angle is one-tenth of the degree rather than the degree, for example, ifscapement is 450 indicates 45 degrees of the font. To ensure that all fonts rotate in the same direction of the coordinate system, be sure to set the clip_lh_angles bit of the IFESCAPEMENT member, otherwise some fonts may rotate in reverse. The following example uses a 14-point Arial font to draw a string per spacer. Void Csampleview :: Ondraw (CDC * PDC) {// determine the size of the window.cRect RcclientgetClientRect (RcClient) // Create Sample String.cstring Str (_T ("WHEEE ... I am Rotating!")) //// Draw transparent, red text.pDC-> SetBkMode (tRANSPARENT) pDC-> SetTextColor (RGB (255,0,0)) CFont font // font objectLOGFONT 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_NORMALstFont.ifClipPrecision = LCIP_LH_ANGLESstrcpy (stFont.lfFaceName, "Arial") // Draw text at 15degree 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.delectionObject () font.delectObjext ()} (58) How to display a string that contains tab characters When you need to expand the tag character, this can be Call CDC :: TabbedTextOut or CDC :: DrawText and specify the DT_expandTabs flag to complete. The TabbedTextOut function allows the specified label bit, the following example specifies a label every 20 device unit: void csampleview :: OctRaw (CDC * PDC) {ctestdoc * pdoc = getDocument () assert_valid (pdoc) cstring stratr.format (_t (" Cathy / Tnorman / Toliver ") INT NTABSTOP = 20 // Tabs Are Every 20 Pixelspdc-> TabbedTextout (10, 10, Str, 1, & NTABSTOP, 10)}
(59) How to quickly format a CString object call cstring :: Format, the function and the printf function have the same parameters, the following example shows how to use the format function: // get size of window.cRect RcWindowGetWindower (rcwindow) // Format Message String.cstring strmessageStrMessage.Format ("Window Size (% D,% D)"), RCWindow.Width (), RcWindow.Height ()) // Display the message.MESSAGEBOX (STRMESSAGE) Too long, how to display a omitted number call CDC :: DrawText and specify a DT_END_ELLIPSIS flag, so that the tail of the string is adapted to the specified boundary rectangle with a small number. If you want to display the path information, specify the DT_END_ELLIPSIS flag and submit 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 fitpdc-> drawtext ("this is a long string"), CRECT (10, 10, 80, 30), DT_LEFT | DT_END_ELLIPSIS) // Add Ellpsis To Middle Of IF It Does NOT Fitpdc-> DrawText (AFXGetApp () -> M_PSZHELPFILEPATH, CRECT (10, 40, 200, 60), DT_LEFT | DT_PATH_ELLIPSIS)}
(61) Why even if the EnableMenuItem menu item is called, the menu item is still set to false if the menu item needs to set the cframewnd :: m_bautomenuenable. If the data member is true (default), the workfall will automatically disable no 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)
(62) How to add a menu item to the system menu to add a menu item to the system menu requires the following three steps: First, use the Resource Symbols dialog (Select Resource Symbols ... You can display the dialog) Define menu Item ID, this ID should be greater than 0x0f and less than 0xF000; secondly, call CWnd :: getSystemMenu Get the pointer to the system menu and call CWnd :: Appendmenu to add menu items to the menu. The following example adds two new int CMainFrame :: OnCreate (LPCREATESTRUCT lpCreateStruct) {... // Make sure system menu item is in the right range.ASSERT (IDM_MYSYSITEM & 0xFFF0) == IDM_MYSYSITEM) ASSERT (IDM-MYSYSITEM <0xF000 to the system menu ) // 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_mysysiSISTEM, STRMENUITEM) ...} The user should detect when selecting the system menu item. Use ClassWizard WM_SYSCOMMAND message handling menus and detects user nID parameters: void CMainFrame :: OnSysCommand (UINT nID, LPARAM lParam) {// Determine if our system menu item was selected.if ((nID & 0xFFF0) == IDM_MYSYSITEM) {/ / TODO-Process System Menu Item} elsecmdiframewnd :: OnSysCommand (Nid, LPARAM)} Last, a well-designed UI application should display a help information at the status bar when the system menu item is highlighted, which can increase a system The entrance to the skeed table of the menu base ID is implemented. (63) How to determine the number of rows occupied by the top menu This can be implemented by simple subtraction and division. First, the user needs to calculate the height and customer area of the primary frame window; secondly, subtract the height of the client area, frame boundary, and title from the height of the mainframe window; finally, divide the menu bar. The following member function is a code implementation that calculates the number of rows occupied by the main box menu. int CMainFrame :: GetMenuRows () {CRect rcFrame, rcClientGetWindowRect (rcFrame) GetClientRect (rcClient) return (rcFrame.Height () -rcClient.Height () - :: GetSystemMetrics (SM_CYCAPTION) - (:: getSystemMetrics (SM_CYFRAME) * 2) ) / :: getSystemMetrics (SM_CYMENU)}
(64) How to determine the color call of the system display element in the user environment Call the SDK function GetSysColor to get a color of a specific display element. The following example shows how to call this function setting window title color in the MFC function cmainframewnd :: onncpaint. void CMiniFrameWnd :: OnNcPaint () {... dc.SetTextColor (:: GetSysColor (m_bActive COLOR_CAPTIONTEXT:? COLOR_INACTIVECAPTIONTEXT)) ... (65) how to query and set the system parameters introduced SDK SystemParametersInfo function in Windows 3.1 SDK, the call to the function can query And set system parameters, repeated rate settings such as button, double-click delay time, icon font, and desktop overlay, etc. // 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_SETDESKWALLPAPER , 0, _T ("forward.bmp"), spif_updateinifile)
(66) How to determine that the current screen resolution calls the SDK function GetSystemMetrics, which can retrieve the Windows display information, such as title size, boundary size, and scroll bars. // Initialize CSIZE Object with screen size.csize sizescreen (sm_cxscreen), getSystemmetrics (SM_CYSCREEN))
(67) How to use a predefined Windows cursor to call CWINAPP :: LoadStandardCursor and transmit the cursor identifier. BOOL CSampleDialog :: OnSetCursor (CWnd * pWnd, UINT nHitTest, UINTmessage) {// Display wait cursor if busy.if (m_bBusy) {SetCursor (AfxGetApp () -> LoadStandardCursor (IDC_WAIT)) return TRUE} return CDialog :: OnSetCursor ( PWND. NHITTEST, MESSAGE
(68) How to retrieve the original Task Manager application used by the Task list The original Task Manager application displays a list of top windows. To display the list, the window must be visible, including a title and cannot be owned by other windows. Call CWnd :: getWindow can retrieve the list of top windows, call iswindowVisible, getWindowTextLength, and getowner to determine if the window should be in the list. The next example will populate the title of the TaskManager window into 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 Do Does Not Have An Owner? IF (PWnd -> IswindowVisible () && PWnd -> getWindowTextLength () &&! Pwnd - > Getowner ()) {// address o window to list box.pwnd -> getWindowText (strcaption) list.addstring (strcaption)} // get next window in window list.pwnd = pWnd-> getWindow (gw_hwndnext)}} (69) How to determine that both the Windows and Windows system directory have two SDK functions to complete this feature. GetWindowsDirectory and GetSystemDirectory, the following example illustrates the use of 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 ("Windows System Directory% S / N", SZDIR)
(70) Where to create a document call, the SDK function getTemPath can determine the directory of the temporary file, which first detects the TMP environment variable for the temporary path: If TMP is not specified, the TMP environment variable is detected, and then returned to the current directory. The following example shows how to create a temporary file. ... // get unique temporary file.CString strFileGetUniqueTempName (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} (71 How can I build a wait cursor? Call the BeginWaitCursor function to start the wait cursor, call the endwaitcursor function to end the wait cursor. To note, both must call the members of the app, as shown below: AFXGetApp () -> BeginWaitcursor (); // To do things AFXGetApp () -> endwaitcursor ();
(72) I have a FORM window in the MDI frame. It has a cancel button, I need to turn off the Form window when the user presses the cancel button. How should I close this document? Turn the onclosedocument function.
(73) How to access the desktop window Static function CWnd :: getDesktopWindow Returns the pointer to the desktop window. The following example illustrates how the MFC function cframeWnd :: BeGinModalStae uses this function to enter a list of internal window. void CFrameWnd :: BeginModalState () {... // first count all windows that need to be disabledUINT nCount = 0HWND hWnd = :: GetWindow (:: GetDesktopWindow (), GW_CHILD) while (hWnd! = NULL) {if (:: IsWindowEnabled (hwnd) && cWnd :: fromHandlepermanent (hwnd)! = null && afxisdescendant (pparent-> m_hwnd, hwnd) && :: SendMessage (hwnd, wm_disablemodal, 0, 0) == 0) { ncount} hWnd = :: getWindow (hwnd, gw_hwndnext)} ...
(74) What is colorref? How can I use it? ColorRef is a 32-bit integer value, which represents a color. You can initialize ColorRef with RGB functions. For example: colorRef color = RGB (0, 255, 0); RGB function receives three 0-255 values, one represents red, one represents green, one represents blue. In the above example, the red and blue values are 0, and there is no red and blue in this color. Green is a maximum of 255. This color is green. 0,0,0 is black, 255, 255, 255 is white. Another method of initializing ColorRef is as follows: CColorDialog colorDialog; colorRef color; if (colorDialog.domodal () == idok) {color = colorDialog.getColor ();} This code uses the color dialog box in the MFC, It requires files.
(75) What is the STDAFX file generated by AppWizard? It is the master to assist in the production of a pre-editing header file. Papermill you don't need to modify it.
(76) I was CDWORDARRAY in my program. I added approximately 10,000 integers to it, which makes it very very slow. Why is it so bad? CdwordArray is very easy to use, just because you don't have the maximum size of the array. Therefore, when you add new elements, this class will renew the distribution space from the heap. Unfortunately, this class will renew the distribution space every time you insert a new element. If you add a lot of new elements to it, these assignments and complex arrays will make it slower. The method of solving this question is that you can change this frequency of renovation with the second parameters of the setsize function. For example, if you set this parameter to 500, it will re-distribute and add 500 new spaces at each array space. Instead of 1. In this way, you can add additional 499 elemental space without reimbursement, which will greatly improve the speed of operation.
(77) How do I change the size of the sub-window of the MDI frame window so that the window is opened at a certain size in the view in the onInitialUpdate function in the view. GetParentFrame will return to a pointer to a frame window that has the viewing window. Then call the MoveWindow on the frame window.
(78) In some parts of my program, I can call the MessageBox function to create an information dialog, such as in the view class. However, I can't, such as the document class in other parts. why? How can I create a message dialog in my application class? The Messagebox function comes from the CWND class, and you can only call it in the class (such as cView) in the CWND. However, MFC also provides an AFXMessagebox function, you can call it in any place. (79) I need to set global variables in my program to enable all classes in the document to access. I should put it where? Put the variable to Attribute in the header of the application program class. Then, in the order of the program, you can access the variable with the following method: cmyapp * app = (cmyapp *) AFXGetApp (); app-> myglobalvariable = ...
(80) I have heard that MFC can discover the memory vulnerability, how do I use this feature? If you run your application if you go in the Debug menu (not the Execute option in the Project menu), the MFC should report when the program terminates Memory vulnerability. If there is no, the test is tried to run the MFC Traceer program (in the VC program group), and start tracking. The postpartum will be returned.
(81) How can I loop in my application? Use the open document that has been opened? Using the getFirstDocPosition () and getNextDocPosition () and getNextDoc () functions in CDOCTemplate.
(82) Can you loop in my app? Use the unapproveled getFirstViewPosition () and getNextView () functions in cdocument.
(83) What is the use of precreateWindow? PrecreateWindow allows you to change window attributes before calling CREATEWINDOW.
(84) How to prevent the MFC from pre-deposit a document name into an application name on the window title bar? Remove the window pattern of FWS_PREFIXTITLE flags in the PrecreateWindow function: cs.style & = ~ fws_prefixtitle;
(85) How should I prevent MFC from adding a document name on the window title bar? Remove the window pattern of fws_addtotitle flags in the PrecreateWindow function: cs.style & = ~ fws_addtotitle;
(86) How should I change the size of the window? Because the window is actually the sub-window of the frame window, you must change the size of the frame window, rather than changing the window. Use the getParentFrame () function in the CView class to get the pointer to the frame window, then call the MoveWindow () function to change the size of the frame. This will make the varying size of the view fever frame window.
(87) I have a modeless dialog. How can I remove the CDIALOG object when you exit? Add "delete this" to postncdestroy. This master is used in the case where you need to automatically delete the object. (88) Why is "delete this" in PostncDestroy instead of onNCDESTROY? ONNCDESTROY is only called by a window that has been established. If the window is lost (such as PreCreateWindow), there is no window to send WM_NCDESTROY message. Postncdestroy is completely deleted in the object window, after OnncDestroy, even after the window is set up after a failure.
(89) Where is the MRU list in the File menu? Where is the name in the list? How can I change the maximum value in the list? The call to loadstdprofilesettings in the initInstance function of the application program class. This call is connected to a parameter (4) is 4) in the default. The MRU document name is called from the INI file. If you have a menu option with ID_File_MRU_FILE1, it will replace it for the transferred MRU list. If you change the value (maximum 16) you change to LoadStdprofileSetting, you change the maximum value of the file name.
(90) I added a new item in the menu. However, when I choose this item, there is no prompt information on the status bar. Why? Open the menu template in the resource file. Open the properties dialog box for the new menu option. In the PROMPT editing box of the bottom of the dialog box, you can make a message on the status bar on the state bar (if you have established a toolbar button): Status Bar String / NFLYING TAG
(91) How can I add some things in the application's default system menu? The system menu is similar to the menu class, you can add or delete the project, which requires the function of the CMenu class. The following code adds a new menu item after your system menu: cmenu * sysmenu; sysmenu = m_pmainwnd-> getSystemMenu (false); sysmenu-> appendmenu (mf_string, 1000, "xxx"); see cmenu in the MFC Help file class.
(92) I established a dialog. But when I display the dialog, the first edit box always cannot get the focus, I have to click it to make it focus. How can I get the first edit box to get a focus when the dialog is open? Open the dialog box template in the resource editor. Select the Tab ORDER option in the Layout menu. Press your needs to click on the controls in the dialog box to resemble these controlled Tab sequences.
(93) How can I have a window with "always on top" features? After calling OnfileNew, add the following code in your InitInstance function: m_pmainwnd-> setWindowPos (& CWnd :: Wndtopmost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); (94) I want to add a document template for my Form View. I first established the dialog template and then use ClassWizard to establish a new class based on CFormView, which is also inherited from cDocument. I also established the corresponding resources and add new document templates in InitInstance. However, when I tried to run the program, ASSERTION information appeared. why?
The Form's dialog box template requires some special settings to CFRomView. To ensure that the simplest method of these settings is to use AppWizard to build a CFormView application program, and check the STYLES Properties selected by the dialog box built by AppWizard. You will hang this dialog box template has a column pattern: no title bar, invisible and "child". Change your Form View's dialog box attributes. (95) I have a list box in a dialog, I need the item in the Tabbed list box. However, when I deal with the list item containing Tab characters (added with addstring), Tab is displayed into small black blocks without expanding. Where is wrong?
In the dialog box mode, the properties of the list box are opened. Make sure the "use tabstops" pattern. Then, ensure that settabstops are called in the OnInitDialog function in the dialog box class. (96) I have established an app and use the CRecordset class. However, when I run the program, it tries to access the database and give the INTERNAL Application Error dialog. What should I do?
In the case of the case, the dialog box is now present when the SQL statement of the data is sent to the data library in the SQL statement of the information. For example, see the example below: set.m_strfilter = "(zipcode = '27111')"; if the zipcode column is defined as a string, there is no problem, if it is defined as long, "INTERNAL Application Error" dialog box appears This is because the type does not match. If you delete a single quotes of 27111, there will be no problem. When you see "INTERNAL Application Error", it is best to check the SQL statement to be sent to the data library. (97) I have established a class with ClassWizard. However, I took the name wrong, I would like to delete it from the project, what should I do?
After the ClassWizard dialog is turned off, remove the new class H and CPP files with the file handler. After opening ClassWizard, it will tell the two files, and ask if you should do it. You can select the button that removes the two questions from the project. (98) When I open the window in the application, I want to pass the rectangular size of the window. The rectangle specifies the peripheral size of the window, but when I call getClientRect, the resulting size is smaller than the desired value (because the toolbar and window border). Is there other methods to calculate the size of the window?
See CWnd :: CalcWindower. (99) I set a integer variable in the document class. However, when I try to write the variable into the Archive file in the Serialize function, the type error occurs. Other variables in the document have no problem. why?
The Archive class only carries some types of >> and << operators. The "int" type is not in it, and it is also because INT variables are different from Windows 3.1 and Windows NT / 95. The "long" type has been supported, and you can change the int class type to the long type. See the CARCHIVE class in the MFC Help document.
(100) How to control the size of the menu? I generated a dynamic menu (such as file, edit, view ... help) with MFC, I want to control the size of this menu (length high).
Method 1: Find WM_MeasureItemStruct. Method 2: Query System :: getSystemMetric (SM_CXMENUSIZE).
/ * You can get the size of the text by the following code: (a) Get the font used * /
NonclientMetrics NCM; hfont hfontmenu; size size; size = size.cy = 0;
memset (& ncm, 0, sizeof (NONCLIENTMETRICS)); ncm.cbSize = sizeof (NONCLIENTMETRICS); if (SystemParametersInfo (SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICS), & ncm, 0)) {hFontMenu = CreateFontIndirect (& ncm.lfMenuFont); / * ( B) Wait for the text of the menu item: * / char sztext [_max_path];
PMenu-> getmenustring (0, sztext, _max_path, mf_byposition); / * then get the height of the menu item text: * / hfont hfontold; HDC HDC;
hDC = :: GetDC (NULL); hFontOld = (HFONT) :: SelectObject (hDC, hFontMenu); GetTextExtentPoint32 (hDC, szText, lstrlen (szText), & size); SelectObject (hDC, hFontOld); :: ReleaseDC (NULL, HDC);} / * At this point, size.cy is height, size.cx is a width, you can add custom height and width to the menu, by comparison, I found that the width is 4 relatively appropriate. * /
(101) Change the status color of LVIS_SELECTED? I want to gray gray gray when the CListCtrl item and the CTREECTRL item in the LVIS_SELECTED state.
Method 1: Find function CustomDraw, which is the public control provided by IE4, allowing you to have your own code. Method 2: Generate a DRAW control, then process text colors in DrawItem.
(102) How can I only store some part of the document? I just want to store a part of the document, can I use a document like using a file? (There is a positioning function). Set each CARCHIVE class to the CFILE class derive class, This way you can use member functions such as SEEK.
(103) Is there a bug in the save tool strip menu?
When using floating menu bars, Savebarstate and LoadBarstate have problems. If the menu is floating, it will appear in the upper left corner when the application is restacked, and it is fixed when the screen is fixed, and the next startup will appear in this position. What is this? You try this ptoolbar-> create (this, ..., id_mytoolbar); your toolbar needs to include ID instead of the default toolbar.
(104) Tip of the day of bug
I created a simple MDI application that uses .BSF (Custom Document Extension) as its document I save a foo.bsf document, you can double-click the file in the Explorer to open the MDI application at the same time. Foo .BSF document. But after I add a TIP of the day component to the MDI application, I will give me a warning from the resource manager: assert (:: iswindow (m_hwnd)), then The MDI app is dead. When the application is started from the DDE (for example, double-click the related document), "Tip of the day" is bug. You can look at the function "showtipatstartup", which is called in "InitInstance" You can see that Tip of the day is displayed as a mode dialog box, which has been messaging when handling other messages. You can modify showtiPatStartup to make it started from DDE without Tip of the day.void ctipofapp :: ShowtiPatStartup (void ) {// CG: This function added by 'Tip of the Day' component CCommandLineInfo cmdInfo; ParseCommandLine (cmdInfo); if (cmdInfo.m_bShowSplash && cmdInfo.m_nShellCommand = CCommandLineInf:.! FileDDE) {CTipDlg dlg; if (dlg.m_bStartup ) DLG.Domodal ();}} If there are other bugs, you can set the filtering of cmdinfo.m_nshellcommand. (105) How can I make my program can display above? Let users choose " Is the top "It is best to join an option in the system menu. You can send the user's selection by modifying the WM_SYSCOMMAND message. The command ID (ID) of the menu is passed as a parameter to OnsysCommand (). To define the ID (ID) Add the following code to cMAINFRAME.CPP: #define WM_ALWAYSONTOP WM_USER 1 Add "always the top" menu item to the system menu, add the following code to the function cmainframe :: oncreate (): cmenu * psysmenu = GetSystemMenu (FALSE); pSysMenu-> AppendMenu (MF_SEPARATOR); pSysMenu-> AppendMenu (MF_STRING, WM_ALWAYSONTOP, "& Always on Top"); the ClassWizard use, the added processing of the message WM_SYSCOMMAND, you should change the message filter, the system can use Handling this message .void cMainframe :: OnsysCommand (uint nid, lparam lparam) {switch (NID) {Case WM_ALWAYSONTOP: IF (getExStyle () & WS_EX_TOPMOST {SETWINDOS (&)
wndNoTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); GetSystemMenu (FALSE) -> CheckMenuItem (WM_ALWAYSONTOP, MF_UNCHECKED);} else {SetWindowPos (& wndTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); GetSystemMenu ( False -> CheckMenuitem (WM_ALWAYSONTOP, MF_CHECKED);} Break; default: cframewnd :: OnsesCommand (NID, LPARAM);}} (106) How to control the maximum smallest size of the window frame? To control the maximum size of a frame, You need to do two things. Processing the message WM_GETMAXINFO in the inheritance class of CFrameWnd, the structure MinMaxInfo sets the limitations of the entire window class, so remember that the size of the toolbar, rolling strip, etc. should be considered. The size of the largest minimum size. voxel points - example #define MINX 200 # define MINY 300 # define MAXX 300 # define MAXY 400void CMyFrameWnd :: OnGetMinMaxInfo (MINMAXINFO FAR * lpMMI) {CRect rectWindow; GetWindowRect (& rectWindow); CRect rectClient; GetClientRect (& rectClient); // get Offset of toolbars, scrollbars, etc. int nwidthoffset = RectWindow.width () - RectClient.width (); int nHeiGHTOFFSET = RectWindow.Height () - RectClient.Height (); lpmmi -> ptMinTrackSize.x = MINX nWidthOffset; lpMMI-> ptMinTrackSize.y = MINY nHeightOffset; lpMMI-> ptMaxTrackSize.x = MAXX nWidthOffset; lpMMI-> ptMaxTrackSize.y = MAXY nHeightOffset;} a second step, in CFrameWnd PreCreateWindow function class inheritance remove WS_MAXIMIZEBOX message, otherwise you will not be maximized unexpected results .BOOL CMyFrameWnd :: PreCreateWindow (CREATESTRUCT & cs) {cs.style & = ~ WS_MAXIMIZEBOX; return CFrameWnd :: PreCreateWindow (cs ); (107) How to change the color of the window frame?
The client area of the MDI frame is overwritten by another window. In order to change the background color of the client area, you need to call this customer window. To do this, you have to handle the message WM_ERASEBKND to generate a new class, inherited from CWND, CMDIClient just call to it with a member variable, # include "MDIClient.h" class CMainFrame: public CMDIFrameWnd. {... protected: CMDIClient m_wndMDIClient;} overloaded CMDIFrameWnd :: OnCreateClientBOOL CMainFrame :: OnCreateClient to CMainFrame ( LPCREATESTRUCT lpcs, CCreateContext * pContext) {if (CMDIFrameWnd :: OnCreateClient (lpcs, pContext)) {m_wndMDIClient.SubclassWindow (m_hWndMDIClient); return TRUE;} else return FALSE;} can then be added to the processing of the message WM_ERASEBKGND (108. How to place the application window in the screen? To place your application window in the center of the screen, you only need to join: CenterWindow (GetDeskTopWindow ());