VC code collection

xiaoxiao2021-03-05  24

First, change the view background color:

Add the following program code in the CVIEW ondraw function:

Void CFileNameView :: OnDraw (CDC * PDC)

{

CfilenaMedoc * pdoc = getDocument ();

Ask_VALID (PDOC);

CRECT RECLIENT;

Cbrush brushbkcolor;

GetClientRect (RectClient);

Brushbkcolor.createsolidbrush (RGB (255, 0, 0)); // Color Settings

PDC-> DPTOLP (RectClient);

PDC-> FillRect (RectClient, & Brushbkcolor);

...

}

Second, add a menu to a dialog-based program:

[1] Add a menu (idR_Menu1) resource and add the menu item required.

[2] Edit the attribute of the dialog resource IDD_DLGMENUTOOLBAR_DIALOG, select IDR_Menu1 in the Properties dialog box.

[3] If you don't want to set the menu directly in the dialog box, you can use the code to dynamically generate in the program.

Add a member variable cMenu M_Menu to the CFileNameDlg class sound name, then add the following code in cfilenaMedlg :: OnIndialog ():

// Load menu

M_Menu.LoadMenu (idR_Menu1);

// Set the current menu

Setmenu (& m_Menu);

// You can use SetMenu (NULL) when you don't need a menu; to cancel the current menu

Third, add a toolbar to Dialog-based program:

[1] Add a toolbar (idR_toolbar1) resource and draw each button.

[2] Add member variables in the CFileNamedlg class to the CFILENAMEDLG CTOOLBAR M_WNDTOOLBAR;

[3] Add the following code in cfilenamedlg :: onInitdialog ()

// Add a flat toolbar

if (m_wndtoolbar.CreateEx (this, TBSTYLE_FLAT, WS_CHILD |! WS_VISIBLE | CBRS_ALIGN_TOP | CBRS_GRIPPER |! CBRS_TOOLTIPS, CRect (4,4,0,0)) || m_wndtoolbar.LoadToolBar (IDR_TOOLBAR1))

