VC entry book by He Zhidan

xiaoxiao2021-03-06  134

This occult starts from the beginning: -------------------- For convenience, for VB -> VC transition! VC entry Yang Zhidan "Targeting object" VC, not a friend of VC. If you have just learned VC, you can look at other articles of this series. "Summary" 1. Establish the simplest VC program 2, DEBUG and RELEASE and switch mode 3, how to back up VC The code "body" is coming, first we write a simplest VC program. 1, enter the VC.2, main menu file-> new.3, choose the MFC AppWizard (exe) in the project, enter the project name (such as Single ) And path. 4, MFC AppWizard -Step 1, choose a single document, other steps by default, directly finish is OK .5, Ctrl F5 run. We can see a simple program, did not add a line of code. I use this as a prototype, simply explain the common problems of VC. 1 Select the CSINGLEVIEW class, right-click, right-click, and Str, in the workspace (left), and fill in the cstring and str. Expand this class, double click SingleView Add Str = "I will vc!", Pay attention to in English. Double-click onDraw (), at the end, add PDC-> TextOut (100, 110, STR), 100 is the horizontal standard, 110 is a longitudinal session. Ctrl F5 View Results. Exercises: Print Ninety-Nine Multiplication Oral Declaration. Tip: INT X1 = 1, X2 = 1; CString Str; Str.Format ("% D *% D =% D", x1, x2, x1 * X2); 2, the menu selection resources, then expand the menu, double-click IDR_MAINFRAME, double-click to view the empty menu item below, enter ID ID_USER, title user. CTRL W, select CSINGLEVIEW in class name, in id Select ID_USER, double-click Command in the message, determine. Double-click the function we just added, add the following code: str = "i can use vc!"; Invalidate (); ctrl f5 look. Exercise: First single Display English when you click on the menu, then display Chinese when you click on the menu. Tip: String (CSTRING class) can be compared to "==". MFC AppWizard's two steps: Step1: What type of application 10 YOU LIKE TO CREATE? (Generate that type of app) 1, Single Document single document Such as Notepad, you can't open two files .2, multiple document multi-document, such as Word.3, Dialog Based based on dialog, such as mine, calculator. Step 6: (Based on dialog box without this step) Base Class Base Category: 1, CView: The most basic view class .2, CEDITVIEW: Automatically generate a simple notebook .3, cfromView: Similar to the dialog, self-belt menu toolbar status bar .4, chtmlview: add a small quantity The code can browse the web. 5, cricheditview: easy to handle the image. 6, CScrollView: Self-band scroll bar. Differently, DEBUG and RELEASE DEBUG is often referred to as debug version, which contains debugging information, and does not make any optimization, easy to make Debugging. Release is called a release version, which has been optimized, making the program in size and running speed so that users can be used well. In fact, Debug and Release have no essential difference. They are just a set of compile options, and the compiler is just a scheduled option action.

