MFC uses the MFC menu, Font dialog box, OnSize function to implement simple Notepad

Source: Internet
Author: User



After a lot of MFC has understood a lot of features, but the previous project has not been used to the MFC menu function, menu is WIN32 function is very common things, this also must understand. In fact, the establishment of the menu is very simple, with the previous file operation function, has been able to start-and accessories, Notepad, is that Notepad.exe written out.






I. BASIC OBJECTIVES



First of all, this notepad can be maximized, minimized, the inside of the edit box can also keep up to minimize, that is, Notepad inside the components will not be distorted, this is not a matter of course, to write to OnSize, otherwise the components will not follow the maximum, this is probably the reason why MFC is more difficult than VB it!






After that, the form size of this notepad is the same as the window of the usual windows, it can be resized freely and has the corresponding menu. By Help, you can display copyright information. In fact, the Notepad has been copied very much like, but if the copyright information is too ugly ~






Clicking on the "New" button pops up and tells the user that if you continue with this command, all unsaved information will be lost and if the user clicks "Yes", create a new file






After that it is open and save, Save as function, here will no longer describe what it is like, just like your usual notepad.









The last is to set the font function, to set the font that Notepad displays, which is the same as the Notepad in Windows, after all, Notepad is a plain text editor, the design font just set its display font only! After the user selects the appropriate font, the font in Notepad is displayed in the font selected by the user.









Second, the preparation process



1, first or new A simple MFC project, there is nothing, we add later, mainly Windows comes with something too slag, we write it out more beautiful. If you don't even create MFC, it doesn't matter, you can read my previous article






2, the new project with the previous "MFC" with the dialog box to switch the implementation of re-login "(Click the Open link), the OnOK function of the OK button to comment out, lest this dialog box a press ENTER will not






3, after the dialog box to pull the components into the form, while the various components of the style set:






4, after that, we began to create a menu for this dialog box, for example, to insert resources for the project, such as "MFC" For the dialog Box Program optimization and icon for the program (click on the Open link) in the same way, the menu is a resource, but the menu is edited differently.






5, the menu editor as shown, there is also a "separator" option, if a little separator, everything in the component will be dimmed, the system automatically recognizes that this is a "delimiter" rather than a functional sub-menu






6, Long Press a submenu drag to change the location of the sub-menu






7, according to the above way, set up a menu like, then switch the main dialog box Cxxdlg, where xx for your project name, in this main dialog box style add menu






8. After that, add the corresponding class function for each menu






9. Associating the message map function of the submenu of this menu with the dialog box, set its function name, and then add the function






10, submenu created the message map function is the same as the function of the component, can see in the ClassView, of course, double-click ClassView inside the function is also able to edit, for all sub-menu, that is, those "new", "open" ... After adding the message map function, we can formally write the program.









Three, the various sub-menu function production



Although the above preparation function is many, but after the function is very simple, the component layout completes, then writes some short function to complete, this is the Microsoft's programming characteristic, it does not resemble in the Java the swing, the layout must write a lot of code. Now do Microsoft programming people despise write Java, say write a big paragraph then can realize a function, write Java despise write Microsoft, say is drag control, who also look down who. In fact, the ignorant is the most terrible, each has its own characteristics, control you do not understand and do not drag, code you do not understand that you think to write a large paragraph to achieve their own functions, mainly their own waste, not related to other programming language things. Both of you know the king. Well, the nonsense is not much to say, back to this function inside.






(a) The size of the edit box varies with the size of the window



1, first you want to add a window message processing function for this main function, find wm_size Add, this and "MFC" To use the file read and write, THEAPP global variable to real login account management System " (Click the Open link) to add OnInitDialog and ondestory. Not much to say, do not understand can be turned over my previous log.






2, after the OnSize function to write the following code, this function is mainly for the user to adjust the window size of the response, including the maximization, but does not include the minimization. The minimized function system can be implemented by itself, but it will turn its window coordinates into negative numbers, resulting in a negative value of the size of the control based on the window size below, and the program crashes. So the right thing to do is that once the coordinates of the window become negative, do not execute the code.