{

Trace0 ("Failed to Create Toolbar / N);

Return False;

}

m_wndtoolbar.showwindow (SW_SHOW);

Repositionbars (AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

Fourth, change the dialog background color:

Modify the code in cdlgmenutoolbardlg :: onpaint () Implement Dialog Pack Color:

CPAINTDC DC (this);

CRECT RECT;

GetClientRect (Rect);

Dc.fillsolidRect (RECT, RGB (60, 110, 170);

Method 2 In InitInstance () (not OnInitDialog ()):

SetDialogbkcolor (RGB (255, 0), RGB (0,255,0));

Note: To put it in the forenequent in the initInstance function!

5. Add Tool Tips for Dialog Toolbar:

[1] Handmade the definition of the message mapping function in the CFileNamedlg class definition, the following black body part

// {{AFX_MSG (CFileNamedlg)

Virtual Bool OnInitdialog (); AFX_MSG void onpaint ();

AFX_MSG BOOL ONTOOLTIPTEXT (UINT, NMHDR * PNMHDR, LRESULT * PRESULT);

//}} AFX_MSG

Declare_message_map ()

[2] Implementation code for adding functions in cfilenamedlg.cpp

// Toolbar Tips

Bool cfilenamedlg :: ONTOOLTIPTEXT (UINT, NMHDR * PNMHDR, LRESULT * PRESULT)

{

AskERT (pnmhdr-> code == ttn_needtexta || pnmhdr-> code == ttn_needtextw);

// unicode message

Tooltiptexta * pttta = (tooltiptexta *) pnmhdr;

Tooltiptextw * ptttw = (tooltiptextw *) pnmhdr;

// tchar szfulltext [512];

CString Strtiptext;

UINT NID = PNMHDR-> IDFROM;

IF (pnmhdr-> code == TTN_NeedTexta && (PTTTA-> UFLAGS & TTF_IDISHWND) ||

PNMHDR-> CODE == TTN_NeedTextw && (PTTTW-> uflags & ttf_idishwnd))

{

// idFrom is the HWnd of the toolbar

NID = :: getdlgctrlid ((hwnd) NID);

}

IF (NID! = 0) // is not separator

{

Strtiptext.LoadString (NID);

Strtiptext = start.mid (strtiptext.find ('/ n', 0) 1);

#ifndef _unicore

IF (pnmhdr-> code == ttn_needtexta)

{

LSTRCPYN (PTTTA-> Sztext, Strtiptext, SizeOf (PTTTA-> Sztext));

}

Else

{

_mbstowcsz (ptttw-> sztext, strtiptext, sizeof (ptttw-> sztext));

}

#ELSE

IF (pnmhdr-> code == ttn_needtexta)

{

_WCSTombsz (PTTTA-> Sztext, Strtiptext, SizeOf (PTTTA-> Sztext));

}

Else

{

LSTRCPYN (PTTTW-> Sztext, Strtiptext, SizeOf (PTTTW-> Sztext));

}

#ENDIF

* PRESULT = 0;

/ / Make the toolbar prompt window in the top

:: SetWindowPos (PNMHDR-> HWndFrom, Hwnd_top, 0, 0, 0, 0, SWP_NOACTIVATE |

SWP_NOSize | SWP_NOMOVE | SWP_NOOWNERZORDER;

Return True;

}

Return True;

}

[3] Add a message mapping in cfilenamedlg.cpp, see the black body part of the following code

Begin_MESSAGE_MAP (CFileNamedlg, CDIALOG)

// {{AFX_MSG_MAP (cfilenamedlg)

ON_WM_PAINT ()

ON_NOTIFY_EX (TTN_NeedText, 0, ONTooltiptext)

//}} AFX_MSG_MAPEND_MESSAGE_MAP ()

[4] Add a declaration in cfilenaMedlg.h:

Bool cfilenamedlg :: ONTOOLTEXT (UINT, NMHDR * PNMHDR, LRESULT * PRESULT);

6. Add a toolbar for a window without a toolbar:

Edit the toolbar in the Explorer and change its properties to IDR_MAINFRAME, then declare in Mainfrm.h:

CToolbar M_Wndtoolbar;

Add: in mainfrm.cpp:

INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct)

{

m_wndtoolbar.create (this);

m_wndtoolbar.loadtoolbar (idR_mainframe);

...;

}

Stop Toolbar: Add the following code after you just added:

M_WndToolBar.setbarstyle (m_wndtoolbar.getbarstyle () | CBRS_Tooltips | CBRS_SIZE_DYNAMIC;

m_wndtoolbar.enabledocking (CBRS_ALIGN_ANY);

Enabledocking (CBRS_ALIGN_ANY);

DockControlbar (& M_WndToolbar); / / Control whether to turn on any stop

Improve the functionality:

Add a "toolbar" in the menu, ID_View_toolbar, everything is OK, try it!

7. Create a separator window:

Only the frame class can be created separately, and the separation can be nested.

Declaring CSPLitterWnd M_Wndsplitter in .h file; and contains CONEVIEW.H (New View Class) and CWINFrame.h (New Framework Class) file;

Then join in the .cpp file:

Bool CMAINFRAME :: OnCreateClient (lpcreateStruct LPCS, CCReateContext * PContext)

{

IF (! m_wndsplitter.createstatic (this, 1, 2))

Return False;

IF (! M_Wndsplitter.createView (0, 0, Runtime_Class (CONEVIEW), CSIZE (240, 420), PCONText))

Return False;

IF (! m_wndsplitter.createview (0, 1, runtime_class (cwinframe), CSIZE (300, 500), PCONTEXT))

Return False;

Return True;

}

When the user creates a split window, sometimes it does not want to adjust the size of the window by dragging the cut strip. At this time, you must lock the cutting. The easiest way to lock the cutlets is not too much not to processes WM_LBUTTONDOWN, WM_MOUSEMOVE, WM_SETCURSOR messages, but give these messages to the CWND window to process these messages. Take the WM_LBUTTONDOWN process process. Modify as follows:

Void cxxsplitterWnd :: ONLBUTTONDOWN (uint nflags, cpoint point)

{

CWnd :: ONLBUTTONDOWN (NFLAGS, POINT);

}

The rest of the treatment is similar.

Eight, the setting of the "Open" button:

Create the Click function of this button with the class wizard, select the default value onOpen, add the following code:

Void cyordlg :: onopen () {

Char szfilefilter [] =

"Bin file (*. Bin) | * .bin |"

"All file (*. *) | *. * ||"; // file type filtering

Cfiledialog DLG (True, Null, Null, OFN_HIDEREADOONLY, SZFILEFILTER);

/ * CFiledialog DLG (FALSE);

DLG.M_OFN .lpstrfilter = _t ("text file (* .txt)

*.TXT

All files(*.*)

*. *

");

Dlg.m_ofn.lpstrdefext = _t ("txt"); * /

IF (DLG.Domodal () == iDOK)

{

m_path = dlg.getPathName (); // Name the EDIT control of the display path to m_path, and increase the cstring variable M_Path

Updatedata (FALSE);

}

}

Nine, the window is centered:

Add: centerWindow () in the initialization function: centerwindow

Ten, dialog box plus status:

Uint indeicators [] = {id_initmessage, id_separator, id_timeMeMessage, ID_Progress};

m_statusbar.createex (this, 0, ws_child | WS_Visible | CBRS_BOTTOM);

M_StatusBar.Setindicators (Indicators, 4);

m_statusbar.showwindow (SW_SHOW);

Repositionbars (AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

Ele 1, set the initial window status:

Bool cobjectnameapp :: initInstance ()

{

m_pmainwnd-> setWindowText (""); // Set the initial window title text

m_pmainwnd-> showWindow (sw_showmaximized); // Setting the initial window to maximize

m_pmainwnd-> UpdateWindow ();

}

For the MDI function setWindowText invalid, the title of the main window can only modify in the resource list, the sub-window title is overnnewdocument () in ** doc.cpp, calls setTitle ("LGDownload Chinese version"); to modify.

Set another optimization method for maximizing the initial window:

Void CMAINFRAME :: ActiVateFrame (int ncmdshow)

{

// Todo: Add Your Specialized Code Here and / or Call The Base Class

Ncmdshow = sw_maximize;

CframeWnd :: ActivateFrame (ncmdshow);

}

12. Dialogue transparency effects:

Add the following code in OnInitDialog ():

/ / Add WS_EX_LAYED extension attribute

SetWindowlong (this-> getsafehwnd (), gwl_exstyle,

GetWindowlong (this-> getsafehwnd (), gwl_exstyle) ^ 0x80000);

Hinstance hinst = loadingLibrary ("user32.dll");

IF (hinst)

{

Typedef Bool (WinApi * Myfunc) (HWND, ColorRef, Byte, DWORD); MyFunc Fun = NULL;

// get the setlayeredWindowAttributes function pointer

Fun = (MyFunc) GetProcaddress (Hinst, "SetlayeredWindowAttributes");

IF (fun) Fun (this-> getsafehwnd (), 0, 128, 2);

Freelibrary (HINST);

}

Note: The parameter 128 of FUN cannot be too small, otherwise it is completely transparent!

Thirteen, set the Static Control Color Properties in the Dialog:

Add a WM_CTLCOLOR event in this dialog, add the following code:

IF (nctlcolor == ctlcolor_static)

{

PDC-> SetTextColor (RGB (255, 255, 255);

PDC-> SetBkcolor (RGB (91, 145, 244);

PDC-> setBkmode (Transparent); // Setting transparent

}

Set the Static control background transparent:

IF (nctlcolor == ctlcolor_static)

{

PDC-> setBkmode (Transparent); // Setting transparent

Return (Hbrush) :: getStockObject (null_brush);

}

14. Make the maximumization and minimization button of the window disappear:

Add the following code to the PrecreateWindow function:

INT Xsize = :: getSystemMetrics (SM_CXSCREEN);

INT Ysize = :: getSystemMetrics (SM_CYSCREEN);

Cs.cx = xsize * 6/10;

CS.CY = ysize * 6/10;

Cs.x = (xsize - cs.cx) / 2;

CS.Y = (Ysize - cs.cy) / 2;

CS.Style & = ~ ws_thickframe;

CS.Style & = ~ (WS_MaximizeBox | WS_MINIMIGIZEBOX);

Cs.dwexStyle | = WS_EX_TOOLWINDOW;

Fifteen, set control font color: (such as Static control)

Add the following code in the onCTLCOLOR function: (may need to select the simple properties of Static)

IF (nctlcolor == ctlcolor_static)

{PDC-> SetTextColor (RGB (255, 0, 0));

PDC-> SetBkcolor (RGB (128, 128, 128)); // Set text background color

PDC-> setbkmode (transparent); // Setting the background transparent

}

The macro definition of other controls is:

.Ctlcolor_btn button control

.Ctlcolor_dlg dialog

.Ctlcolor_edit edit box

.Ctlcolor_listbox list control

.Ctlcolor_msgbox message control

.Ctlcolor_scrollbar scroll bar control

.Ctlcolor_static static control

16. Convert characters to numbers:

INT i = ATOI ("12345"); or SSCANF ("12345", "% D", & I);

17. Call external applications can be used: CreateProcess, Winexec, Shellexecute.

Example: Shellexecute (PWND-> M_Wnd, "Open", "My.exe", NULL, NULL, SW_NORMAL)

First, parent form handles, two, command "open", three, file path, four, parameters, five, run path, six, display method

Eighteen, classic installation software: InstallShield for Microsoft Visual C 6.0

The Release method is changed in the Set Active Configuration in the Build menu.

In the Project menu, choose the Add to Project's Component and Control to join the OCX control

19. Registration:

Register

Regsvr32 x: /xxx/demo.ocx is not necessarily available in Windows System Directory

2. Uninstall

Regsvr32 / u x: /xxx/demo.ocx

Twenty, get the current time:

CTIME M_TIME = CTIME:: GetCurrentTime ();

Char sztext [100];

MEMSET (Sztext, 0,100);

Sprintf (Sztext, "% D_% D_% D", m_time.getHour (), m_time.getminite (), m_time.getsecond ());

/ / How to get the current time date

CTIME TIME = CTIME :: getcurrenttime ();

CString M_Strtime = Time.Format ("% Y-% M-% D% H:% M:% S");

// Method Two

SystemTime Ti;

GetSystemTime (& TI); // How to get the current time date

Ti.wmilliseconds; // Get milliseconds

SystemTime Time;

CString Str;

GetLocalTime (& Time);

Str.Format ("% 04D:% 02D:% 02D", time.wyear, time.wmonth .....);

Two, modify the title of a single document:

Add SetWindowText ("Weichao") in OnCreat ();

Cs.Style = WS_OVERLAPPEDWINDOW is added to CMAINFRAME :: PrecreateWindow (Createstruct & Cs);

Second, the hidden program in the taskbar of the task bar:

Dialog Box Program OnInitdialog () function:

Setwindowlong (this-> m_hwnd, gwl_exstyle, ws_ex_toolwindow); // Hidden Task Block button

Two three, read the edit box content:

Getdlgitemtext (idc_edit_txdata, m_strtxdata);

Two four, the self-painted menu is not correct, the height is right, the solution:

Under Classname in Classwizard, select CMIANFrame, select WM_CONTEXTMENU to Messages and generate the corresponding function, as follows:

Void CMAINFRAME :: OnContextMenu (CWND * PWND, CPOINT POINT)

{

CMenu Menu;

Menu.LoadMenu (idR_Menu1); // idR_Menu1 is the ID number you want to pop up.

Cmenu * popup = menu.getsubmenu (0);

Popup-> TRACKPOPUPMENU (TPM_LEFTALIGN, POINT.X, POINT.Y, THIS);

Second 5, restart the computer:

Call an API function EXITWINDOWSEX is OK, two parameters: uflag, tag, you can choose EWX_REBOOT, EWX_SHUTDOWN, EWX_POWEROFF or on EWX_FORCE second parameter is 0

Second, the movement of the Title dialog:

Void cscreensnapdlg :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT)

{

// Implement the form without title

Postmessage (WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM (Point.x, Point.y);

CDIALOG :: ONLBUTTONDOWN (NFLAGS, POINT);

}

Second 7, get operating system version:

OsversionInfo OsversionInfo; / / Contains the data structure of the operating system version information

OsversionInfo.dwosveionsInfosize = SizeOf (OsversionInfo);

GetversionEx (& OSVersionInfo); // Get operating system version information

28, Setup dialog as the top: (Add) in OnInitDialog)

SetwindowPOS (& Wndtopmost, 0,0,0,0, swp_nomove | swp_nosize);

Two nine, dialog box program is not displayed in the taskbar: (Add) in OnInitDialog)

ModifyStyleex (WS_EX_APPWINDOW, WS_EX_TOOLWINDOW);

Thirty, add the right-click menu to the dialog window:

CMenu Menu, * pmenu

Menu.LoadMenu (idR_Menu1);

Pmenu = menu.getsubmenu (0);

Cpoint ptscreen (point);

ClientToscreen (& PTScreen);

Pmenu-> TrackPopupnupmenu (TPM_RightButton, Ptscreen.x, Ptscreen.y, this);

Third, file lookup: (for example to find continuous wrapper)

File * fp, * fp1;

INT FLAG = 0;

int CH;

FP = fopen ("c: //test.txt", "r");

FP1 = FOPEN ("C: //wrttest.txt", "w");

While (! feof (fp))

{

CH = FGETC (FP);

IF (Feof (fp))

Break;

IF (CH == '/ n' && flag == 1)

CONTINUE;

Else IF (CH == '/ n' && flag == 0)

FLAG = 1;

Else

FLAG = 0;

FPUTC (CH, FP1);

}

Fclose (fp1);

Fclose (fp);

Third 2, the tray menu does not click on the solution that cannot disappear:

Use the following code after the menu:

Cpoint pt;

GetCursorpos (& PT);

SetForegroundWindow ();

Notifymenu.trackpopupmenu (TPM_RightButton, Pt.x, Pt.y, this);

Postmessage (WM_NULL, 0, 0);

Third, the dialog box is shown by small to large display:

Add: in initdialog:

ShowWindow (SW_HIDE);

CRECT DLGRECT; GetClientRect (& DLGRECT);

Cpoint centerpoint;

Centerpoint.x = DLGRECT.WIDTH () / 2;

Centerpoint.y = DLGRect.Height () / 2; // Get the midpoint coordinates of the dialog

CRGN TESTRGN;

This-> showwindow (sw_hide);

INT m = getSystemMetrics (SM_CYSIZEFRAME)

// The following code implements the dynamic pop-up of the dialog

For (int i = 10; i

{

Testrign.createRectrgn (Centerpoint.x-i, centerpoint.x i, centerpoint.y i);

SetwindowRgn ((HRGN) TESTRGN, TRUE;

ShowWindow;

CenterWindow ();

Testrign.deleteObject ();

}

Three four, read the text file by line:

The following example demonstrates a row of one line until it is finished.

Cstdiofile myfile;

Cstring readfilestring;

IF (MyFile.Open ("C: //Readme.txt", CFile :: ModeRead) == True)

{

While (MyFile.ReadString (ReadFileString)! = false)

{

// ... processing code

}

}

Three five. When using IDC_Hand, prompt is not defined, add the following code:

#if (WinVer> = 0x0500)

#define IDC_Hand MakeintResource (32649)

#ENDIF / * WINVER> = 0x0500 * /

Three six, do not automatically create new documents when the application starts

By default, the SDI / MDI application developed with AppWizard is created a new document at startup. If you want to make your application not to create a new document when you start, you can add the following statement before the application class cmyapp :: initInstance () function:

CMDINFO.M_NSHELLCOMMAND = CCOMANDLINFO :: Filenothing;

Sanqi, play MP3:

CfileDialog file (true);

File.Domodal () == iDok)

{

CSTRING FILENAME = file.getfilename ();

IF (hwnd! = null)

{

MCIWNDDESTROY (HWND);

}

HWnd = mciWndcreate (this-> m_hwnd, null, mciwndf_noplaybar, filename);

:: ShowWindow (hwnd, sw_hide);

MCIWNDSETVOLUME (HWND, 1000);

MCIWNDPLAY (HWND);

}

38, get the screen RGB value: ONTIMER Add

Cpoint Pos;

GetCursorpos (& POS); // Get mouse coordinates

HDC HDC = :: getdc (null);

ColorRef CLR = :: getpixel (HDC, POS.X, POS.Y);

CString Clrtext;

CLRText.format ("R:% D G:% D B:% D", GtrValue (CLR), GETGVALUE (CLR), GetBValue (CLR)); Sanjiu, open a URL:

turn on

Http://www.sina.com.cn This site is as follows:

Shellexecute (NULL, "Open", "http://www.sina.com.cn", null, null, sw_maximize;

This command will open http://www.sina.com.cn with the default browser, and maximize the open window.

Another example:

Shellexecute (NULL, "Open", "IExplore.exe http://www.sina.com.cn", null, null, sw_maximize;

This command will open a Sina site directly with IE. However, a new window will open.

Forty, bitmap button:

CButton * Pradio = (cbutton *) getdlgitem (IDC_RADIO);

Pradio-> setBitmap (:: loadbitmap (afxgetinstancehandle (), makeintresource (idb_bitmap)));

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

New Post(0)