We can modify these options through the main menu -> Project-> Setting (Alt F7). Debug and Release Switching: Main Menu -> Build -> SET ACTIVE Configuration How to Back Up VC Code Delete Debug and Release Folders, for convenience Keep the Release version of the executable. Delete file: *. Opt, *. NCB, *. PLG. You can delete files (not recommended): * .dsw, *. CLW. Regeneration * .dsw: Double click * .dsp Regeneration * .clw: Ctrl W Opens the class wizard, select the file, the .vc Getting Started (1) (Menu) menu He Zhidan menu item Properties Description: The only constant of the ID identity menu. The Caption menu item title, "&" The characters behind "&" are shortcuts, and the characters after the menu item will be marked. Separator horizontal line, other properties are invalid. POP_UP has a submenu Grayed invalid, the title is invalid in gray, the title is normal to display Checked when adding a pair of Hook Break to None before the title, making it a line or a column of its brothers or one. Help is only valid for the top-level menu item, so that it and the last top menu later moves to the upper right corner of the window. PROMPT When the mouse pointing to it, the multi-document application generates an IDR_XXXXXTYPE in addition to generating IDR_MAINFRAME, where xxxx is an application name. They correspond to no documentation and documentation, respectively. A menu ID can have a response function in multiple classes, but there will be only one response. I test the results, CChildFrame, CCMenuApp, CCMenuDoc, CCMenuView, CMainFrame (my application called CMenu) in response to the order: in IDR_MAINFRAME in, CMainFrame, CCMenuApp other three do not respond in IDR_XXXXTYPE in, CCMenuView, CCMenuDoc. , Cchildframe, ccMenuapp, cmainframe.ctrl w Open ClassWizard, select the project, class (most common is xxxView), select the menu item we want to modify in the ID. Double-click the Command (or Update_Command_ui) to determine it. In the member function, double-click the function we just added, you can edit the function. When the user clicks on the menu, the function we just edited will execute. If we double-click UPDATA_COMMAND_UI, the response is similar as follows: void ... onupdate ... (ccmdui * pcmdui) {pcmdui-> setcheck (true); // Add a pair of hook pcmdui-> enable before menu item True); // Make the menu item to use} Because this function often affects its shape, it will be performed when its "father" or "grandfather" is selected. Several functions related to the menu in the CWND class. Setmeun (cMenu * Pmenu); Modify the menu of the window, to null, is deleted. Commonly used GetMenu (); GetSystemMenu (); some functions of CMenu. The menu specified by the appendmenu () function is finally attached to a new menu item, and you can specify the relevant case of the menu item, which has two syntax. NFLAG specifies the state, which may be or in combination with one of the following four groups, and can also be added to the MF_POPUP combination to the pop-up menu. MF_CHECKED, MF_CHECKEDMF_DISABED, MF_ENABED, MF_G_G_WARD_STRING, MF_OWNERDRAW, MF_SEPARATOR, MF_BITMAP menu items are string, self-drawn, separated, bitmaps.

MF_MENUBARBREAK, MF_MENUBREAKNIDNEWITEM Specifies the content of the menu item ID.lpsznewItem specifies the content of the menu item, which is related to NFLAG. When MF_OWNERDRAW, this parameter is a data pointer to transmit data, and the system stores the data into the parameter (DrawItemStruct structure) ItemData field when sending a message WM_MeasureItem and WM_DRAWITEM; NFLAG is MF_String This parameter is a menu title. INSERTMENUNFLAGS Specifies the list of menu items and status, and the status option will see the appendmenu () function. If the location option is MF_BYCOMMAND, if the mf_bycommand, the new menu item is inserted before the specified menu item; or MF_BYPOSITION, this parameter specifies the location of the new menu item Insert to -1 in the last. ModifyMenu () parameters are similar to INSERTMENU. DeleteMenu Removes menu item RemoveMenu Removes menu item Settings and Displays Floating Menu Bool TrackPopUpMenu (uint NFLAGS, INT X, INT Y, CWND * PWND, LPCRECT = NULL); NFLAG Floating Menu Coordinate Settings and Mouse Operation Mode, Valid Value As follows: TPM_CENTERALIGN TPM_LEFTALIGN TPM_RIGHTALIGNTPM_LEFTBUTTON TPM_RIGHTPM_LEFTBUTTON TPM_RIGHTBUTTONX, Y Floating Menu Coordinate PWND Specify Operation Menu Window LPRECT Specifies the Mouse Operation Range to pop up the shortcut menu, the method II requires editing a new menu in the resource editor, method The third must have a main menu.

A method: void CHeView :: OnLButtonDown (UINT nFlags, CPoint point) {CMenu PopupMenu; PopupMenu.CreatePopupMenu (); PopupMenu.AppendMenu (MF_STRING, ID_FILE_NEW, "NEW .."); // ... ClientToScreen (& point); PopupMenu.TrackPopupMenu (TPM_CENTERALIGN | TPM_RIGHTBUTTON, point.x, point.y, this); CView :: OnLButtonDown (nFlags, point);} method two: void CHeView :: OnLButtonDown (UINT nFlags, CPoint point) {CMenu menu; menu .LoadMenu (IDR_DUMMY); CMenu * pMenu = menu.GetSubMenu (0); ASSERT (pMenu = NULL!); ClientToScreen (& point); pMenu-> TrackPopupMenu (TPM_CENTERALIGN | TPM_RIGHTBUTTON, point.x, point.y, this); CView :: ONLBUTTONDOWN (NFLAGS, POINT);} Method 3: Void Cheview :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT POINT) {CWND * PWND = AFXGetApp () -> getMainWnd (); cmenu * pmenu = pwnd-> getMenu () PMENU = PMENU-> GetSubmenu (0); Assert (Pmenu! = Null); ClientToscreen (& Point); Pmenu-> TrackPopupmenu (TPM_CENTERALIGN | TPM_RightButton, Point.x, Point.y, this);} Exercise: Dynamic menu, Users click "More Menu" to add some menu items.

In fact, the principle of self-painting menu is not difficult to understand. The style of it is selected to be self-painted, and the information (pointer) of the self-painted use is forced to LPCTSTR, and the DrawItem will be overloaded, pay attention to the information of the self-drawn use. Example is as follows: CownerMenu. h in the class CMenuItem {public: CString m_szText; COLORREF m_color; CMenuItem (CString szText, COLORREF color) {m_szText = szText; m_color = color;}}; # include class COwnerMenu: public CMenu {public: void DrawItem (lPDRAWITEMSTRUCT lpDrawItemStruct); bool AppendMenu (UINT nIDNewItem, CString caption, COLORREF color); COwnerMenu (); CTypedPtrList m_MenuList; virtual ~ COwnerMenu ();}; COwnerMenu.cpp in COwnerMenu :: ~ COwnerMenu () {while (m_MenuList.GetCount ()) {CMenuItem * pMenuItem = m_MenuList.GetHead (); delete pMenuItem; m_MenuList.RemoveHead ();}} bool COwnerMenu :: AppendMenu (UINT nIDNewItem, CString caption, COLORREF color) {CMenuItem * pMenuItem = new CMenuItem (caption, color); m_MenuList.AddTail (pMenuItem); return CMenu :: AppendMenu (pMenuItem MF_OWNERDRAW, nIDNewItem, (LPCTSTR));} void COwnerMenu :: DrawItem (lPDRAWITEMSTRUCT lpDrawItemStruct) {CDC * pDC = CDC :: FR omHandle (lpDrawItemStruct-> hDC); pDC-> SetTextColor (((CMenuItem *) lpDrawItemStruct-> itemData) -> m_color); pDC-> TextOut (0,0, ((CMenuItem *) lpDrawItemStruct-> itemData) -> m_szText );} In the use of menus (don't forget to add files): Void cownermenuview :: OnRButtondown (uint nflags, cpoint point) {cownermenu menu; menu.createpopupnu (); menu.Appendmenu (ID_1, "1", RGB (0, 0, 128); ClientToscreen (& Point); Menu.TrackPopupmenu (TPM_LEFTBUTTON | TPM_LEFTALIGN, POINT.X, POINT.Y, THIS); CView :: OnRbuttondown (NFLAGS, POINT);} VC Getting Started He Zhi Dan's main content: 1. Implementation of the main function 2, common functions 3. CSTRING and CHAR [] Mutual conversion 4, put null bytes in cstring, the most important function is not easy to understand.

CString :: CString (CHAR * P) {INT N = Strlen (p); m_data = new char [n 1]; strcpy (m_data, p);} cstring :: cstring (cstract & other) {int n = strlen Other.m_data); m_data = new char [n 1]; struct (m_data, other.m_data);} cstring & cstring :: operator = (cstring & other) {delete [] m_data; int n = strlen (Other.m_data) ; M_data = new char [n 1]; strcpy (m_data, other.m_data); return * this;} string :: ~ string () {delete [] m_data;} collate, Compare with a character long pointer finger String comparison, the same as strCMP, the difference is that _TCSCOLL, _TCSICMP is called separately. DeleteInt Delete (int NINDEX, INT NCOUNT = 1) The return value is the length of the string before being deleted, NINDEX is the first deleted character, Ncount is a delete several characters. According to my experiment: When the length of the NCOUNT> string is wrong, this function is not executed when Ncount is too large. When there is not enough character deletion, this function is not executed. FINDONEOFINT FINDONEOF (LPCTSTR LPSZCHARSET) Const; This function is the function of finding any of the LPSzCharset, and then returns the position, and does not find the return 0. Such as: cstring str = "0123456789"; int x = str.findoneOf ("31"); X value is 1. Findint Find (Tchar CH) const; int find (tchar ch, int nstart) const; int find (lpctstr pstr, int nStart) const; return value to the serial number, CH to be searched , Lpszsub's character string to be searched, NSTART starts searching. Such as: cstring str. "0123456789"; int x = str.find ("34", 4); the return value is -1. Getat tchar getat (int NINDEX) const; Return the character of Nindex, you can put characters The string is understood as an array, Getat is similar to []. Note Nindex range, if not suitable, there will be debug errors. INSERTITINT INSERT (INT NINDEX, TCHAR CH) INT INSERT (INT NINDEX, LPCTSTR PSTR) Returns the modified length, NINDEX characters (or string) inserted into the label. Leftcstring Left (int ncount) const; returned ahead NCOUNT character.

Right and Left similar MakeLower, MakeUpper MakeReverse case of changing the character of an inverted character, such as: CString str = "X0123456789"; str.MakeReverse (); str becomes "9876543210X" = const CString & operator = (const CString & string); Const CSTRING & OPERATOR = (tchar ch); Const CSTRING & OPERATOR = (LPCTSTR LPSZ); merge parameters to yourself. Such as: cstring str = "0123456789"; str = "ha"; str 0123456789ha "; str [] tchar operator [] (int NINDEX) const; like processing a character array to process strings. Note that it is read-only. CString str = "0123456789"; STR [0] = 'x'; is wrong.

TrimLeft, TrimRightvoid TrimLeft (); void CString :: TrimLeft (TCHAR chTarget); void CString :: TrimLeft (LPCTSTR lpszTargets); void TrimRight (); void CString :: TrimRight (TCHAR chTarget); void CString :: TrimRight (LPCTSTR lpszTargets ); Cstring str = "/ n / t a"; str.trimleft (); str.trimleft (); STR is "a"; if there is no parameters, from left to delete characters (/ N / T space, etc.), to encounter a non-such class Character. Of course, you can also specify to delete those characters. If the specified parameter is a string, then a character in these characters will delete .cstring str = "abbcadbabcadb"; str.trimleft ("ab"); result "CadbabCADB"); result "CADBABCADB" int CString :: remove (tchar ch); CH deleted characters. Returns the number of deleted characters, there are multiple times of conversion. CString and char []. CHAR STR [100] = "str"; CString SSTR = "SSTR"; str.format ("% s", str); str = lpctstr sstr; struct (str, (lpctstr) SSTR); if it is assignment, you want: cstring s (_t (_t ("this is a test" )); LPTSTR P = s.getBuffer (); // Add the code IF (P! = Null) * p = _t ('/ 0'); s.RELEASEBUFFER (); // Timely release so that the value of other CString member functions Str is used. Put the null byte 1, CString STR ("ABC / 0" DEF ", 7); Str =" g "; int NLENGTH = Str.getLength (); NLENGTH is 8.2, CString Str ("My Name Is Hedan!"); str.sett (5, 0); int NLENGTH = Str.getLength (); Note: Not all CString member functions Can, Be careful when using it. Example: dynamic configuration data source CString strDsn, strDBQ; strDsn = "DSN = test"; strDBQ.Format ( "DBQ =% s", strSourceMDBName); CString strConnect = strDsn "" strDBQ; strConnect.SetAt (strDsn.GetLength (), '/ 0'); SQLConfigDataSource (NULL, ODBC_ADD_SYS_DSN, "Microsoft Access Driver (* .mdb)", StrConnect); VC Getting Started 4 (Common Control) Common Control He Zhi Dan Main Content: 1, button (1), Bitmap button and dynamic button (2), self-drawn button 2, list box 3, editing controls and crichedit4, the CSLIDERCTRL button is very simple, dragging one to the dialog, double-click it to edit the code.

Using the Program Wizard into a dialog-based program control, dragging a button on the dialog box, ID is IDC_OWNER, double-click the control to add a response function. Set the associated variable m_ok for IDOK, add the following code to the response function. m_ok.enableWindow (false); its role is to disable OK. Change the code just added to the following, Ctrl F5, click our plus button to see the determination button to turn the check box, let's click it, it executes the previous code. UINT Style = m_ok.GetButtonStyle (); Style | = BS_3STATE; m_ok.SetButtonStyle (Style); style is: BS_AUTOCHECKBOX BS_AUTORADIOBUTTON BS_AUTO3STATE BS_CHECKBOX BS_DEFPUSHBUTTON BS_GROUPBOX BS_LEFTTEXT BS_OWNERDRAW BS_PUSHBUTTON BS_RADIOBUTTON BS_3STATE will just add code into the following: CWnd * pWnd = GetDlgItem (IDOK); PWND-> EnableWindow (false); its effect is also disabled, the role of the first line is based on the ID, note that some functions are unique, then I have to force the PWND to force conversion Class CButton pointer. The CButton commonly used functions are: .Getfocus (); get a window with focus, setfocus (); get focus. If a button has focus, space can make it execute. Getfont (); setFont (); get and set fonts. Bitmap button. On the self-drawing style hook of the determined button, the title of the determination button is changed to OK, plus four bitmaps, "Oku", "Okd", "OKF", "Okx", and bounce with the button, pressed , Get focus, disabled, pay attention to the name of the bit. Define a member variable CBitmapButton BB, add bb.autoload (iDok, this) in OnInitDialog (); there is a question to note that the default button will be canceled when you click on the point, so you have to reset a default button. Change the above sentence to: bb.LoadBitmaps ("OKU"); // You can load up to 4, at least one. bb.subclassdlgitem (IDOK, this); // is associated with the control. Bb.sizeToContent (); // Change the size of the control to adapt the bitmap self-drawing button: On the self-portrait hook of the cancel button, Ctrl W open the class wizard, double-click the response function of the CControlDLG message WM_DRAWITEM. void CControlsDlg :: OnDrawItem (int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) {if (IDCANCEL == nIDCtl) {CDC * pDC = new CDC (); pDC-> Attach (lpDrawItemStruct-> hDC); pDC-> TextOut (10,10, "Haha");} cdialog :: OndrawItem (Nidctl, lpdrawitemstruct);} Alternate function CRECT R; getClientRect (& r); r stores the boundary value of the cancel button.

The list box creates a dialog-based program control, add a list box, ID: IDC_LIST, set a control type of variable m_ctrl, add three buttons, ID, INSERT, DELETE; void ccontrolsdlg :: onappend ( ) {Updatedata (); if (m_input.isempty ()) Return; INT i = m_ctrl.getCount (); m_ctrl.setcurseel (i-1); // Select the last one; m_ctrl.addstring (m_input);} void ccontrolsdlg :: OnSERT () {INT i = m_ctrl.getcurseel (); if (-1 == i) MessageBox ("Please select an item in the list box, the new item will be behind this", "Note" ); Else {updatedata (); m_ctrl.insertstring (i 1, m_input);}} void ccontrolsdlg :: onremove () {INT i = m_ctrl.getcursel (); if (-1! = I) m_ctrl.deleteString ( i);} Common function: resetContent is emptied. INT FINDSTRING (INT NSTATAFTER, LPCTSTSTARTSTARTERTER) Const; starts looking for the string referred to by LPSZITEM from NSTARTAFTER, if the return -1 is not found, otherwise return the serial number. INT SelectString (INT NSTARTAFTER, LPCTSTSTR LPSZITEM); Similar to FINDSTRING, find the found string after finding it. Edit Control: Generate a dialog-based program controls, add an editing control, set an associated variable m_ctrl of a control type. Add a button, double-click Code: m_ctrl.setsel (0, 3); // Select the first 4 characters . M_ctrl.cut (); // Cut m_ctrl.paste (); // Paste m_ctrl.paste (); // Paste similar functions There are undo, copy, replacesel. Void MoveWindow (int X, int y, int nwidth, int nHEight, Bool Brepaint = true); Void MoveWindow (LPCRect LPRECT, BOOL BREPAINT = true); mobile window (such as control). The last parameter is heavy, the front parameters indicate the position of the four corners, pay attention to the size and proportion possible may change. Build a dialog-based application Control, add a CRICHEDIT CTRL F5, and there should be no reactions. Because we didn't add: bool ccontrolsapp :: initInstance () {afxinitrichedit (); this way.

CSLIDERCTRL generates a dialog-based application controls, plus a slider control, allowing it to be associated with a shaping variable m_value, let it associate the NM_RELEASEDCAPTURE of this control with a control type of variable m_ctrl, where to add: Void ccontrolsdlg :: OnReleaseDcaptureSlider1 (NMHDR * PNMHDR, LRESULT * PRESULT) {Updatedata (TRUE); CSTRING STR; Str.Format; MessageBox (STR); * PRESULT = 0;} plus: m_ctrl.setRange (20, 120); // Set the smallest, maximum M_Ctrl.SetPageSize (30); // Set how much M_Ctrl.SETPOS (30); // Setting position VC Getting Started Collection Five (dialog) Dialog Box He Zhi Dan main Content: 1. Establish a mode dialog and a mode dialog 2, the controls and focus settings 3, Example 4, General Dialog 5, and Common Functions Dialogs can be divided into "model" and "no" according to its action mode. Mode "two categories. For the Mode dialog box, the user cannot do other work before the dialog is turned off. There is no mode dialog, and it still remains on the screen while the user can work in other windows of the application. Build a dialog-based program Dialog. Insert a dialog box in the Explorer, Ctrl W Create a Class CownerDiaog; add a button in IDD_DIALOG_DIALOG to double-click on its editing code. Void cdialogdlg :: onbutton1 () {COWNERDIALOG DLG; DLG.DOMODAL ();} Don't forget #include "OwnerDialog.h". You don't close it, you can't get the command to the main dialog, but you can still open other programs. We delete the code just added. Void cdialogdlg :: onbutton1 () {cownerDialog * pdlg = new cownerDialog (); pdlg-> create (IDD_DIALOG1); PDLG-> showWindow (sw_restore);} This is a non-Mode dialog box, you can proceed before the sub-dialog , Issue commands to the master dialog. Note If you turn off the master dialog, the sub-dialog is also closed. There are four functions in layout to be very useful, Tab ORDER (Shortcut Ctrl D): Click the button in turn to determine their focus order. In this way, when the user is switched on the focus, the sequence of the control is to be set. For example, a dialog box wants us to enter the username, the mouth is printed, then press OK. We set their focus order to 1, 2, 3, so that users entered the username, then press Tab, enter the mouth, enter the car. Layout Align Tap the selected control to align the Layout Space Evenly average allocated control Layout make Same size to make the selected control size of the selected control, the program randomly generates a x, user input y = x * X, the value, the program checks the right error, if it is wrong, it will be corrected.

Generate a dialog-based application, remove "TODO: Settings Control here", this static control is not used. Join the two editing controls (if the control is mostly changed to an easy understanding ID), Ctrl W associates two controls with two shaping variables m_x, m_y (naming to be easily understood). Add a button, ID is changed to IDC_CHECK, double-click its editing code. Void ccheckdlg :: oncheck () {updata (); if (m_y == m_x * m_x) MessageBox ("you are right); else {m_y = m_x * m_x; updatedata (false); messagebox (" think about the results ");}} Find constructor (preferably ininitdialog () processing), find m_x = 0; change to CTIME T = CTIME :: getCurrentTime (); int n = t.GetSecond (); for (int i = 0; i

ShowWindow (SW_HIDE); its parameters can also be: SW_HIDE SW_MINIMIZE SW_RESTORE SW_SHOWMAXIMIZED SW_SHOWMINIMIZED SW_SHOWMINNOACTIVE SW_SHOWNA SW_SHOWNOACTIVATE SW_SHOWNORMAL vc Starter Collection six (multi-threaded) multithreaded He Zhidan main elements: 1, the worker thread 2, 3 user interface thread, the thread is synchronized Divided into workers threads and user user interface threads. The thread of the user interface is that it has a separate message queue that can have its own window interface that can be reacted for user input and events. A worker thread can be created with the following methods. Uint mythreadproc (lpvoid pParam) {...} AFXBEGINTHREAD (Mythread, ..); it has six parameters, the first one is the control function, the second to transmit the thread to the entry parameters of the control function, the current thread priority , The size of the current thread, the current thread creation status, security attribute, and the latter four have default. User interface thread: First use the application wizard to establish a single document program Thread, then establish Thread1: Public CFrameWnd, Frame1: Public CFrameWnd, you can use Ctrl W to establish these two new classes. Add a pointer Thread1 * pthread1 in cthreadapp, in Bool Cthreadapp :: InitInstance (), initialization: pthread1 = new thread1 (); pthread1-> createthread (); modify Thread1 constructor to public. Add a pointer Frame1 * m_pwnd in Thread1, then initialize. Bool Thread1 :: InitInstance () {m_pwnd = new frame1 (); return true;} Change the frame1 constructor to the public, containing #include "frame1.h" in thread.h. Edit a menu idR_Menu in the resource editor, it has a menu item id_begin. Frame1 :: frame1 () {create (null, "demo"); showwindow; updateWindow (); cmenu menu; // can use local variables, because it will not be used, plus menu. Menu.LoadMenu (IDR_MENU); SetMenu (& Menu);} One difficulty in synchronous multi-thread is the coordination of each thread. The same method opens a thread in CTHREADAPP. Bool cthreadapp :: initInstance () {. . . . . . Pthread1 = new thread1 (); pthread1-> createthread (); pthread2 = new thread1 (); pthread2-> createthread (); . . . . . } The menu in iDR_Menu sets a response function in Frame1, and the method is also Ctrl W Open the class wizard.

And define a global plastic variable n in Frame1, the initial value is 0.Handle Handle = CreateSemaphore (NULL, 0, 1, "HE"); WaitForsingleObject (Handle, 10000); CSTRING STR; N ; str.Format (" % D Tasting ", N); MessageBox (STR); ReleaseSemaphore (Handle, 1, Null); When you click on Frame1 menu, a dialog box will pop up, do not point it to you, click another thread menu, temporarily Will not pop up the dialog box, determine the dialog box, and another thread's dialog box is also played. This synchronization method is called a semaphore. It allows limited threads to access a shared system resource, using counters to implement semaphore. Handle CreateSemaphore (LPSecurity_Attributes LPA, LONG CSEMINIAL, long csemmax, lptsr lpszsemname); The first parameter indicates whether the created object can be inherited by its sub-process. If you want to share this signal between all sub-processes, you can set it to True, or you can directly set it to null to use the default security settings second parameters to make several threads. The third parameter is up to several threads. The last parameter is the name of the semaphore, and the string is used as a parameter when calling createMapphone () or OpenSemaphore () in other processes. Signal handle can be obtained. ReleaseSemaphore (Handle HSemaphore, Long Crelease, LPLONG PLPREV) Second Representation A few release, VC Getting Started Column 7 (Toolbar) Toolbar He Zhidan Main Content: 1, Summary. 2, common functions 3, instances. 4, dynamically establish the toolbar 5, in the toolbar, the control 6, use the dialog box to set the chart button toolbar We can click Right click on the Toolbar of the Resource Editor, select Insert Toolbar, select a toolbar, after On the right, double-click on it to edit it. We can use graphics tools and color box to paint its appearance, its properties have an ID, long, width and mouse pointing to it. General CToolBar definitions in CMAINFRAME, in fact, is now completed in the CMAINFRAME oncreate function.

(!! M_wndToolBar.CreateEx (this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || m_wndToolBar.LoadToolBar (IDR_MAINFRAME)) if {TRACE0 ( "Failed to create toolbar / n"); return - 1; // fail to create} m_wndToolBar.EnableDocking (CBRS_ALIGN_ANY); EnableDocking (CBRS_ALIGN_ANY); DockControlBar (& m_wndToolBar); Bool Create (CWnd * pParentWnd, DWORD dwStu; e = WS_CHILD | WS_VISIBLE | CBRS_TOP, UINT nID = AFX_IDW_TOOLBAR); pParentWnd Specify the version of the window. DWStyle Specifies Toolbar Style CBRS_TOP Allow Toolbar in the top of the frame window.

CBRS_BOTTOM allow the toolbar to the bottom of the frame window, the parent window after changing the size CBRS_NOALIGN toolbar toolbar displays the same position CBRS_TOOLTIPS tooltip CBRS_SIZE_DYNAMIC tool Koda dynamic toolbar CBRS_SIZE_FIXED fixed CBRS_FLOATING toolbar is floating from the command when the mouse button CBRS_FLYBY When you are brushing, the CBRS_HIDE_INPLACE button is not visible to the user's style or spacer or a set of buttons, or the button's style determines the appearance of the button and the user's reaction method. void SetButtonStyle (int nIndex, UINT nStyle); nIndex specified toolbar button or index number of standard buttons .nStyle TBBS_BUTTON interval, this default value as the start flag TBBS_CHECKGROUP TBBS_SEPARATOR spacer TBBS_CHECKBOX automatic confirmation flag area TBBS_GROUP a set of buttons for a Group Parts Enabledocking Functions and CFRameWnd classes of the CFRameWnd class, the setup toolbar, setting the toolbar .void EANBLEDOCKING (DWORD DWSTYLE) CBRS_ALIGN_TOP Allow toolbars on the client area CBRS_ARIGN_BOTTOM Allow toolbar at the lower side of the room area CBRS_ALIGN_LEFT Allow toolbar on the left side of the client area CBRS_ALIGN_RIGHT Allow toolbar on the right side of the client area CBRS_ALIGN_ANY Allow toolbar at any position in the customer area CBRS_FLOAT_MULTI allows multiple controls Bar floating in a mini frame window Floating Void DockControlbar (....) PBAR To float control bar pointer. Represents the location that allows floating, or is not allowed to float, can be combined by the following value: AFX_IDW_DOCKBAR_TOP control bar placed On the upper side of the frame window; the AFX_IDW_DOCKBAR_BOTTOM control bar is placed on the frame window The AFX_IDW_DOCKBAR_LEFT control bar is placed on the left side of the frame window. When the standard mouse is released,

The command button will "pop up", if we want the command button to stay in the pressed state, you can set the style of the command button to a confirmation box. In the ON_UPDATE_COMMAND_UI message handler, use the setCheck () member function and the setradio () member function to change the button status. SetCheck () parameter 0 indicates that the delete state is deleted, 1 indicates the confirmation state, 2 indicates that the parameter 0 of the case where the setRADIO () indicates the delete state, and Non 0 indicates the confirmation state. We build a single document program with the application wizard, add a button in the toolbar. The ID is set to ID_TIME. Add a Booler data type m_btime to the CMAINFRAME class, the initial value is false.ctrl w Add id_time ON_COMMANDT and ON_UPDATE_COMMAND_U message response function. Void cmainframe :: onshowtime () {m_btime =! m_btime;} void cmainframe :: onupdateshowtime (ccmdui * pcmdui) {pcmdui -> setCheck (m_btime);} If there is a menu of the same ID, it will automatically according to the situation of the button Hook hook. In fact, we can build a toolbar without Toolbar resources. Code is as follows: UINT nID [] = {ID_FILE_NEW, ID_FILE_OPEN, ID_TIME}; m_wndToolBar.Create (this); m_wndToolBar.LoadBitmap (IDB_BITMAP1); m_wndToolBar.SetButtons (nID, sizeof (nID) / sizeof (UINT)); wherein the bitmap The size should be appropriate, otherwise it will affect the beauty, the last line makes several IDs and related toolbars and related. If you want to set the style of each button, you can add: m_wndtoolbar.setButtonStyle (1, TBBS_SEPARATOR); m_wndtoolbar.create (this); m_wndtoolbar.loadbitmap (idb_bitmap1); m_wndtoolbar.setButtons (NULL, 3); m_wndtoolbar.setButtonInfo (0, ID_FILE_NEW, TBBS_BUTTON, 0); m_wndtoolbar.setButtonInInfo (1, ID_FILE_OPEN, TBBS_BUTTON, 2); Embed a control in the toolbar, such as editing box 1, define an editing control object, can not be a local variable, otherwise Will be released. 2, call CREATE, the only thing to note is that the location is to be on the site of the toolbar. CRECT RECT; M_WNDTOOLBAR.GETITEMRECT (1, & Rect); Edit.create (WS_CHILD | WS_VISIBLE, RECT, & M_WNDTOOLBAR, ID_EDIT); add the chart button with the dialog box for toolbar. Insert a dialog, Styles' style is set to Child, Border is set to None. In CMAINFRAME, M_WndToolbar is changed to cdialogbar, and add a cbitmapButton BB; change the sentence to the establishment toolbar to: m_wndtoolbar.create (this, IDd_dialog1, WS_CHILD | WS_VISIBLE | CBRS_TOP, AFX_IDW_STATUS_BAR); the last ID is determined with himself. Ctrl F5, an extremely unestictable toolbar is coming out.

To finish the button, their processing functions are still Ctrl W. Hook on the Owner Drawer and Bitmap of the Button Styles. Add a sentence in the place just now. bb.autoload (idc_button1, & m_wndtoolbar); note that you need to add three bitmaps (one can also). As your button is named X, the names of the just three bitmaps are "xup", "xdown", "xfocus", shortly called "Xu", "XD", "XF". VC Getting Started Collection Eight (Basic Operation) Basic Operation He Zhi Dan Main Content: Workspace (ClassView, ResolyView, FileView) Menu App Wizard Class Wizard (Class Wizard) Standard Control Common debugging method VC window is divided into three parts, the body window (upper right corner), Work window (left), output window (bottom). Work window has three labels, classview, resoreceview, fileview; click " ", "-" open folder; for the folder or file that does not open, double-click to open; for the open folder double-click close. Double-click the class name in ClassView, the Text window display class definition, double-click the member variable to view the definition, double click on the function to enter the function. Right-click on the function name, two functions are more practical: Calls, Called By. Right-click the class name, two features are very valuable: increase the member variable, add member functions. Common Menu: Edit-> Advanced / Format Selection Alt F8 Conges the selected object Edit-> Advanced / Make Selection Uppercase Ctrl Shift U Turn the selected part to the uppercase Edit-> Advanced / Make Selection LowerCase Ctrl U Checking some of the three menus whose lowercase EDIT does not have much practical value, because if you want to view a member of a class, you can use the classname ::, you will list the member, you only need to start the beginning of the space (or Other non-identifier characters) can be used to automatically match the first eligible member. When you finish the function name, when you correct parentheses, you will display the information, including comments on the function definition of the same line. View-> ClassWizard Ctrl W Editing the class View-> DebugWindow Ctrl F10 in the application, runs to the cursor, and its child can be used. The Debug menu is basically used, set Active Configuration, setting the Debug mode or Release mode. #ifdef _debug # Endif This macro definition is not executed in the Release mode. Tool-> Customize-> Toolbars definition toolbar AppWizard has a few steps, only the first, second, and final step more important.

The first step selection: MFC a Ppwizard (EXE); Step 2: Single Document Single document MULTIPLE Document Multi-Document Dialog Basede Based on dialog Based on the last step (Based on dialog): base class: Select the base class of the view class, The difference is more obvious, and everyone will try it. Application Guide automatically generates an application class, document module class, framework class, document class, and view class. Most of the simple program is in the view class. When the data is more complicated, the document class is used. Ctrl W Open ClassWizard This dialog box contains the following tabs. 1, Message Maps tab: Connection between the management message and the member function. 2, MEMBER VARIABLES tab: Use the user to join or delete member variables (associated with the control). 3, Automation tab: Provide a variety of features to support Automation, allow users to easily delete Automation properties and methods. 4, Active Events tab: Provide a variety of features to support ActiveX, allowing users to easily delete properties and response functions. 5, Class Info tab: Display information, allows users to create new classes to support dialogs and formatted views. Message Maps1 Projcect Engineering, generally does not have to be modified because only one is generally only one. 2, Class Name class name 3, Object IDs lists the ID number of the currently selected object, including menu items, dialog controls, etc. that can generate messages. 4, Message lists the current items of the current item selected in the Object IDS box and the MFC function that can be rewritten. Double-click the message equivalent to addFunction.5, the Member Functions list box lists all member functions included in the Class Name box current class. Labeling V is virtual function, and the WINDOWS message is marked. MEMBER VARIABLES tab: Double-click ID, pop-up Add member Variable dialog: Category has two options, values, control, each control can be associated with a value type data, and can also be associated with a control type data. When you edit a dialog, there will be more toolbars, there are many standard controls. If you accidentally turn it off, right-click on the blank of the standard toolbar, such as the right side of the menu, hook the Controls. There are two ways to add a control to the dialog: 1, drag directly to the dialog. 2. Click on a control and draw it on the dialog box. The most commonly used methods of debugging, if we doubt a problem with a plastic variable X, you can: 1, cstring str; str.format ("% d", x); // and printf very similar MessageBox (STR); Advantages: Point determination The procedure will continue to run. Disadvantages: If there is too much time, it is too wasteful and keyboard. 2, CTRL F10 runs to the cursor, enter X in the Watch window, and the value will be displayed later. Advantages: Simple, you can view all values. Disadvantages: It is not possible to see the case where the second run is here. 3, #ifdef _debug AFXDUMP << x; #ENDIF Display the result in Output, cannot be in the Release state. Ctrl f5 seems to be invalid, F5 can.

AFXDUMP.SETDEPTH (1); Set the depth, such as Maps, Arrays, which only plays a few element, we use this function, it will play all the content. # idf _debug char TEST [] = "0123456789 / N "; AFXDUMP.HEXDUMP (" - ", (byte *) TEST, 11, 6); # Endif results: - 30 31 32 33 34 35 - 36 37 38 39 0A first parameters, line First head character. Second parameter, content to be played. The third parameter, the number of elements to play. The fourth parameter, the number of each line. 4, trace (...), trace0, trace1 TRACE2, TRACE3 can only be used to pay attention to the string when debugging, including the end character, no more than 512 characters .5. After the F9 sets the breakpoint in the debug state, F5 to the next breakpoint The next line of F10, the F11 enters functions (including system functions), SHIFT F11 out. After the F5, the debug menu has the corresponding menu item. F5, View-> Debug Window's child item is more useful .Watch View you specified Variable Variables Display Auot variable, local variable, THIS Memory display Specify memory address stored Value Call Stack Display Function Call Relationship REGISTERS Register DISABBLEMBLE assembly code actually under Release F5alt F7 project set C / C generate Browse INFO selection. Debug info selection PROGAME DATABASE for Edit and Continuelink Generate Debug Info Select Link Incrementally to select VC Getting Started (9) Collecting Class User Hardware He Zhi Dan MFC provides collection class (Collect) Specially responsible for data object storage and management, MFC The set class is divided into three categories, which are used to handle the data structure of three types of different properties: table (List, a double-linked list similar to data structure), array (array) and mapping (MAP, with a function similar to a dictionary). One Array uses an experience prototype: Template Class Carray: public cobject Simply said that when you entered, use the arg_type class, output Use TYPE to automatically implement conversion. Specific implementation can see C: / Program files / Microsoft Visual Studio / VC98 / MFC / include / AFXTempl.h. Such as: #include "AfxTempl.h" // That class requires those headers to view MSDN, the final carray vars; vars.set (0, 'a'); int x = vars.getat (0); INT x = VARS.GETAT (0); this nature is self The definition class is more efficient, because I can control the modification process by overloading "=". Set breakpoints, we will find that this class has three class members: m_nsize, m_nmaxsize, m_ngrowby, respectively correspond to the number of elements, has been opened When there is insufficient space, how many elements of each element are opened, a common function: int getSize () Const gets the value of m_nsize .int getupperbound () const; array Upload, m_nsize-1.void setsize (int nnewsize, INT ngrowby = -1); three class members will change, the previous content is not necessarily lost .void freeextra (); sorting extra space, make m_nmaxsize = m_nsize.void removEall (); delete all elements .Type Getat (int) NINDEX) Const; gets the value of the nindex (starting from 0) element .void setat (int NINDEX, ARG_TYPE NEWELEMENT);

NINDEX can not be crossed. Const type * getdata () const; return the data pointer; INT NINDEX, ARG_TYPE NEWELEMENT; and SETAT, if too big, will open a new space .int add (arg_type newelement); add an element , M_NSize plus one .int append (const carray & src); // plus one of the same type of array .void Insertat (int NINDEX, Arg_Type NewElement, int ncount = 1); Void Insert (int NStartIndex, Carray * PNewArray); Type & Operator [] (int NINDEX); with C-style operators. Type Operator [] (int Nindex) const; other arrays: CByteArray support byte arrays. CWordArray supports word array. CDwordArray supports double-byage-based group. CoBarray supports COJECT Types Pointer array. CPTRARRAY supports Void type pointer array. CuintArray supports unsigned shaping arrays. CStringArray supports the CString array. Usage is basically consistent with the above. I use CSTRINGLIST as an example, talk about the experience of using the table. Note: View MSDN In fact, it is actually coblist. Pay attention to the corresponding type to change to the CString class. Of course, there are some small differences. Specifically see the VC_Assist6. The following example is almost all functions of this class. CStringList var ( 15); position = var.insertafter (null, "item1"); position = var.insertafter (position, "item3"); position = var.insertbefore (position, "item2"); For (position = var.getheadPosition (); null! = position;) AFXMESSAGEBOX (VAR.GetNext (position)); for (position = var.gettailposition); null! = position; var.getprev (position)) {cstring Str; str = var.getat (position); if ("Item3 == Str) {var.removeat (position);} else {str.makeupper (); var.sett (position, str);}} var. REMOVEHEAD (); var.removetail ();

Var.removeall (); var.addhead ("he"); var.addtail ("dan"); position = var.find ("h"); var.sett (position, "he"); position = var. FindIndex (1); var.set (Position, "DAN"); // End The following is an introduction to this class function.position insertbefore (position position, cobject * new insertfter (position position, cobject * newElement); Insert a new element before or after a position. Position getHeadPosition () const; position gettailposition () const; get header location and tail position .cObject * & getnext (position & rposition); cobject * getnext (position & rposition) const; cobject * & GetPrev (Position & RPSITION); COBJECT * GETPREV (Position & RPSITION) Const; gets the rear element or the previous element, pay attention to RPSITION will change .cObject * & getat (position position); cobject * getat (position position) const; Element .void sett (position pos, cobject * new); set element. Void Removeat; Delete element according to location. COBJECT * REMOVEHEAD (); delete and return to head element COBJECT * REMOVETAIL (); delete and return Tail element posient addhead (cobject * newElement); increase head element void addhead (coblist * p Newlist); add a table Position AddTail (COBJECT * NEWELEMENT); increasing tail elements void addtail (coblist * pnewlist); add a table Position Find (COBJECT * SearchValue, position startafter = null) Const Depending on element value .Position Findex (int NINDEX) Const According to the index, find a location, the paragraph (10) message He Zhi Dan PretranslateMessage function, is the name of the message, before the message is translated, we can block a key or a command. Below is some commonly used Information about messages. These information is placed in PMSG .WM_keyDown nVirtkey = (int) wparam; / * virtual key value, and ASCLL code has many identical places * / lkeydata = lparam; / * and hardware related * / wm_char chcharcode = Tchar) WPARAM; LKEYDATA = LPARAM; WM_COMMAND WNOTIFYCODE = HiWord (WPARAM); WID = Loword (WPARAM); hwndctl = (hwnd) LPARAM; WM_LBUTTONDOWN FWKEYS =

wParam; // xPos = LOWORD (lParam); // mouse abscissa yPos = HIWORD (lParam); // mouse ordinate fwKeys MK_CONTROL MK_LBUTTON MK_MBUTTON MK_RBUTTON MK_SHIFT WM_MOUSEMOVE fwKeys = wParam; xPos = LOWORD (lParam); yPos = HIWORD ( LPARAM); The following example demonstrates the common usage of PretranslateMessage. Bool cpretranslatedlg :: PretranslateMessage (MSG * PMSG) {if (wm_keydown == pmsg-> message) IF (0x30 == (int) PMSG-> wparam) {Return True; / * Prohibition of 0 (ASCLL 0X30) * /} if (WM_CHAR == PMSG-> Message) IF ('a' == (tchar) pmsg-> wparam) {return true; / * prohibited Enter 'a' * /} if (WM_MOUSEMOVE == PMSG-> Message) if (MK_Control & PMSG-> WPARAM) IF (MK_Control & Pmsg-> WPARAM) / * When Ctrl is pressed, display information * / {int xpos = LOWORD (PMSG-> LPARAM); int ypos = HiWord (pmsg-> lparam); CSTRING STR; Str.Format ("Coordinate% D% D", XPOS, YPOS); AFXMessageBox (STR);} if (WM_Command == PMSG-> Message) IF (id_1 == loword (pmsg-> wparam) // disable menu item ID_1, pay attention to the button to send BN_Clicked {Return True;} Return CDialog :: PretranslateMessag E (PMSG);} VC Getting Started Time 11 (XML) XML He Zhidan We create an XML file, as shown in the figure: 1. Establish a dialog-based program, the project is called XML; Second, initialize Ole.Bool CXMLAPP :: InitInstance () {AFXOLINIT (); .......} III, add a button in the dialog box, ID is IDC_CREATE, we generate an XML file in this button response function .void cxmldlg :: oncreate () {msxml2 :: IXMLDOMDocumentPtr pDoc; MSXML2 :: IXMLDOMElementPtr xmlRoot; // create a DOMDocument object HRESULT hr = pDoc.CreateInstance (__ uuidof (MSXML2 :: DOMDocument30)); (! SUCCEEDED (hr)) if {MessageBox ( "

Unable to create a DomDocument object, please check if the MS XML Parser Runar is installed! ");} // The name of the root node is China PDOC-> Raw_createElement ((_ bstr_t) (char *)" China ", & xmlroot); PDOC-> raw_appendChild (xmlRoot, NULL); MSXML2 :: IXMLDOMElementPtr childNode; pDoc-> raw_createElement ((_ bstr_t) (char *) "City", & childNode); childNode-> Puttext ( "WuHan"); // node value childNode-> setAttribute ("Population", "8,000,000"); // Attribute name, attribute value childNode-> setttribute ("area", "10000"); xmlroot-> appendchild (childnode); pdoc-> raw_createElement ((_ bstr_t) (char * ) "City", & childNode); ChildNode-> PutText ("Shanghai);" Population "," 12,000 "); ChildNode-> SetAttribute (" Area "," 12000 "); XMLROOT-> AppendChild (// Save to the file // If there is no existence, it is created, the presence is covered with PDOC-> Save ("f: //he.xml");} Don't forget #import "msxml4.dll" // introduction Type library four, add a button, ID is IDC_GET, read XML files in this button response function .void cxmldlg :: ONGET () {/ / Create DOMDocument object MSXML2 :: IXMLDOMDocumentPtr pDoc; HRESULT hr = pDoc.CreateInstance (__ uuidof (MSXML2 :: DOMDocument30)); (! SUCCEEDED (hr)) if {MessageBox ( "Can not create DOMDocument object, check whether the installed MS XML Parser Running! ");} // Load file PDOC-> LOAD (" f: //he.xml "); // Find a node named city in the tree," // "is indicated at any layer MSXML2 :: ixmldomelementptr childNode; childNode = (msxml2 :: ixmldomelementptr) (pdoc-> selectsinglenode ("// city");

// Get Node Type MSXML2 :: DomNodeType Nodetype; ChildNode-> get_nodetype (& nodetype); // Node name BStr var; cstract name; childnode-> get_nodeename (& var); name = (char *) (_ bstr_t) var; // node value VARIANT varVal; childNode-> get_nodeTypedValue (& varVal); CString strValue = (char *) (_ bstr_t) varVal; // node properties on the list MSXML2 :: IXMLDOMNamedNodeMapPtr pAttrs = NULL; MSXML2 :: IXMLDOMNodePtr pAttrItem; childNode- > GET_ATTRIBUTES; Long Ncount; Pattrs-> get_length (& ncount); for (int i = 0; i get_item (i, & pattern); // We can pass the function get_nodename, get_nodetyped accuue Get the attribute name and attribute value // can also get cstring strattrname = (_ bstr_t) Pattritem-> nodename; cstring strattrignue = (_ bstr_t) Pattritem-> nodetypedPalue;}} VC Getting Started Book 12 (call other programs) Call other programs He Zhidan Winexec prototype: Uint Winexec (LPCSTR LPCMDLINE, / / ​​Address of Command Line uint Ucmdshow // WINDOW Style for new application); for the 16-bit operating system and compatibility system. For example: Winexec ("NOTEPAD.EXE F: // Call program .txt", sw_show); Winexec ("notepad.exe", sw_show); Different parameters are separated by spaces, and there is no space in the path, and most of the programs The default is installed in "... / program files / ..."

, Such as Word, this greatly limits the application range of Winexec. The above can be used: 1. The program is located. 2. Current path .3, system catalog, you can get .4, Windows Directory with getSystemDirectory. 5, the directory set in environment variables. SHELLEXECUTE prototype: hinstance shellexecute (hwnd hwnd, // parent window handle LPCTSTSTSTSTSTSTSTSTSTSTR LPOPERATION, // Operation, "Open", "Print", "Explore" lpctstr lpfile, // file name , Front plus path lpctstr lpparameters, // parameter lpctstr lpdirectory, // default folder int nshowcmd // display mode); open an application shellexecute (this-> m_hwnd, "open", "cagc.exe", "" , "", Sw_show); "t-> m_hwnd," open "," notepad.exe "," c: /mylog.log "," ", sw_show); open a document with the system program related document Shellexecute (this-> m_hwnd, "open", "c: /abc.txt", "", ", sw_show); activate related programs, send emailshellexecute (this-> m_hwnd," open "," mailto: nishinapp @ Yahoo .com "," "", "", sw_show; print the document with the system printer (this-> m_hwnd, "print", "c: /abc.txt", "," ", sw_hide); LPParameters Example: First, establish a program called Call.exe, add the following code: BOOL ccallapp :: initinstance () {int n = __ARGC; for (int i = 1; i program argrents -> "1 2 3 4 5". If there are multiple parameters, separated by spaces. Third, Run. Four, execute shellexecute (NULL, NULL, "F: //call.exe", "1 2 3 4 5", NULL, SW_SHOW);

BOOL CreateProcess (LPCTSTR lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCTSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); STARTUPINFO startupInfo; memset (& startupInfo, 0, sizeof (STARTUPINFO)); startupInfo .cb = sizeof (STARTUPINFO); example: // when the program starts maximize the most startupInfo.dwFlags | = STARTF_USESHOWWINDOW; startupInfo.wShowWindow = SW_SHOWMAXIMIZED; // run .... exe PROCESS_INFORMATION ProcessInfo; BOOL bCreate = :: CreateProcess ( " F: //call.exe ", // 1 2 3 4", NULL, NULL, NULL, FALSE, 0, NULL, NULL, & Startupinfo, & ProcessInfo; // WaitforsingleObject (ProcessInfo.hprocess, 1000000); MessageBox ("calling program ends!"); Control control He Zhidan 1, file => new => Project => MFC ActiveX Control Wizard creates a project called Owner, all settings are default, and you can directly finish. 4, CTRL F5 runs. Executable for debug session, select cancellation. 5, TOOL => ActiveX Control Test Container is tested. 6. Register, copy the control's OCX file to the Windows system directory, such as: Win95 / System. Start menu, runregsvr32 Owner.ocx. Regsvr32 [/ u] [/ s] [/ c] [/ i [: cmdline ]]]] Dllname where: / U Logan / S does not display the prompt information / c output console / i call dllinstall and pass CMDLINE, call the logout / n when using / u Do not call DLLREGISTERSEVER, must be used with / i . 7. Create a dialog-based executable OwneRexe, Note AppWizard-Step 2 of 6 Select the ActiveX Controls check box.

Application Guide to us Add Bool Cownerexeapp :: InitInstance () {AFXENSTANCE () {AFXENABLECONTROLCONTAINER (); ...... 8, Project => add to project- Components. Find the control you just registered and inserted into the control toolbar. Get it on the dialog as using standard controls. 9, CTRL F5, we can see anything that is not dry. Let's take a check of a number of power (such as 1, 2, 4, 8) that checks a number of 2, let us supplement the second step and third steps. 2, add a Booler variable IS2N in COWNERCTRL, the initial value is false; change the onDrawne: Void CownerCtrl :: Ondraw (CDC * PDC, Const CRECT & RCBOUNDS, Const CRECT & RCINVALID) {CBRUSH * PBRUSH; if (IS2N) PBRUSH = New CBRUSH (RGB (255, 0)); Else Pbrush = New CBRUSH (RGB (255, 255, 255)); PDC-> FillRect (RCBounds, PBRUSH); delete pbrush;} Ctrl W Open Class Wizard, Automation => Add Method Name Fill in the ISPOW2N, returns VOID, a long shaped parameter x. Note that there are multiple parameters, mobilized with the downwise key or PageDown. Modify this function: void cownerctrl :: ISPOW2N (long x) {is2n = ((x & -x) == x); invalidateControl ();} Ctrl F5 generates new OCX, covering the original OCX. Note when Windows System Directory After the OCX is modified, OXC in our program will automatically update the control. Not all functions of the control can be called by the control user, only the method can be. Go back to OWNEREXE, add an edit control (associated with a long shape variable m_input) and a button, let the control associated with m_ctrl, this button's response function is: void cownerexedlg :: Onis2n () {updatedata (); m_ctrl. IsPow2N (M_INPUT);} Ctrl F5, view the effect, take a closer look, when the input is zero, the result is wrong. Obviously 0 cannot be 2 N times. 3, we define an event for the control, the event is very similar to a custom message, you must decide when it is called, and it is necessary to set the initial value when it is called. Go back to our control, Ctrl W => ActiveX Events => add events. Name ZERO, parameter is x, long shaping. Insert IF (0 == x) Firezero (X); in Void CownerCtrl :: ISPOW2N (LONG X), indicating that the parameter of ISPOW2N is found in the ISPOW2N execution process, this method is called. And its parameters are the same as ISPOW2N.

转载请注明原文地址:https://www.9cbs.com/read-99891.html

New Post(0)