Void CNotepadDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
/ / After minimizing, the window coordinate value of the control will become negative, and then restored, at this time, lastwindowrect is negative,
/ / You need to judge the following code, otherwise the program will go wrong
If(nType!=SIZE_MINIMIZED){
CWnd *pWnd;
/ / Get the handle of the space with ID i
pWnd = GetDlgItem(IDC_EDIT1);
CRect rect; / / Get the size of the control before the change
/ / Determine whether it is empty, because the dialog will be created when the function is created, and the control has not been created
If(pWnd){
pWnd->GetWindowRect(&rect);
ScreenToClient(&rect);//Convert the size of the control to the area coordinates in the dialog
//cx/m_rect.Width() is the proportion of the dialog in the horizontal direction.
//cy/m_rect.Height() is the proportion of the dialog in the vertical direction.
Rect.left=rect.left*cx/rect.Width();//Adjust the size of the control
Rect.right=rect.right*cx/rect.Width();
Rect.top=rect.top*cy/rect.Height();
Rect.bottom=rect.bottom*cy/rect.Height();
pWnd->MoveWindow(rect);//Set the control size
}
GetClientRect(&rect);//Replace the changed dialog size with the old size
}
}

(b) Copyright Information





This is not much to say, this and "MFC" using the file read and write, Theapp global variables to the real login account management system (click to open the link) Also in the dialog box to switch the same, first draw a good copyrightdlg this dialog box, and then for this dialog box New Class Wizard, Then because Copyrightdlg does not have any function except the display and the self-brought off function, Copyrightdlg does not have to write anything at all, just need to be in the main function "Help", "about ..." class function, introduce the header file, write open "about ..." The Code of the dialog box can be




#include "CopyrightDlg.h"

void CNotepadDlg::OnCopyright() 
{
	// TODO: Add your command handler code here
	CCopyrightDlg dlg;
	dlg.DoModal();
	
}



After the code is involved in the file operation, so first at the beginning of the NotepadDlg.cpp this file, that is, containing a bunch of sub-menu this CPP, the beginning of the introduction of CString filename, this global variable, just below the code of #endif this line of the system, let "new , "Open", "save" and so on named share this file variable, because there is only one dialog box, so there is no need to blowing out, such as "MFC" Using the System File dialog box to open the file and save the file, the use of StdAfx.h set global variables (click Open link), Write variables into the StdAfx.h, without having to share the variable with multiple dialog boxes.



(iii) New document,



The code is as simple as:






Void CNotepadDlg::OnFileNew()
{
// TODO: Add your command handler code here
If(IDNO==MessageBox("All unsaved information, will be lost, continue?", "Notepad", MB_YESNO)
Return;
SetDlgItemText(IDC_EDIT1,"");
SetWindowText("Notepad");
Filename="";

}

First, the window prompts the user whether to continue, and then the text box, title bar, operation of the file path empty.








(d) Opening of documents



This is a bit difficult, although the basic principle and the "MFC" Using the System File dialog box to open the file and save the file, the use of StdAfx.h set global variables (click to open the link), but here is the edit box operation, not the list space, therefore, You first have to read all the contents of the file into a character array and then read it into the edit box. Note After you open the file, update the title bar, the path to the current control file.



Void CNotepadDlg::OnFileOpen()
{
If(IDNO==MessageBox("All unsaved information, will be lost, continue?", "Notepad", MB_YESNO)
Return;
CFileDialog dlg(TRUE,"txt","",OFN_HIDEREADONLY,"text file(*.txt)|*.txt||");
If(IDCANCEL==dlg.DoModal()){
Return;
}
Filename=dlg.GetPathName();
SetWindowText(filename);
CFile file;
If(!file.Open(filename,CFile::modeRead|CFile::shareDenyNone)){
AfxMessageBox ("Open file failed");
Return;
}
/ / Read the size of the file to open
/ / Then create a corresponding size array of characters according to the size of the open file
CFileStatus stat;
file.GetStatus(stat);
//+1 is because we want to make an array of characters, then make up \0
Char *pText=new char[stat.m_size+1];
/ / file.Read return value is the size of the file read
Int nRet=file.Read(pText,stat.m_size);
pText[nRet]='\0';
/ / Put the read out into the text box, and then delete the string array
SetDlgItemText(IDC_EDIT1,pText);
Delete []pText;
file.Close();
}

(v) file-save





First read the current control of the file path, which is defined at the beginning of the filename, if not read, prove that the user has not opened the file, select the "Save" button, directly drag the "Save as" processing, using a CString as the content of the edit box and the file transition, Write the contents of this CString to the file, and it's done.






void CNotepadDlg::OnFileSave() 
{
	// TODO: Add your command handler code here
	CFile file;
	if(!file.Open(filename,CFile::modeCreate|CFile::modeWrite)){
		CNotepadDlg::OnFileSaveas();
		return;
	}
	CString string;
	GetDlgItemText(IDC_EDIT1,string);
	file.Write(string,string.GetLength());
	file.Close();
}

(vi) file-Save as





You naturally want to pop up a "save as" CFileDialog to the user, and then this through CFileDialog, such as "MFC" Using the System File dialog box to open the file and save the file, the use of StdAfx.h set global variables (click Open link) to get to the file path, Then write to the file as "save" above. Note that the title bar is also updated here.




Void CNotepadDlg::OnFileSaveas()
{
// TODO: Add your command handler code here
CFileDialog dlg(FALSE,"txt","",OFN_OVERWRITEPROMPT,"text file(*.txt)|*.txt||");
If(IDCANCEL==dlg.DoModal()){
Return;
}
CFile file;
Filename=dlg.GetPathName();
If(!file.Open(filename,CFile::modeCreate|CFile::modeWrite)){
AfxMessageBox ("Save file failed");
Return;
}
CString string;
GetDlgItemText(IDC_EDIT1,string);
file.Write(string,string.GetLength());
file.Close();
SetWindowText(filename);
}

(vii) format-font





The main thing is to set the display font, in order to make the font's brilliance just stay in the Onfontset function, and here, you have to write the CFont font in the beginning like CString filename, and then, as shown in the following code






Void CNotepadDlg::OnFontSet()
{
// TODO: Add your command handler code here

//lf is a pointer to a font
LOGFONT lf={0};
/ / If the font already exists, then get the information of the current font
If(font.GetSafeHandle()){
font.GetLogFont(&lf);
}
/ / font settings need to go to the system's font editing dialog box, the parameters inside is the font pointed to by lf
/ / Open the font editing dialog box automatically select this font
CFontDialog dlg(&lf);
If(IDCANCEL==dlg.DoModal()){
Return;
}
/ / This will be obtained, the user selected font is saved to a CFont object named font
//where CFont font; has defined the global variable cost cpp at the beginning of the file in this file.
dlg.GetCurrentFont(&lf);
font.DeleteObject();
font.CreateFontIndirect(&lf);
/ / Remove the handle of the operation text input box m_edit, then m_edit is the handle of the operation of this dialog box
CEdit* m_edit=(CEdit*)GetDlgItem(IDC_EDIT1);
M_edit->SetFont(&font);
} 

Iv. Summary and Prospect





At this point, the entire high-imitation Notepad is finished. Of course, there are "edit" in the revocation function, this estimate to design a linked list to record the operation of the user, cut, copy, paste design of MFC in the ClipBoard.exe of the shear plate operation, the estimated should have the function, has not been studied. Find and Replace with CFileDialog, CFontDialog, there is a dialog box, use this dialog box to get the user input, the text of the current edit box to save a CString, and then the C language of the CString to traverse, find and replace the operation ......



MFC uses the MFC menu, Font dialog box, OnSize function to implement simple Notepad


Related Article

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.