Summary of VC ++ Interface Programming

Source: Internet
Author: User
1. Change the view background color:
Add the following code to the OnDraw function of CView:
Void CFileNameView: OnDraw (CDC * pDC)
{
CFileNameDoc * pDoc = GetDocument ();
ASSERT_VALID (pDoc );
CRect rectClient;
CBrush brushBkColor;
GetClientRect (rectClient );
BrushBkColor. CreateSolidBrush (RGB (, 0, 0); // color settings
PDC-> DPtoLP (rectClient );
PDC-> FillRect (rectClient, & brushBkColor );
...
}
2. Add a menu to a dialog box-based program:
[1] Add a menu (IDR_MENU1) Resource and add the required menu items.
[2] edit the properties of resource IDD_DLGMENUTOOLBAR_DIALOG in the dialog box. In the Properties dialog box, select IDR_MENU1.

[3] If you do not want to directly set the menu in the dialog box properties, you can use the following method to dynamically generate the menu in the program through code:
Add the member variable CMenu m_menu in the CFileNameDlg class and add the following code in CFileNameDlg: OnInitDialog:
// Load the menu
M_menu.LoadMenu (IDR_MENU1 );
// Set the current menu
SetMenu (& m_menu );
// When you do not need a menu, you can use SetMenu (NULL); to cancel the current menu.
3. Add the toolbar to the Dialog-based program:
[1] Add a toolbar (IDR_TOOLBAR1) Resource and draw the buttons.
[2] Add the member variable CToolBar m_wndtoolbar to the CFileNameDlg class name;
[3] Add the following code to 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 (,) |! 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 );
4. Change the background color of the dialog box:
In CDlgMenuToolbarDlg: OnPaint (), modify the code to implement the Dialog filling color:
CPaintDC dc (this );
CRect rect;
GetClientRect (rect );
Dc. FillSolidRect (rect, RGB (60,110,170 ));
Method 2: Add the following content to InitInstance () (not OnInitDialog:
SetDialogBkColor (RGB (0,255, 0), RGB (, 0 ));
Note: put it at the beginning of the InitInstance function!
5. Add a tooltip for the dialog toolbar:
[1] manually add the definition of the message ing function in the CFileNameDlg class definition.
// {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] add function implementation code in CFileNameDlg. cpp
// Toolbar prompt
BOOL CFileNameDlg: OnToolTipText (UINT, NMHDR * pNMHDR, LRESULT * pResult)
{
ASSERT (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) // not a separator
{
StrTipText. LoadString (nID );
StrTipText = strTipText. Mid (strTipText. Find ('/N', 0) + 1 );

# Ifndef _ UNICODE
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;
// Set the toolbar Prompt window to 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 message ing in CFileNameDlg. cpp. See the simhei section in the following code.
BEGIN_MESSAGE_MAP (CFileNameDlg, CDialog)
// {AFX_MSG_MAP (CFileNameDlg)
ON_WM_PAINT ()
On_policy_ex (TTN_NEEDTEXT, 0, OnToolTipText)
//} AFX_MSG_MAP
END_MESSAGE_MAP ()
[4] add a statement in CFileNameDlg. h:
BOOL CFileNameDlg: OnToolTipText (UINT, NMHDR * pNMHDR, LRESULT * pResult );
6. Add a toolbar to a window without a toolbar:
Edit the toolbar in resource manager, change its attribute to IDR_MAINFRAME, and declare the following in MainFrm. h:
CToolBar m_wndToolBar;
Add the following in MainFrm. cpp:
Int CMainFrame: OnCreate (maid)
{
M_wndToolBar.Create (this );
M_wndToolBar.LoadToolBar (IDR_MAINFRAME );
......;
}
Dock toolbar: Add the following code after the added tool:
M_wndToolBar.SetBarStyle (m_wndToolBar.GetBarStyle () | CBRS_TOOLTIPS | CBRS_SIZE_DYNAMIC );
M_wndToolBar.EnableDocking (CBRS_ALIGN_ANY );
EnableDocking (CBRS_ALIGN_ANY );
DockControlBar (& m_wndToolBar); // determines whether to enable arbitrary dock.
Complete the following functions:
Add a "toolbar" in the menu and set the ID to ID_VIEW_TOOLBAR. Everything is OK. Try it!
7. Create a separate window:
Only framework classes can be created and separated and can be nested.
Declare CSplitterWnd m_wndSplitter in the. h file, and include the COneView. h (New View class) and CWinFrame. h (new framework class) files;
Then add the following to the. cpp file:
BOOL CMainFrame: OnCreateClient (LPCREATESTRUCT lpcs, CCreateContext * pContext)
{
If (! M_wndSplitter.CreateStatic (this, 1, 2 ))
Return FALSE;
If (! M_wndSplitter.CreateView (240,420, RUNTIME_CLASS (COneView), CSize (), pContext ))
Return FALSE;
If (! M_wndSplitter.CreateView (300,500, RUNTIME_CLASS (CWinFrame), CSize (), pContext ))
Return FALSE;
Return TRUE;
}
After creating a split window, you do not want to adjust the size of the window by dragging the split bar. In this case, you must lock the shard. The simplest way to lock the Shard is to prevent CSplitterWnd from processing WM_LBUTTONDOWN, WM_MOUSEMOVE, and WM_SETCURSOR messages. Instead, these messages are sent to the CWnd window for processing, thus blocking these messages. Take the WM_LBUTTONDOWN process as an example. To:
Void CXXSplitterWnd: OnLButtonDown (UINT nFlags, CPoint point)
{
CWnd: OnLButtonDown (nFlags, point );
}
The other methods are similar.
8. Set the "open" button:
Use the Class Wizard to create the click function of this button, select the default OnOpen, and add the following code:
Void CYourDlg: OnOpen ()
{
Char szFileFilter [] =
"BIN File (*. bin) | *. bin |"
"All File (*. *) | *. * |"; // File type filtering
CFileDialog dlg (TRUE, NULL, NULL, OFN_HIDEREADONLY, szFileFilter );
/* CFileDialog dlg (FALSE );
Dlg. m_ofn. lpstrFilter = _ T ("all text files (*. txt) *. txt files (*.*)*.*");
Dlg. m_ofn.lpstrDefExt = _ T ("txt ");*/
If (dlg. DoModal () = IDOK)
{
M_path = dlg. GetPathName (); // name the Edit Control of the display path as m_path and add the CString variable m_path.
UpdateData (FALSE );
}
}
9. Center the window:
Add CenterWindow (); To the OnInit function.
10. Add a status bar to the dialog box:
UINT indicators [] = {ID_INITMESSAGE, ID_SEPARATOR, ID_TIMEMESSAGE, 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 );
11. Set the initial window status:
BOOL CObjectNameApp: InitInstance ()
{
M_pMainWnd-> SetWindowText (""); // you can specify the title Text of the initial window.
M_pMainWnd-> ShowWindow (SW_SHOWMAXIMIZED); // set the initial window to maximize
M_pMainWnd-> UpdateWindow ();
}
The MDI function SetWindowText is invalid. The title of the main window can only be modified in the resource list. The title of the subwindow is in ** doc. in cpp, the OnNewDocument () is reloaded and SetTitle ("LGdownload Chinese version") is called to modify it.
Another Optimization Method for maximizing the initial window is as follows:
Void CMainFrame: ActivateFrame (int nCmdShow)
{
// TODO: Add your specialized code here and/or call the base class
NCmdShow = SW_MAXIMIZE;
CFrameWnd: ActivateFrame (nCmdShow );
}
12. Dialog Box transparent effects:
Add the following code to OnInitDialog:
// Add the WS_EX_LAYERED extension attribute
SetWindowLong (this-> GetSafeHwnd (), GWL_EXSTYLE,
GetWindowLong (this-> GetSafeHwnd (), GWL_EXSTYLE) ^ 0x80000 );
HINSTANCE hInst = LoadLibrary ("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 fun parameter 128 cannot be too small, otherwise it will be completely transparent!
13. Set the color attribute of the STATIC control in the dialog box:
Add the WM_CTLCOLOR event in the dialog box and add the following code:
If (nCtlColor = CTLCOLOR_STATIC)
{
PDC-> SetTextColor (RGB (255,255,255 ));
PDC-> SetBkColor (RGB (91,145,244 ));
PDC-> SetBkMode (TRANSPARENT); // TRANSPARENT setting
}
Set the background transparency of the STATIC control:
If (nCtlColor = CTLCOLOR_STATIC)
{
PDC-> SetBkMode (TRANSPARENT); // TRANSPARENT setting
Return (HBRUSH): GetStockObject (NULL_BRUSH );
}
14. Remove the maximization and minimization buttons of the window:
Add the following code to the PreCreateWindow function:
Int xSize =: GetSystemMetrics (SM_CXSCREEN );
Int ySize =: GetSystemMetrics (SM_CYSCREEN );
Cs. cx = x size * 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_MINIMIZEBOX );

Cs. dwExStyle | = WS_EX_TOOLWINDOW;
15. Set the control font color: (for example, STATIC control)
Add the following code to the OnCtlColor function: (you may need to select a simple property of STATIC)
If (nCtlColor = CTLCOLOR_STATIC)
{PDC-> SetTextColor (RGB (255, 0, 0 ));
PDC-> SetBkColor (RGB (128,128,128); // sets the text background color.
PDC-> SetBkMode (TRANSPARENT); // sets the background transparency.
}
Macros of other controls are defined:
. CTLCOLOR_BTN button control
. CTLCOLOR_DLG dialog box
. CTLCOLOR_EDIT edit box
. CTLCOLOR_LISTBOX list control
. CTLCOLOR_MSGBOX message control
. CTLCOLOR_SCROLLBAR scroll bar Control
. CTLCOLOR_STATIC Static Control
Convert a character to a number:
Int I = atoi ("12345"); or sscanf ("12345", "% d", & I );
17. Call functions available to external applications:
CreateProcess, WinExec, and ShellExecute.
Example: ShellExecute (pWnd-> m_wnd, "open", "my.exe", NULL, NULL, SW_NORMAL)
I. parent form handle, II. Command "open", III. File Path, IV. parameters, V. Run path, Vi. Display Mode
18. Software for creating a classic Installer: InstallShield for Microsoft Visual C ++ 6.0
The release mode is changed in Set Active configuration in the build menu.
In the project menu, select Add to Project component and control to Add the ocx control.
19. Registration of controls:
1. Registration
Regsvr32 x:/xxx/demo. ocx does not have to be in the Windows System directory
2. Uninstall
Regsvr32/u x:/xxx/demo. ocx
20. Obtain the current time:
CTime m_time = CTime: GetCurrentTime ();
Char szText [100];
Memset (szText, 0,100 );
Sprintf (szText, "% d _ % d", m_time.GetHour (), m_time.GetMinite (), m_time.GetSecond ());
// How to get the current time and date
CTime time = CTime: GetCurrentTime ();
CString m_strTime = time. Format ("% Y-% m-% d % H: % M: % S ");
// Method 2
SYSTEMTIME ti;
GetSystemTime (& ti); // how to get the current time and date
Ti. wMilliseconds; // obtain the millisecond time
SYSTEMTIME time;
CString str;
GetLocalTime (& time );
Str. Format ("% 04d: % 02d: % 02d", time. wYear, time. wMonth .....);
Ii. Modify the title of a single document program:
Add SetWindowText ("weichao") to OnCreat ");
Add cs. style = WS_OVERLAPPEDWINDOW to CMainFrame: PreCreateWindow (CREATESTRUCT & cs;
2. Hide the icon of the Program on the taskbar:
The OnInitDialog () function is used in the dialog box program:
SetWindowLong (this-> m_hWnd, GWL_EXSTYLE, WS_EX_TOOLWINDOW); // hide the task blocking button
Ii. Read the content of the edit box:
GetDlgItemText (IDC_EDIT_TXDATA, m_strTXData );
Ii. Incorrect width and height of the Self-painted menu. solution:
Under ClassName in ClassWizard, select CMianFrame, select WM_CONTEXTMENU under Messages, and generate the corresponding function, as shown below:
Void CMainFrame: OnContextMenu (CWnd * pWnd, CPoint point)
{
CMenu menu;
Menu. LoadMenu (IDR_MENU1); // IDR_MENU1 is the ID of the menu to be displayed.
CMenu * popup = menu. GetSubMenu (0 );
Popup-> TrackPopupMenu (TPM_LEFTALIGN, point. x, point. y, this );
}
Ii. restart the computer:
You can call an API function ExitWindowsEx. There are two parameters: UFlag and flag. You can select EWX_REBOOT, EWX_SHUTDOWN, EWX_POWEROFF, or the second parameter on EWX_FORCE is 0.
Ii. move without title dialog box:
Void CScreenSnapDlg: OnLButtonDown (UINT nFlags, CPoint point)
{
// Move the form without a title
PostMessage (WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM (point. x, point. y ));

CDialog: OnLButtonDown (nFlags, point );
}
Ii. Obtain the OS version:
OSVERSIONINFO OsVersionInfo; // data structure containing the operating system version information
OsVersionInfo. dwOSVersionInfoSize = sizeof (OSVERSIONINFO );
GetVersionEx (& OsVersionInfo); // get the operating system version
Ii. Set the dialog box to the top level: (add in OnInitDialog)
SetWindowPos (& wndTopMost, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
II. The Dialog Box program is not displayed on the taskbar: (add in OnInitDialog)
ModifyStyleEx (WS_EX_APPWINDOW, WS_EX_TOOLWINDOW );
Thirty. Right-click a menu in the dialog box:
CMenu menu, * pmenu;
Menu. LoadMenu (IDR_MENU1 );
Pmenu = menu. GetSubMenu (0 );

CPoint ptScreen (point );
ClientToScreen (& ptScreen );

Pmenu-> TrackPopupMenu (TPM_RIGHTBUTTON, ptScreen. x, ptScreen. y, this );
Sany, file search: (for example, find continuous line breaks)
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 );
3. solution:
Use the following code after the menu:
CPoint pt;
GetCursorPos (& pt );

SetForegroundWindow ();
Policymenu. TrackPopupMenu (TPM_RIGHTBUTTON, pt. x, pt. y, this );
PostMessage (WM_NULL, 0, 0 );
3. animation effects displayed in the dialog box from small to large:
Add:
ShowWindow (SW_HIDE );
CRect dlgRect;
GetClientRect (& dlgRect );
CPoint centerPoint;
CenterPoint. x = dlgRect. Width ()/2;
CenterPoint. y = dlgRect. Height ()/2; // obtain the midpoint coordinate of the dialog box.
CRgn testrgn;
This-> ShowWindow (SW_HIDE );
Int m = GetSystemMetrics (SM_CYSIZEFRAME );

// The following code is displayed dynamically in the implementation dialog box.

For (int I = 10; I <dlgRect. Width ()/2 + m; I + = 1)
{
Testrgn. CreateRectRgn (centerPoint. x-I, centerPoint. y-I, centerPoint. x + I, centerPoint. y + I );
Setjavaswrgn (HRGN) testrgn, TRUE );
ShowWindow (SW_SHOW );
CenterWindow ();
Testrgn. DeleteObject ();
}
3. Read text files by line:
The following example shows how to fetch a row until the result is obtained.
CStdioFile myFile;
CString ReadFileString;
If (myFile. Open ("C: // Readme.txt", Cfile: modeRead) = TRUE)
{
While (myFile. ReadString (ReadFileString )! = FALSE)
{
//... Process Code
}
}
5. When IDC_HAND is used, the system prompts undefined. Add the following code:
# If (WINVER> = 0x0500)
# Define IDC_HAND MAKEINTRESOURCE (32649)
# Endif/* WINVER> = 0x0500 */
3. Disable Automatic Creation of documents when the application starts
By default, the SDI/MDI application developed with AppWizard creates a new document at startup. To enable the application to not create a new document at startup, you only need to add the following statement before calling ProcessShellCommand of the application class CmyApp: InitInstance () function:
Using info. m_nShellCommand = CComandLineInfo: FileNothing;
Play mp3:
CFileDialog file (true );
If (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. Obtain the RGB value of the screen: add it to OnTimer
CPoint pos;
GetCursorPos (& pos); // get the mouse coordinates
HDC hDC =: GetDC (NULL );
COLORREF clr =: GetPixel (hDC, pos. x, pos. y );

CString ClrText;
ClrText. Format ("R: % d G: % d B: % d", GetRvalue (clr), GetGvalue (clr), GetBvalue (clr ));
3. Open a website:
Open the [url] http://www.sina.com.cn [/url] site as follows:
ShellExecute (NULL, "open", "http://www.sina.com.cn", NULL, NULL, SW_MAXIMIZE );
This command opens the [url] http://www.sina.com.cn [/url] in the default browser and maximizes the Opened Window.
Another example:
ShellExecute (NULL, "open", "IEXPLORE.exe [url] http://www.sina.com.cn [/url]", NULL, NULL, SW_MAXIMIZE );
This command will directly use IE to open an sina site. However, a new window will be opened.
40. Bitmap Buttons:
CButton * pRadio = (CButton *) GetDlgItem (IDC_RADIO );
PRadio-> SetBitmap (: LoadBitmap (AfxGetInstanceHandle (), MAKEINTRESOURCE (IDB_BITMAP )));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.