(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) / / Maximize the program. (2) Determine the path of the application USE getModuleFileName Get the path to the application, then remove the executable file name. Example: tchares // max_path defines it in the API, as if it is 128GetModuleFileName (Null, ExefullPath, Max_Path) (3) How to get other programs in the program? Two methods: (1) SDK function SHGETFOFO Or use the Extracticon to get the Handle of the icon resource, (2) SDK function SHGETFILEINFO Gets a lot of information about files, such as size icons, properties, types, etc.example (1): display 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)}}}}}: equivalent function, Use Extracticon Functionvoid CsampleView :: OnDraw (CDC * PDC) {HiCon Hicon = :: Extracticon (AFXGETITINSTANCEHANDLE (), _ T ("Notepad.exe"), 0) IF ( Hicon && Hicon! = (HICON) -1) PDC-> Drawicon (10, 10, hicon)} Description: Get the path to the notepad.exe to get the getWindowsDirectory function, if you call the brush under Win95, you should use access to registration The method of the table obtains its path, becomes a more elegant program, considering the comprehension. (4) Get various directory information Windows directory: Use "getWindowsDirectory" under the System directory under Windows: Use "getsystemdirectory" Temp Directory: USE " GetTemppath "Current Directory: Use" getCurrentDirectory "Please note the first parameter of the first two functions as a directory variable name, the latter one is reversed by two after the buffer. (5) How to customize the message 1) Manually define the message, can you Write #define WM_MY_MESSAGE (WM_USER 100), MS The recommended WM_USER 100 (2) write message processing function, returning LRESULT.LRESULT CMAINFRAME :: ONMYMESSAGE (WPARM 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 style of the window? Overload CWnd :: and modify the PreCreateWindow 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 will the window is centered Call Function CWnd :: Center WindowsExample (1):? Center window () // Relative to it's parent // relativeto ScreenExample (2): Center window (CWnd :: GetDesktopWindow ()) // Relative toApplication's MainWindowAfxGetMainWnd () -> Center window () (9) how to make a window and the MDI window Maximize and minimize boot? 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 . (10) How to limit the size of the window? That is, FixedDialog form. Windows sends a WM_GETMAXMINIINFO message to track, responds to it, write code in ONGETMAXMINFO: (11) How to make the window not visible? Very simple, with SW_HIDE hide the window, you can combine FindWindow, ShowWindow control (12) How to create a word wrap of CEditView overloaded CWnd:.: PreCreateWindow and modify CREATESTRUCT structure, closed CEditView object ES_AUTOHSCROLL WS_HSCROLL style and position, due to the CEditView:: PrecReateWindow Displays Sets CS. Style, modify CS. 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_NOSIZIZE | SWP_NOAORDER) (15) Display window MFC for universal controls provides several CView derived window classes, packages The function of the general control, but still uses a workfall document display window architecture: CEDITVIEW encapsulates the editing control, CTREEVIEW keeps the tree list control, and the CListView packages the 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 to send the window to the window to send WM_NCHITTEST information to the window when the window needs to determine the mouse position, 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 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 windows. // 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 the title of any window (including the control).
// 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_ADDTO Title 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 (23) How to enable and disable toolbars 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 You can use the new SDK function setWindowRGN. This function will paint and mouse messages Limited a specified area of the window, actually causes 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 to Obtain Application Example handle of the program Save an instance handle of the application in CWINAPP M_HINSTANCE, you can call the AFXGetInstancdHandle to get the handle .Example: handle hinstance = AFXGETITINSTANCEHANDLE = AFXGETINSTANCEHANDLE = AFXGETINSTANCEHANDLE = AFXGETITINSTANCEHANDLE = AFXGETInstanceHandle () (26) How to program end applications? This is a very simple and programming. I have encountered problems. Send a WM_CLOSE message to the window, call the CWnd :: ONCLOSE member function. Allows whether the user prompts whether to save the modified data .Example: AFXGETMAINWINDOW () -> SendMessage (WM_CLOSE) can also create a custom function Terminate Windowvoid Terminate WINDOW (LPCSTR PCAPTION) {CWND * PWND = CWND :: FindWindow (Null, PCAPTION) IF (PWND) PWnd -> SendMessage (wm_close)} Description: The FindWindow function is not advocated because it cannot handle the title bar automatic change For example, we have to detect notepad is not running and don't know the title bar of NOTEPAD in advance. At this time, FindWindows 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 modeless dialog represents this dialog.BOOL bResult = pDialog -.> Creste (IDD_IDALOG) ASSERT (bResult)} (28) how to prevent the main frame in the note window activities Document Name Create a master window and 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 disable the style bit, 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 (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 your code, work When you create a status bar and toolbar, use a sub-window for the mainframe window, the status bar has an AFX_IDW_STATUS_BAR identifier, the toolbar has an AFX_IDW_TOOLBAR identifier, the following example shows how to call CWnd:: getDescendantWindow and AfxgetMainWnd to get Pointer: // Get Pointer to Status Bar .cstatusbar * Pstatusbar = (CStatusbar *) AFXGETMAINWND () -> getDescendantWindow (AFX_IDW_STUTUS_BAR) (32) How to enable and disable toolbars If you set a CBRS_Tooltips 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 tool bar is a toolbar window title , it is possible to call CWnd:: SetWindowText title set, the following example: int CMainFrame:: OnCreate (LPCREATESTRUCT lpCreateStruct) {... // set the caption of the toolbar .m_wndToolBar.SetWindowText (_T "Standdard") (34) how to make ? window is always at the forefront BringWindowToTop (Handle) SetWindowPos function, most top style of the specified window, with style Example WS_EX_TOPMOST expansion window: void ToggleTopMost (CWnd * pWnd) {ASSERT_VALID (pWnd) pWnd -> SetWindowPos (pWnd-> GetStyle ( ) & WS_EX_TOPMOST? & WDNOTOPMOST: & 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, The display bitmap is easy in the dialog box, just drag the graphic control to the dialog and select the appropriate properties, the user can display icons, bitmaps, and increase Strong meta file. (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) ...} How to use the OLE_COLOR data type in the OLE control, such as COLLECONTROL:: GetfortColor, and ColeControl: GetBackColor, etc. Returns the color of the OLE _COLOR data type, while GDI objects are used by pen and brushes. It is a ColorRef data type, 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-> FillRect (RcBounds, & Brushback) // Other Drawign Commands ...} (41) How to display a file list call CWnd:: DLGDIRLIST or CWnd without using universal files open dialog :: DLGDIRLISTCOMBOBOX, Windows will automatically populate the available drive names or files in the list box or combo box, and the following example populates the files in the Windows directory in the combo box: Bool Csampledig:: OnInitDialog () {CDIALOG: : OnInitDialog () TCHAR szPath [MAX_PATH] = { "c: // windows"} int nReslt = DlgDirListComboBox (szPath, IDC_COMBO, IDC_CURIDIR, DDL_READWRITE | DDL_READONLY | DDL_HIDDEN | DDL_SYSTEM | DDL_ARCHIVE) return TRUE} (42) Why spin button control It looks forward that the CSPinctrl:: setRange Sets the range of the rotation button control, the default upper limit of the rotation button control is 0, the default lower limit is 100, which means that the value of rotation according to the control is generated from 0 to 0. 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, 0, 100, 24), this, IDC _MYBUTTON) (47) How to limit the graphics in the edit box If the user is only allowed in the editing control Receive numbers, 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 the editing control only to collect only characters. 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) 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, there are two Method. 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 a dialog) CWnd:: OnCrtLCOLOR, you can reset this function in the parent window class and specify a new painting property of the control. For example, change all the editing 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 handle the notification message and specify the painting attribute of each control, this method is not a fully object-oriented method. Control processes the message and specifies the painting properties More reasonable. Message reflection allows users to do this. The notification message is sent to the parent window. If the parent window is not processed, it is sent to the control. Create a custom color list box control must follow the following steps. First, create a CListBox to create a CListbox using ClassWizard Class and add the following data members 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 predefined GDI objects Several predefined objects of Windows can be used 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 ellipse.pDC-> Ellipse (rcView) // Restore original brush.pDC-> SelectObject (pOrgBrush)} (52) how to get GDI object attribute information 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 CRectTracker rectangular area is a very useful class can call CRectTracker :: TrackRubberBand In response to the WM_LBUTTONDOWN message, create a rectangle of a rubber region. 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 PDOC-> setModifiedflag () PDOC-> UpdateAllViews (null)} elsepdoc-> m-tracker.trackberband (this, point, true) cview :: ONLBUTTONDOWN (NFLAGS, POINT)} (54) How to update flip background color Text call CDC :: setBkmode and transfer Opaque with current background color fill background, or call CDC :: setBkmode and transmit transpaarent keeps 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 and width of the currently selected fonts 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 rotating text As long as the user uses TrueType or GDI pen or fonts 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 RcWindowGetWindowRect (rcwindow) // Format Message String.cstring StrMestageStrMessage.Format ("Window Size (% D,% d) "), rcwindow.width (), rcwindow.Height ()) // display the message.MessageBox (StrMessage) (60) How long is the end of Taiwan to display a omitted number call CDC :: DRAWTEXT and specify a DT_END_ELLIPSIS flag so that you can use a small number to replace the tail of the string so that it is suitable for the specified boundary rectangle. If you want to display the path information, specify the DT_END_ELLIPSIS flag and 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 do the menu items are set to false even if the menu item is in a disabled state, if the data member is true, if the data is true, the workfrup will automatically disable There is no online menu item for ON_UPDATE_COMMAND_UI or ON_COMMAND.
// Disable MFC from automatically disabling menu items.m_bAuoMenuEnable = FALSE // Now enable the menu item.CMenu * pMenu = GetMenu () ASSERT_VALID (pMenu) pMenu-> EnableMenuItem (ID_MENU_ITEM, MF_BYCOMMAND | MF_ENABLED) (62) How the system menu Add a menu item 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 conversation in the View menu) Define the menu item ID, the 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 Add the menu item 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 (64) How to determine how 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 ("Forest.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 the title size, the boundaries, and the size of the scroll bar. // Initialize CSize object with screen size.CSize sizeScreen (GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN)) (67) How to use a predefined Windows cursor calls CWinApp :: LoadStandardCursor and send 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 file call call SDK function getTemPath can be determined Temporary file directory, first detect TMP environment variables for 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. It should be noted that both the two members functions are called, as shown below: AFXGetApp () -> beginwaitcursor (); // To do things AFXGetApp () -> endwaitcursor (); (72) I have in the MDI framework FORM window. 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 any part of the program, you can use the following method to access the variable: cmyapp * app = (cmyapp *) AFXGetApp (); app-> myglobalvariable = ... (80) I heard that MFC can find memory Vulnerability, how do I use this feature? If you run your application if you go in the Go option in the Debug menu (not the Execute option in the Project menu), the MFC should report the memory vulnerability when the program terminates. 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 preset the document name into the application name on the window title bar? Delete the window style of the FWS_PREFIXTITLE flag in the PrecreateWindow function: cs.style & = ~ fws_prefixtitle; (85) How should I prevent MFC? Add a document name on the window title bar? Delete the window style of the FWS_ADDTITITE flag in the PrecreateWindow function: cs.style & = ~ fws_addtotitle; (86) How should I change the size of the window? Because the view window is actually the sub-window of the frame window So you have to change the size of the frame window instead of 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 at the bottom of the dialog, you can specify the prompt information on the status bar and the prompt information on the toolbar (if you have created the toolbar button): Status bar string / nflying tag (91) How do I? In order to add some things in the application's default system menu? The system menu is similar to other menus, you can add or remove projects, which requires the member 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. How should I do? In the case of the case, when the SQL statement of the data is sent to the data library in the SQL statement of the data. 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, the new class H and CPP files are deleted with the document 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). Do you have 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_MEASureItem Method 2: Query System :: getSystemMetric (SM_CXMENUSIZE). / * You can get the size of the text with the following code: (a) Getting the font used * / nonclientmetrics ncm; hfont hfontmentMenu; size size; size.cy = 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 text of menu items: * / 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, HD C);} / * 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 make the clistctrl item and the CTREECTRL item in the LVIS_SELECTED state. Method 1: Find the function CustomDraw, which is the public control provided by IE4, allowing you to have your own code. Method 2: Generate a DRAW control, then handle text color in DrawItem. (102) How to 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? (That's a positioning Function). Sets each CARCHIVE class to the derived class of the CFILE class so you can use member functions such as Seek. (103) Save the tool strip menu Is bug? When using the floating menu, 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 in the screen, the next startup will appear in this position. What is the reason? You try this ptoolbar-> Create (this, ..., id_mytoolbar); your toolbar needs to include ID instead of the default toolbar. (104) Tip of the day bug I created a simple MDI application, use .bsf ( Custom Document Extension) When I save a foo.bsf document as a document, you can double-click the file in the Explorer to open the FOO.BSF document at the same time. But when I add A to the MDI application After the Tip of the day, you will give me a warning from the resource manager, you will give me a warning: assert (:: iswindow (m_hwnd)), then the MDI application is dead. When the application is started from DDE (For example: Double-click the relevant document), "Tip of the day" is bug. You can look at the function "ShowtiPatStartup", which is called in "InitInstance", you can see Tip of the day as a mode dialog box When processing other messages, it has been messaging when you modify showtiPatStartUp to start from DDE to start up.void ctipofapp :: showtipatstartup (void) {// cg: this function add by 'tip of the Day 'Component. Cco mmandLineInfo cmdInfo; ParseCommandLine (cmdInfo); if (cmdInfo.m_bShowSplash && cmdInfo.m_nShellCommand = CCommandLineInf:! FileDDE) {CTipDlg dlg; if (dlg.m_bStartup) dlg.DoModal ();}} if there are other bug, you can set Filtering cmdinfo.m_nshellcommand. (105) How can I make my program on other windows? Let the user choose "Almost" It is best to join an option in the system menu. You can modify the WM_SYSCOMMAND message To send the user's choice. The command ID (ID) of the menu is passed to the onsysCommand () as a parameter. To define the ID (ID), add the following code to cmainframe.cpp: #define WM_ALWAYSONTOP WM_USER 1 will "always On the top"
The menu item is added 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 "); Use classwizard to join the processing of the WM_SYSCommand message, you should change the message filter, use the system to handle this message. Void cMainframe :: OnsesCommand (uint nid, lparam lparam) {switch (nid) {Case WM_ALWAYSONTOP : if (GetExStyle () & WS_EX_TOPMOST) {SetWindowPos (& 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 :: OnSysCommand (nID, lParam);}} (106) how to control the maximum and minimum window frame Size? To control the maximum smallest size of a frame, you need to do two things. Handling messages in the inheritance class of CFrameWnd processing messages, structure MinMax INFO sets the entire window class, so remember to consider the size of the toolbar, rolling strips, etc. - Samples of the largest minimal size - 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