VC practical small knowledge summary (reproduced)
(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. Shielded advertising]
AfxgetMainWnd () -> showwindow (sw_showmaxmize) // maximizes the program.
(2) Determine the path to the application
Use getModuleFileName Get the path to the application and then remove the executable file name. Example: tchar exefullpath [max_path] // max_path is defined in the API, as if it is 128 getModuleFileName (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): The NotePad icon is displayed 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 ), 0) IF (HiCon && HiCon! = (HICON) -1) PDC-> Drawicon (10, 10, hicon)}
Description: Get the path of NOTEPAD.EXE to get 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 "getSystemDirectory" Temp Directory: Use "getTemppath" Current Directory: Use "getcurrentdirectory"
Note The first parameter of the first two functions is the directory variable name, and the latter is the opposite of the buffer.
(5) How to customize the message 1) Manually define the message, you can write
#define WM_MY_MESSAGE (WM_USER 100),
MS recommended at least WM_USER 100
(2) Write a message processing function, use
WPARAM, LPARAM Returns LRESULT. LRESULT CMAINFRAME :: OnmyMessage (WPARAM WPARAM, LPARAM LPARAM) {Temp Directory: Use "getTemppath" // Add to 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 :: PrecreateWindow and modify the CreateStruct structure to specify the window style and other creation information.
Example: Delete "Max" Button and Set Original Window's Position and Size BOOL CMainFrame :: PreCreateWindow (CREATESTRUCT & cs) {cs.style & = ~ WS_MAXINIZEMOX cs.x = cs.y = 0 cs.cx = GetSystemMetrics (SM_CXSCREEN / 2) CS.CY = getSystemMetrics (SM_CYSCREEN / 2) Return CmdifraMew :: 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. Set the value of m_ncmdshow in the initstance function.
M_ncmdshow = sw_showmaxmized // Maximize m_ncmdshow = sw_showminmized // Minimize m_ncmdshow = sw_shownormal // Normal mode
MDI window: If you create a new application, you can use the MFC AppWizard's Advanced button and detect the maximize or minimize the MDI Window's PrecreateWindow function in the MDI sub-window style group, set WS_MAXMIZE or WS_MINMIZE
If you are derived from cmdichildwnd, call the CWnd :: Show Window in the OnInitialUpdate function to specify the style of the MDI Child Window.
(10) How to limit the size of the window? That is, FixedDialog form. Windows sends a WM_GETMAXMINFO message to track, in response to it, write code in ONGETMAXMINFO:
(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: WINDOWS will send a WM_QUERY-OPEN message in the recovery program form, set the member function with ClassWizard
ONQUERYOPEN (), Add Following Code: Bool CMAINFRAME :: ONQUERYOpen () {Return False}
(14) Move window call CWnd:: setWindowPOS and specifies 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 REWINDOW GETWINDOWRECT (REWINDOW) // Make The Window TWICE 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 techniques have two points of adverse, one of which is a large window when the window's customer area is double-hit; two, 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 clicked on its 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 be called
CWnd:: getparentframe. void CSampleDialog:: OnLbuttonDown (UINT nFlags, Cpoint point) {Cdialog::. OnLButtonDow (nFlags, goint) // Fool dialog into thinking simeone clicked on its caption 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 That Needs to Be ERSED. Bool Csampled:: OneRaseBkgnd (CDC * PDC) {// Create a Pruple Brush. CBrush Brush (RGB (128, 0, 128)) // Select The Brush Into The Device Context. CBrush * pOldBrush = pDC-> SelcetObject (& brush) // Get the area that needs to be erased. CRect reClip pDC-> GetCilpBox (& rcClip) // Paint the area. pDC-> PatBlt (rcClip.left, rcClip.top, RcClip.width (), rcclip.height (), ptcopy // 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 (" Button New Title ")) If you need to modify the title of the window (Note: Control is also a window), you should consider using 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 The implementation of the AFXSetWindowText is as follows:
voik AFXAPI AfxSetWindowText (HWND hWndCtrl, LPCTSTR IpszNew) {itn nNewLen = Istrlen (Ipaznew) TCHAR szOld [256] // fast check to see if text really changes (reduces flash in the controls) if (nNewLen> _contof (szOld) || :: GetWindowText (HWndCrtl, Szold, _countof (Szold)! = Nnewlen || IstrMP (Szold, Ipsznew)! = 0 {// Change It:: setWindowText (hwndctrl, ipsznew)}}
(20) 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_ADDTOTITELIN MAIN FWS. CS.Styel & = ~ FWS_ADDTTTIL & = ~ FWS_ADDTTTITEL RETURN CMDIFRAMEWND:: PrecreateWindow (CS)}
Closing the FWS _Addtotitle style of the MDI sub-window creates a window with a empty title, 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 strip 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 pointers of these 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 creates a member function that completes this feature by calling CControlBar:: GetBarsTyle and CControlbar:: SetBarstyle
void CMainFrame:: EnableToolTips (BOOL bDisplayTips) {ASSERT_VALID (m_wndToolBar) DWORD dwStyle = m _wndToolBar.GetBarStyle () if (bDisplayTips) dwStyle | = CBRS_TOOLTIPS else dwStyle & = ~ CBRS_TOOLTIPS m_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 rcDialog GetClientRect (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 is created 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 border dc SelecStockObject (NULL_PEN) // get the RGB colour components of the sphere color COLORREF color = RGB (.. 0, 0, 255) BYTE byRed = GetRValue (color) BYTE byGreen = GetGValue (color) BYTE byBlue = GetBValue (color) // get the size of the view window Crect rect GetClientRect (rect) // get minimun number of units int nUnits = min (rect.right, rect.bottom) // calculate he horiaontal and vertical step size float fltStepHorz = (float) rect.right / nUnits float fltStepVert = (float) rect.bottom / nUnits int nEllipse = nUnits / 3 / / calculate how many to draw int nIndex // current ellipse that is being draw CBrush brush // bursh used for ellipse fill color CBrush * pBrushOld // previous brush that was selected into dc // draw ellipse, gradually moving towards upper-right corner For (Nindex = 0 Nindes < Nellipse Nindes ) {// Creat Solid Brush Brush . CreatSolidBrush (RGB (((nIndex * byRed) / nEllipse). ((NIndex * byGreen) / nEllipse), ((nIndex * byBlue) / nEllipse))) // select brush into dc pBrushOld = dc .SelectObject (& brhsh) // Draw Ellipse DC .ellipse ((int) FltStepharz * 2, (int) Fltstepvert * Nindex, Rect. Right - ((int) Fltstephaz * Nindex) 1, Rect. Bottom - (INT) FLTSTEPVERT * (NINDEX * 2)) 1) // delete the brush brush.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 The instance handle of the program is saved in CWINAPP M_HINSTANCE, which can call the AFXGetInstancDHandle to get the handle.
Example: handle hinstance = afxgetInstanceHandle ()
(26) How to program the end of the application? This is a simple and reprogramming. 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. [ Shielded Advertising] Series: VC Practical Try Summary (1)
EXAMPLE: AFXGETMAINWINDOW () -> SendMessage (WM_Close)
You can also create a custom function TERMINATE WINDOW
Void Terminate Window (LPCSTR PCAPTION) {CWND * PWND = CWND :: FindWindow (Null, PCAPTION) IF (PWND) PWnd -> SendMessage (WM_CLOSE)}
Note: The FindWindow function is not advocated because it cannot process automatic changes in the title bar. For example, we have to detect that nothingpad is running, do not know the title bar of NOTEPAD in advance, then FindWindow can be powerful, you can enumerate the WINDOWS task list The way is achieved. 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 {// the UpdateData rountine will set focus to correct item TRACEO ( "UpdateData failed during dialog termination ./n") return (UpdateData (TRUE)!) } // call destroywindow instead of enddialog. DestroyWindow ()} void csampledialog:: oncancel () {// call destroyWindow instead of enddialog. Destroywindow ()}
Second, it is necessary to properly remove the C object indicating the conversation. 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, create a modeless dialogue. 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 dialog is not synchronized, return immediately after creating a function call,
void CMainFrame:: OnSampleDialog () {// Allocate a modeless dialog object CSampleDilog * pDialog = new CSampleDialog ASSERT_VALID (pDialog) Destroy () // Create the modeless 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 Reset using ClassWizard
CWnd:: PrecreateWindow and close the fws_addtotitle style. Bool CMAINFRAME:: PrecreateWindow (CreateStruct & Cs) {// Turn Off FWS_ADDTOTITELIN MAIN FWS. CS.Styel & = ~ FWS_ADDTTTIL & = ~ FWS_ADDTTTITEL RETURN CMDIFRAMEWND:: PrecreateWindow (CS)}
Closing the FWS _Addtotitle style of the MDI sub-window creates a window with a empty title, you can call CWnd:: SetWindowText to set the title. Remember to set the title guide when setting 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 shows how to call CWnd:: getDescendantWindow and AFXGETMAINDWND to get pointers:
// 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 complex, with a total of ten parameters, but most of them can be replaced with null, which can specify the security attributes of the process, inherit information, priority, etc., come to see very simple EXAMPLE:
STARTUPINFO STINFO // Start the 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 shows how to call CWnd:: getDescendantWindow and AFXGETMAINDWND to get pointers:
// Get Pointer to Status Bar. Cstatusbar * Pstatusbar = (cstatusbar *) AFXGETMAINWND () -> getDescendantWindow (AFX_IDW_STUTUS_BAR)
(32) How to enable and prohibit the toolbar Tool Tips If you set the CBRS_ToolTips style bit, the toolbar will display the tooltip, you want to enable or disable the tooltip, you need to set or clear the style. The following example creates a member function that completes this feature by calling CControlBar:: GetBarsTyle and CControlbar:: SetBarstyle
void CMainFrame:: EnableToolTips (BOOL bDisplayTips) {ASSERT_VALID (m_wndToolBar) DWORD dwStyle = m _wndToolBar.GetBarStyle () if (bDisplayTips) dwStyle | = CBRS_TOOLTIPS else dwStyle & = ~ CBRS_TOOLTIPS m_wndToolBar.SetBarStyle (dwStyle)} // Get pointer to toolbar . CToolbar * ptoolbar = (ctoolbar *) AFXGETMAINWND () -> getDescendantWindow (AFX_IDW_TOOLBAR) (33) How to set the toolbar Title Toolbar is a window, so you can set the title in calling CWnd:: setWindowText to set the title:
INT CMAINFRAME:: oncreate (lpcreatestruct lpcreatestruct) {... // set the caption of the toolbar. m_wndtoolbar.SetWindowText (_t "standdard")
(34) How to make the window at the foremost?
Bringwindowtotop (Handle)
SetWindowPos function, the top style of the specified window, the style of the WS_EX_TOPMOST extension window
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)) ...}
When you need to redraw dialog (or dialogue sub-control), Windows sends a message WM_CTLCOLOR to the dialog, usually the user can let 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 a member variable for the dialogue base class.
CBURSH: Class CMYFORMVIEW: PUBLIC CFORMVIEW {... private: CBRUSH M_ brush // background brush ...}
Second, the brush is initialized to the desired background color in the constructor of the class.
CMYFORMVIEW:: CMYFORMVIEW () {// Initialize Background Brush. M_brush .createsolidbrush (RGB (0, 0, 255))} Finally, using ClassWizard to process WM_CTLCOLOR messages 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 calls getdlgitem, pass the return value to a cspinbuttonctrl * to call CSPinButtonCtrl:: setPOS function:
BOOL CSampleDialog:: OnInitDialog () {CDialog:: OnInitDialog () // Get pointer to spin button CSpinButtonCtrl * pSpin - (CSpinButtonCtrl *) GetDlgItem (IDC_SPIN) ASSERT _ VALID (pSpin) // Set spin button's default position pSpin -.. > Setpos (10) Return True}
Second, you 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 (false)
(39) How to change the control of the control Since the control is also a window, the user can call CWnd:: setFont Specifies the new font. This function uses a CFont pointer to ensure that the font object cannot be revoked before the control is canceled. The following example will 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:: OnItDialog () {... // Create An 8-Point Arial Font M_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 _QUALITY VARIABLE_PITCH |.. FF_SWISS, _T ( "Arial")) // Set font for push button m_wndButton SetFont (& m _font) ...} (40) how Using OLE_COLOR data types such as ColeControl:: GetfortColor and ColeControl: GetBackColor, in the OLE control: GDI objects, such as pen and brushes, are used by ColorRef data types, calling Colecontrol:: TranslateColor can be easy Change the OLE_COLOR type to the ColorRef type. The following example creates a brush of a current background color:
void CSampleControl:: OnDraw (CDC * pdc const 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 The following example populates 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 rotating button controls look forward to calling CSPINCTRL:: SetRange Settings The range of rotation button controls, the default upper limit of the rotation button control is 0, the default lower limit is 100, which means that the rotation is rotated according to the value of the control 100 becomes 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 button m_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 (idi _ 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 is dynamically created a downstream button control:
.. // In class declaration (.H file) private: CButton * m _pButton // In class implementation (.cpp file) m_pButton = new CButton ASSERT_VALID (m_pButton) m_pButton -> Create (_T ( "Button Title"), WS_CHILD | Ws_visible | BS_PushButton. CRECTTON. CRECT (0, 0, 100, 24), this, IDC _MyButton (47) How to limit the graphics in the edit box If only the user is allowed 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 the editing control to press only the 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 derived class using ClassWizard, followed by specifying a member variable in the dialogue class to call the Edit Control in the OnNitDialog to 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) ...}
Use the classwizard to process the WM_CHAR message, calculate the nchar parameter and determine the operation performed, and the user can determine if the modification is modified, and the character can be configured. The following example shows how to display alphanumeric characters, if the character is alphabetic character, call CWnd onchar, otherwise onchar is not called.
// only Display Alphabetic Dharacters. Void CMYEDIT:: OnChar (uint nchar, uint nrepcnt, UITN nflags) {// determine if nchar is an alphabetic character. If (: ischaralpha (tchar) nchar) CEDIT:: OnChar ( nchar, nrepcnt, nflags)}
If you want to modify the character, you cannot simply 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 Uppercase Void 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)} 1, open CD-ROM
McIndstring ("Set Cdaudio Door Open Wait", NULL, 0, NULL;
Second, close the CD_ROM
McIndstring ("Set Cdaudio Door Closed Wait", NULL, 0, NULL;
Third, turn off the computer
OSVERSIONINFO OsVersionInfo; // data structure contains the operating system version information OsVersionInfo.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); GetVersionEx (& OsVersionInfo); // Get OS version information if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {// Windows98, calls the ExitWindowsEx () Function restarts the computer DWORD DWRESERVED; EXITWINDOWSEX (EWX_REBOOT, DWRESERVED); / / You can change the first parameter, implement some processing programs before using the user, // shut down, turn off the power, etc. //
Fourth, restart the computer
TypeDef Int (Callback * Shutdowndl) (INT); // Displays the pointer hinstance hinst = loading dialog function ("shell32.dll"); // Load shell32.dllshdowndlg shutdowndialog; // Point to the shell32.dll library display The pointer IF (hinst! = Null) {// get the address of the function and calls ShutDowndialog = (Shutdowndialog) (* shutdowndialog) (* shutdowndialog) (* shutdowndialog) (* shutdowndialog) (* shutdowndialog) (* shutdowndialog) (* shutdowndialog) (0);}
Five, enumerate all fonts
LOGFONT lf; lf.lfCharSet = DEFAULT_CHARSET; // Initialize the LOGFONT structurestrcpy (lf.lfFaceName, ""); CClientDC dc (this); // Enumerate the font families :: EnumFontFamiliesEx ((HDC) dc, & lf, (FONTENUMPROC) EnumFontFamProc, (lPARAM) this, 0); // enumeration function int CALLBACK EnumFontFamProc (LPENUMLOGFONT lpelf, LPNEWTEXTMETRIC lpntm, DWORD nFontType, long lparam) {// Create a pointer to the dialog window CDay7Dlg * pWnd = (CDay7Dlg *) lparam ; // add the font name to the list box pwnd-> m_ctlfontlist.addstring (lppelf-> Elflogfont.lffacename); // Return 1 to Continue Font Enumeration Return 1;} // where m_ctlfontlist is a list control variable six, once Just run a program instance, if you have run, exit
IF (FindWindow (NULL, "Program Title")) EXIT (0);
Seven, get the current mouse location
Cpoint Pt; getCursorpos (& PT); // Get position
Eight, context menu event trigger event
ONCONTextMenu event
Nine, display and hidden programs menu
CWND * PWND = AFXGETMAINWND (); if (b_m) // Hide menu {PWND-> setMenu (null); PWND-> DrawMenubar (); b_m = false;} else {cmenu menu; menu.loadmenu (idR_mainframe); display Menu can also change the menu item PWND-> SetMenu (& menu); PWND-> DrawMenuBar (); b_m = true; menu.detach ();}
Ten, get the icon for executable
Hicon Hicon = :: Extracticon (AfxGetInstanceHandle (), _ T ("NOTEPAD.EXE"), 0); if (Hicon && Hicon! = (HICON) -1) {PDC-> Drawicon (10, 10, Hicon);} DESTROYICON (hic);
Eleven, window automatic leaning program demonstration
BOOL AdjustPos (CRect * lpRect) {// automatically aside int iSX = GetSystemMetrics (SM_CXFULLSCREEN); int iSY = GetSystemMetrics (SM_CYFULLSCREEN); RECT rWorkArea; BOOL bResult = SystemParametersInfo (SPI_GETWORKAREA, sizeof (RECT), & rWorkAre a, 0); CRect Rcwa; if (! BRESULT) {// If the call is unsuccessful, use GetSystemMetrics to get the screen area RCWA = CRECT (0, ISX, ISY);} el = lpRect-> left; int = = LPRECT-> TOP; IF (ix
Add a menu item to the system menu to make the following three steps:
First, use the Resource Symbols dialog (select Resource Symbols ... You can display the conveyance in the View menu) Define the menu item ID, which should be greater than 0x0f and less than 0xF000; secondly, call the CWnd :: GetSystemMenu to get the pointer to the system menu and call CWnd :: Appendmenu Adds the menu item to the menu. The following example is added to the system menu two new int CMainFrame :: OnCreate (LPCREATESTRUCT lpCreateStruct) {// ... // Make sure system menu item is in the right range ASSERT (IDM_MYSYSITEM <0xF000);. // Get pointer to system menu . CMenu * pSysMenu = GetSystemMenu (FALSE); ASSERT_VALID (pSysMenu);. // Add a separator and our menu item to system menu CString StrMenuItem (_T ( "New menu item")); pSysMenu-> AppendMenu (MF_SEPARATOR); pSysMenu -> appendmenu (mf_string, idm_mysysIstem, strmenuite); // ...}
Thirteen, run other procedures
1. Run Email or URL
Char szmailaddress [80]; STRCPY (Szmailaddress, "Mailto: Netvc@21cn.com"); Shellexecute (Null, "Open", Szmailaddress, Null, NULL, SW_SHOWNORMAL);
2, run the executable
Winexec ("NOTEPAD.EXE", SW_SHOW); // Run
14. Dynamic increase or delete menu
1, add menu added
CMenu * mainmenu; mainmenu = AFXGETMAINWND () -> getMenu (); // Get the main menu (MainMenu-> GetSubMenu (0)) -> appendmenu (mf_separetor); // Add Division (MainMenu-> getSubmenu (0))) -> appendmenu (mf_string, id_app_about, _t ("always on & top")); // Add new menu item DrawMenubar (); // Heavy painting menu
2. Delete the menu
delete
CMenu * mainmenu; mainmenu = AFXGETMAINWND () -> getMenu (); // Get main menu CString Str; for (int i = (mainmenu-> getSubmenu (0)) -> getMenuItemcount () - 1; i> = 0; I -) // Number of items to get menu. {(MAINMENU-> GetSubMenu (0)) -> getMenustring (i, str, mf_byposition); // copy the label of the specified menu item to the specified buffer. Explanation of MF_BYPosition. IF (str == "always on & top") // If we have just increased menu items, then delete. {(MAINMENU-> GetSubMenu (0)) -> deleteMenu (i, mf_byposition); Break;}} fifteen, changing the application icon static changes:
Modify the icon resource iDR_mainframe. It has two icons, one is 16 * 16, the other is 32 * 32, pay attention to modify together.
Dynamic changes: Send a WM_SETICON message to the main window. The code is as follows:
HiCon Hicon = AFXGETAPP () -> Loadicon; ASSERT (HICON); AFXGETMAINWND () -> SendMessage (WM_SETICON, TRUE, (LPARAM) HICON;
XVI, another way to change the window title
Use statement cWnd * m_pcWnd = AFXGETMAINWND (), then call the setWindowText () function in the following form:
SetWindowText (* m_pcwnd, (lpctstr) m_windowtext); // m_windowText can be a variable of a CString class.
17. Copying image data by enhancement metafile on the clipboard
The following code copies the image data through the meta file to any application,
// It can be placed in a function of CVIEW derived class.
Cmetafiledc * m_pmetadc = new cmetafiled (); m_pmetadc-> createenhacesd (getdc (), null, null, "whatver"); // Draw meta file // do what Ever You Want to do: Bitmaps, Lines, Text ... // close meta file dc and prepare for clipboard; HENHMETAFILE hMF = m_pMetaDC-> CloseEnhanced (); // copy to clipboardOpenClipboard (); EmptyClipboard (); :: SetClipboardData (CF_ENHMETAFILE, hMF); CloseClipboard (); // DeleteMetaFile ( HMF); delete m_pmetad;
Eighteen, the transfer of text data on the clipboard puts the text on the splicing board:
CString source; // put your text in sourceif (OpenClipboard ()) {HGLOBAL clipbuffer; char * buffer; EmptyClipboard (); clipbuffer = GlobalAlloc (GMEM_DDESHARE, source.GetLength () 1); buffer = (char *) GlobalLock ( clipbuffer); strcpy (buffer, LPCSTR (source)); GlobalUnlock (clipbuffer); SetClipboardData (CF_TEXT, clipbuffer); CloseClipboard ();} // get the text from the splice plate: char * buffer; if (OpenClipboard ()) { Buffer = (char *) getClipboardData (cf_text); // Do Something with buffer here // before it goes out of scope} closeclipboard (); 19, capturing screen images to cutting version
void CShowBmpInDlgDlg :: OnCutScreen () {ShowWindow (SW_HIDE); RECT r_bmp = {0,0, :: GetSystemMetrics (SM_CXSCREEN), :: GetSystemMetrics (SM_CYSCREEN)}; HBITMAP hBitmap; hBitmap = CopyScreenToBitmap (& r_bmp); // hWnd is window handles if (OpenClipboard ()) {EmptyClipboard (); SetClipboardData (CF_BITMAP, hBitmap); CloseClipboard ();} ShowWindow (SW_SHOW);} HBITMAP CShowBmpInDlgDlg :: CopyScreenToBitmap (LPRECT lpRect) {// lpRect representative of the selected region { HDC HSCRDC, HMEMDC; / / Screen and Memory Device Description Table HBitmap Hbitmap, Holdbitmap; // Bit 图 INT NX, NY, NX2, NY2; // Selection Area Coordinate INT NWIDTH, NHEIGHT; // Bitmap Width and Height INT XSCRN, YSCRN; // Screen resolution // Make sure the selected area is not empty rectangular IF (ISRECTEMPTY (LPRECT)) Return Null; / / Creating a device description table hscrdc = createdc ("Display", NULL, NULL, NULL); / / Create a compatible memory device description table for the screen device description table hmemdc = createcompatibledc (hscrdc); // Get selected area coordinate nx = lpRect-> left; NY = LP Rect-> Top; NX2 = LPRECT-> Right; NY2 = LPRECT-> BOTTOM; // Get screen resolution xscrn = getDeviceCaps (hscrdc, horzres); YSCRN = getDeviceCaps (HSCRDC, Vertres); // Make sure the selected area is Visible IF (NX <0) Nx = 0; IF (NY <0) NY = 0; IF (Nx2> XSCRN) NX2 = Xscrn; IF (Ny2> YSCRN) NY2 = YSCRN; NWIDTH = Nx2 - NX; NHEight = NY2 - NY; / / Create a bitmap hbitmap = createcompatiblebitmap (hscrdc, nwidth, nHEight), and select the new bitmap = (hbitmap) SelectObject (HbitMap) SelectObject (HbitMap) SelectObject (hmemdc, Hbitmap;
/ / Copy the screen device description table to the memory device description table Bitblt (HMEMDC, 0, 0, NWIDTH, NHEIGHT, HSCRDC, NX, NY, SRCCOPY); // Get the handle of the screen bitmap hbitmap = (hbitmap) SelectObject HMEMDC, Holdbitmap; // Clear DeleteDC (HSCRDC); Deletedc (HMEMDC); // Return Bits Outlet Return HbitMap;}} 20, how to display bitmap scales in the Static control
// Display bitmap void cshowbmpindlgdlg :: showbmpinstaic () {cbitmap hbmpinstaic () {cbitmap hbmpinstaic () {cbitmap hbmpinstaic () {cbitmap hbitmap; // Point PSTATIC * Pstain; pstaic = (cstatic *) getdlgitem (IDC_IMAGE); // Load Resource mm.bmp is my file name, with your replacement hbitmap = (hbitmap) :: loadImage (:: afxgetinstanceHandle (), "mm.bmp", image_bitmap, 0, 0, lr_loadfromfile | lr_createdibsection; hbmp.attach (hbitmap); // get the picture format BITMAP bm; hbmp.GetBitmap (& bm); CDC dcMem; dcMem.CreateCompatibleDC (GetDC ()); CBitmap * poldBitmap = (CBitmap *) dcMem.SelectObject (hbmp); CRect lRect; pStaic -> getClientRect (& LRECT); // Display bitmap pstaic-> getdc () -> stretchblt (limited.wid, limited.top, limited.width (), LRECT.HEIGHT (), & DCMEM, 0, 0, BM. BMWIDTH, BM.BMHEIGHT, SRCCOPY; DCMem.selectObject (& Poldbitmap);