VC tips 15

zhaozj2021-02-17  53

VC tips 15 King Fan2002 / 12/6

First, only two ways of running only one program instance is implemented, it is recommended to adopt a second way: 1, if (FindWindow (NULL, "Program Title")) EXIT (0); 2, BOOL CDEMOTBAREAPP :: InstanceSrun ) {HANDLE m_hMutex; m_hMutex = :: CreateMutex (NULL, TRUE, _T ( "YourApplication")); ASSERT (m_hMutex); if (GetLastError () == ERROR_ALREADY_EXISTS) {m_hMutex = NULL; return TRUE; // instance has been run } RETURN FALSE; // Instance Unbound}

Second, load the cursor setCursor (AFXGetApp () -> LoadStandardCursor (IDC_WAIT)); where :: setCursor () is a full-class function to set the cursor parameter of the entire routine is a macro definition cursor handle. AfxGetApp () is a system function that returns a current CWINAPP object. Its member function loadStandardCursor () is used to read a system pointer, and each system pointer is defined as follows: IDC_AppStarting Standard arrow IDC_ARROW standard arrow IDC_CROSS Cross Cursor (for positioning) IDC_HAND WINDOWS 2000: Hand type IDC_HELP arrow IDC_IBEAM I-beam IDC_ICON Obsolete for applications with a question mark marked version 4.0 or later. IDC_NO prohibited symbol IDC_SIZE Obsolete for applications marked version 4.0 or later. Use IDC_SIZEALL. IDC_SIZEALL cross IDC_SIZENESW arrow pointing northeast and southwest of the bi-directional arrow pointing south and north IDC_SIZENS Bidirectional arrow IDC_SIZENWSE pointing to the northwest and southeast of two-way arrow IDC_SIZEWE pointing to the two-way arrow IDC_UPARROW arrow IDC_WAIT hourglass

Third, get the main frame: CMAINFRAME * PMAINFRAME = (CMAINFRAME *) AFXGetApp () -> m_pmainwnd; Get an instance handle of the application: Example: Handle Hinstance = AFXGetInstanceHandle ();

Get the pointer of the application main window: example: AFXGETMAINWND () -> showwindow (sw_showmaxmize); // Maximize the program

Fourth, re-establish the code IF (m_fontlogo.m_hobject) m_fontlogo.detach ();

M_FontLogo.createFont (NHEIGHT, 0, 0, 0, NWEight, Bitalic, Bunderline, 0, 0, 0, 0, 0, 0, Name);

5. Fill the area Dc.FillSolidRect (Rect, :: getSyscolor); color_3dface);

Sixth, draw the font of the three-dimensional font effect, it is worth watching void ctestview :: onpaint () {CPAINTDC DC (this); // device context for Painting CRECT; getWindowRect (RECT);

CFont M_FontLogo; M_FontLogo.createFont (24, 0, 0, 0, fw_bold, true, false, 0, 0, 0, 0, 0, "arial"); cstring m_logotext; m_logotext = _t ("Benlux Pro3D System" ); Dc.setbkmode (transparent); cfont * Oldfont = dc.selectobject (& m_fontlogo);

// Draw Text In DC ColorRef OldColor = DC.SetTextColor (:: getsyscolor (color_3dhilight));

Rect.right = Rect.width (); Rect.bottom = Rect.Height (); Rect.Lep = Rect.top = 0; Dc.FillSolidRect (RECT,: :: GetSysColor (Color_3dface));

dc.DrawText (m_LogoText, rect CPoint (1,1), DT_SINGLELINE | DT_LEFT | DT_VCENTER); dc.SetTextColor (:: GetSysColor (COLOR_3DSHADOW)); dc.DrawText (m_LogoText, rect, DT_SINGLELINE | DT_LEFT | DT_VCENTER);

// RESTORE OLD TEXT Color Dc.SettextColor (OldColor); // restore old font dc.selectObject (oldfont); // do not call cView :: onpaint () for Painting Messages}

7. Simple messages retrieves and extract functions, allowing the system to respond to other operations BOOL PeekandPump () {Static MSG MSG;

While (:: PeekMessage (& MSG, NULL, 0, 0, PM_NOREMOVE)) {if (! AFXGetApp () -> pumpMessage ()) {: postquitMessage (0); return false;}} Return true;

8. In your program, use animated light to replace the default wait cursor (ANI cursor) hcursor m_hanicursor = null; beginwaitcursor (); // begin Wait Cursor for API FUNCTION // Load Ani Cursor from File In Current Path Tchar CursorPath [MAX_PATH]; GetModuleFileName (NULL, cursorPath, MAX_PATH); char drive [_MAX_DRIVE]; char dir [_MAX_DIR]; char fname [_MAX_FNAME]; char ext [_MAX_EXT]; _splitpath (cursorPath, drive, dir, fname, ext); sprintf (cursorPath, "% s% s / wait.ani", drive, dir); // ani cursor file name is wait.ani m_hAniCursor = LoadCursorFromFile (cursorPath); HCURSOR oldCursor; if (! m_hAniCursor = NULL) oldCursor = SetCursor (m_hanicursor); for (long i = 0; i <1000; i ) Sleep (5); oldcursor = null; m_hanicursor = null; endwaitcursor (); // end wait cursor for API Function Nine, how to limit the editing box Permissible characters If users only allow reception 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 only to collect only characters. If the user needs a complex editing control, you can use Microsoft's mask editing control, which is a very useful OLE custom control. If you want to use the OLE custom control to handle the character, you can derive a CEDIT class and process the WM_CHAR message, and then filter out specific characters from the editing control. First, create a CEDIT 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_WNDIT; // Instance of Your New Edit Control.

// in You Dialog Class Implementation (.cpp file) BOOL CSAMPEDIALOG:: OnIndialog () {

// Subclass the Edit Lontrod. M_wndedit .subclassdlgitem (IDC_EDIT, this); ...} Using the ClassWizard to process the WM_CHAR message, calculate the NCHAR parameter and determine the operation performed, the user can determine whether to modify, transmit characters. The following example shows how to display alphabetic characters. If the character is alphabetical character, call CWnd; onchar, otherwise I don't call onchar.//only display alphabetic dharacters .void CMYDIT:: 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 use the modified NCHAR call. CEDIT:: onchar. To modify a character, you need to modify NCHAR first, then call CWnd:: DefWindowProc with modified NCHAR. The following example shows how to transform characters to uppercase: // make all characters Uppercasevoid CMYEDIT:: OnChar (uint nchar, uint nrepcnt, uint nflags) {// make sure character is Uppercase. If (: ischaralpha)). nChar) nChar =:: CharUpper (. nChar); // Bypass default OnChar processing and directly call default window proc DefWindProc (WM_CHAR, nChar, MAKELPARAM (nRepCnt, nFlags));} ten, how long the display when the string at the end thereof One omitted number calls CDC :: DrawText and specifies the DT_END_ELLIPSIS flag so that the character can be used to replace the tail of the string so that it is suitable for the specified boundary rectangle. If the path information is to be displayed, specify the DT_END_ELLIPSIS flag and omitted the characters in the middle of the string. VOID CsampleView :: OnDraw (CDC * PDC) {ctestdoc * pdoc = getDocument (); assert_valid (pdoc); // add Ellpsis to end of string if it does not fit PDC-> DRAWText ("this is a long String" ), CRECT (10, 10, 80, 30), DT_LEFT | DT_END_ELLIPSIS);

// Add Ellpsis to Middle Of IF IT Does NOT FIT PDC-> DrawText (AFXGetApp () -> M_PSzhelpFilePath, CRECT (10, 40, 200, 60), DT_LEFT | DT_PATH_ELLIPSIS);}

XI. How to achieve a rectangular rectangle (with trace rectangle and removable, scaling) CRECTTRACKER is a useful class that can be created by calling CRECTRACKER :: TRACKRUBBERBAND to respond to WM_LButtondown messages to create a rectangle. The following example shows that the size of the blue ellipse in the window using CRECTRACKER is easy. First, in the document class, a CRECTTRACKER data member is declared: Class Ctestdoc: public cdocument {... public: CRECTRACKER M_TRACKER; ...}; Second, Initialization CRECTRACKER object in the textual constructor: ctestdoc :: ctestdoc () {m_tracker.m_Rect .SETRECT (10, 10, 300, 300); m_tracker.m_nstyle = CRECTTRACKER :: ResizeIndLine;} then draws ellipse and trail rectangles in the onDraw function of the view class: void ctestview :: Ondraw (CDC * pDC) {CTestDoc * pDoc = GetDocument (); ASSERT_VALID (pDoc); // Select blue brush into device context CBrush brush (RGB (0, 0, 255.)); CBrush * pOldBrush = pDC-> SelectObject (& brush);

// Draw Ellipse in Tracking Rectangle. CRECT RCELLIPSE; PDOC-> M_Tracker.getTrueERECT (RCellipse); PDC-> Ellipse (rCellipse);

// Draw Tracking Rectangle. PDOC-> M_Tracker.draw (PDC); // Select Blue Brush Out of Device Context. PDC-> SelectObject (PoldBrush);} Finally, the WM_LBUTTONDOWN message is processed in the view class, and add the following code. This section can drag and drop, move, or reset the size of the ellipse according to the mouse button.

Void ctestview :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {// Get Pointer to Document. ctestdoc * pdoc = getDocument (); assert_valid (pdoc);

// if Clicked On Ellipse, Drag Or Resize It. OtherWise Create A // Rubber-Band Rectangle Nd Create A New Ellipse. Bool Bresh Bresult = PDOC-> M_Tracker.hittest (Point)! = CRECTTRACKER :: HitNothing;

// Tracker Rectangle Changed So Update Views. If (BRESULT) {PDOC-> M_Tracker.track (this, point, true); pdoc-> setmodifiedflag (); pdoc-> UpdateAllViews (null);} else pdoc-> m_tracker. TRACKRUBBERBAND (this, Point, True); CView :: ONLBUTTONDOWN (NFLAGS, POINT);

Twelve, how to create a temporary file in the temporary directory If you want to create a temporary file in the temporary directory, the following code can help you. bool GetuniqueTempName (CString & strTempName) {strTempName = ""; // Get the temporary files directory TCHAR szTempPath [MAX_PATH];. DWORD dwResult = :: GetTempPath (MAX_PATH, szTempPath); if (dwResult == 0) return false;

// Create a unique Temporary File. Tchar sztempfile [max_path]; uint nresult = getTempFileName (sztemppath, _t ("~ ex"), 0, sztempfile; if (dwresult == 0) Return False;

Strtempname = sztempfile; return true;}

Thirteen, how to limit the minimum range of windows to limit the size of the form, the following code can help you. Increase the processing function of the WM_GETMAXMINFO message in CMAINFRAME, then write code in this function as follows: // Limit the minimum height and width of the main form :: ONGETMAXINFO (MinMaxInfo Far * LPMMI) {lpmmi-> ptmintracksize.x = 600 LPMMI-> Ptmintracksize.y = 400; cnewframeWnd :: ONGETMAXINFO (LPMMI);

XIV. How to delete files to the recycle bin to delete files to recycle bins, very simple. Just use the shfileOperation function, the following code I will demonstrate the usage of this function. Of course you can copy directly into your project. // Delete files to the recycle bin // pszpath: The full path file name to be deleted // bdlete: true delete, do not move to the recycle bin, false: Move to the recycle bin one, // Return: true Delete Success FALSE Delete failed BOOL CDelFileToRecycleDlg :: Recycle (LPCTSTR pszPath, BOOL bDelete / * = FALSE * /) {SHFILEOPSTRUCT shDelFile; memset (& shDelFile, 0, sizeof (SHFILEOPSTRUCT)); shDelFile.fFlags | = FOF_SILENT; // do not report progress shDelFile. Fflags | = fof_noerror; // don't report errors shdlfile.fflags | = fof_noconfirmation; // don't confirm delete // copy pathname to double-null-terminated string. // tchar buf [_max_path 1]; ///////////////////max_path 1]; // allow one more character _tcscpy (buf, pszPath); // copy caller's pathname buf [_tcslen (buf) 1] = 0; // need two NULLs at end // Set SHFILEOPSTRUCT params for delete operation shDelFile.wFunc = FO_DELETE; / / Required: delete operation shdelfile.pfrom = buf; // Required: Which file (s) shdlfile.pto = null; // must be null if (bDelete) {// if delete Requested .. shdelfile.fflags & = ~ fof_allowundo ; // ..don't use recycle bin} else {// OtherWise .. shdelfile.fflags | = fof_allowundo; // ..send to recycle bin} Return ShfileOperation; // DO it!}

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

New Post(0)