"MFC" uses the file to read and write, Theapp global variables to the real login account management system

Source: Internet
Author: User

This article is also in the "MFC" with the dialog box switch implementation of the re-login "(Click to open the link) further work, but also to its further improvements, the last login is only to determine whether the user entered the user name and password is the admin and 123, this time using the file read and write to achieve user account creation, deletion and modification , no longer with the admin and 123 This account, the user can create a lot of accounts, and give them permission to modify the account, at the same time, the use of Theapp global variables, the user once successful, their login information will always be recorded, similar to the session in the Web page. Although now VC6 in the MFC is outdated, but still has the research significance, after all, XP once was a cannot surpass the era!

I. BASIC OBJECTIVES

1, in the rights management, the user can add to the login account, delete, modify management, and give different permissions, if the user's "user name", "Password" is empty, it is considered that the user does not make this modification. At the same time, users must be required to keep at least one account with "Advanced" permissions


2, re-login can be found, just added the account has been effective, only the "advanced" permission of the account to enter the "account management" to modify the user information, and "normal" permissions of the account is not allowed to enter


Second, the production process

"Login" and "Re-login" function, "Control Panel" in the "MFC" with the dialog box switch implementation re-login "(click Open link) in the focus on how to complete, this chapter mainly describes how to complete the" Account Management "function

1. First, insert a dialog box in the resource list


2, delete the "OK" and "delete" button, change the font of the dialog box to 9th, because this dialog box to accommodate a lot of things, the title bar to "Rights Management", add three static text and two edit box, how to add the "MFC" with the dialog page to implement user login "(click Open link) has said , mainly a drop-down control combobox for permissions, to change the style


3, it is worth noting that this drop-down list after adjusting the position and style, pay attention to its triangle to adjust the size of each drop-down option, otherwise the drop-down option is too small to see at all. Only through the keyboard on and down to choose, this is very wretched!


4, after adding three buttons, the button can be in its caption style with "& Shortcut Keys" Way to add shortcut keys, increase the user experience


5, the last pull out of the list control, and set the appropriate style, the control in the "MFC" Student information management, the implementation of List control node additions and deletions (click to open the link) has been highlighted, here no longer repeat, in order to make your program more beautiful, Use the Control Layout tool below to adjust the position of the control.


6, such as "MFC" with the dialog box switch implementation re-login "(click Open link) the same as for this prior dialog box Add Class Wizard, and named Cpriordlg, you want to add a form message function for this dialog box


7. From the list on the left, find the form initialization event, which is what the form does when it is opened and what it does when the form is destroyed, that is, when the form is closed. This is essentially the message map function when you click on the button, but one is the click of the button, tell the system what needs to be done, now is the capture system at a certain time, do what



8, click OK, you can in the ClassView class list, under Cpriordlg, find OnInitDialog () This class, in the bool Cpriordlg::oninitdialog () function, the use of system initialization to complete two things, (1) Initialize the control, (2) Read the user list Readuser () from the file, so the function is as follows:

BOOL Cpriordlg::oninitdialog () {cdialog::oninitdialog ();//Set this form to display SetWindowLong in the taskbar (This->getsafehwnd (), GWL_ ExStyle, Ws_ex_appwindow);//Initialize list control clistctrl* plist= (clistctrl*) GetDlgItem (idc_list1);p list->insertcolumn (0 , "account", 0,100);p list->insertcolumn (1, "password", 0,100);p list->insertcolumn (2, "Permissions", 0,100);//initialization, you must first add the column, This function is called, otherwise the list control does not have Readuser (plist);//Initialize drop-down list combo control ccombobox* pcombo= (ccombobox*) GetDlgItem (IDC_COMBO1); Pcombo->addstring ("normal");p combo->addstring ("advanced");//Set drop-down list combo control the default option is the first Pcombo->setcursel (0); return TRUE;  Return TRUE unless you set the focus to a control              //Exception:ocx property Pages should return FALSE}
9, because reading from the file user list is a separate function, also because its statement is more complex, there is no need to blend in the bool Cpriordlg::oninitdialog () function, so we open a function called Readuser (), You can add your own function as follows, right-click the Cpriordlg, and select Add member function:

10, enter the function's noun and return value in the popup dialog box, of course, you can write your own handwriting,

The Readuser function is to throw a pointer to the control list and then manipulate it, with the following function:

void Cpriordlg::readuser (CListCtrl *plist) {//First empty the original and refresh the Plist->deleteallitems (); CFile File;//cfile::sharedenynone is this file allows to be opened by multiple individuals, by default only one thread is allowed to operate if (!file. Open ("User.dat", cfile::moderead| Cfile::sharedenynone)) {return;} Suser U;int i=0;//read out must match the size of the struct, do not match, either read it or read the error while (file. Read (&u,sizeof (U)) ==sizeof (U)) {//The whole process is very similar to inserting into a column, basically the same plist->insertitem (i,u.sname);p list-> Setitemtext (I,1,U.SPWD); switch (u.prior) {case 0:plist->setitemtext (i,2, "normal"); Break;case 1:plist-> Setitemtext (i,2, "advanced"); break;}} File. Close ();}

The CFile class makes it easy to manipulate files, and if a file fails to read, it is returned with a struct suser, which normalizes the structure's size from the User.dat file each time, and then assigns the contents of the structure to the program. Since this struct is used in many other functions, other classes, and other dialogs, it may be useful to set this structure to a global variable for the entire program.

11, Find Cxxapp class, where xx is the project name you are editing, such as I am editing the project called Isys, then find Cisysapp, directly double-click this class, It also enters into the header file of this class CIsysApp.h, in which defines a structure as shown in Suser, which contains two strings of length 20 to record the user name and password, with a record permission to reshape. And by the way in the following public to set up a m_info, specifically to save the login information, and then in any place to use, in its non-header file, that is, you can click its subordinate class to enter its. cpp instead of. h, add an extern cxxapp Theapp; Can, in the picture misspelled words, forgive me!


12, so set, back to the Cpriordlg in the compilation found no problem, the following continue to complete the CPRIORDLG in the OnDestroy function void Cpriordlg::ondestroy (), The main task of the whole function is to write the contents of this list control to User.dat

Once the dialog box is closed, no matter what value is returned, execute this function void Cpriordlg::ondestroy () {Cdialog::ondestroy (); CFile file; Suser u;//todo:add Your message Handler code here//open a User.dat file in the current directory, and No if (!file. Open ("User.dat", cfile::modecreate| Cfile::modewrite) {AfxMessageBox ("failed to create/Open file"); return;} The same as above is a list of traversed lists of operations clistctrl* plist= (clistctrl*) GetDlgItem (IDC_LIST1);//If the user has deleted all users, we will re-put the admin, 123 This default account activates int ncount=plist->getitemcount (); the if (ncount==0) {//character array operation must be done in the following way, u.sname= "admin"; strcpy ( U.sname, "admin"); strcpy (U.spwd, "123"); U.prior=1;file. Write (&u,sizeof (U));} else{for (int i=0;i<ncount;i++) {///write Plist->getitemtext (i,0) is not saved anywhere, only returns a retrieved value Plist->getitemtext (i,0, U.sname,sizeof (u.sname));p List->getitemtext (i,1,u.spwd,sizeof (u.spwd)); if (Plist->getitemtext (i,2) = = "Advanced") U.prior=1;elseu. prior=0;//the contents of the structure into a file. Write (&u,sizeof (U));}} When the file is finished, the file is closed or not, because after the function is finished, the object file will be refactored. Close ();}
This user.dat directly with Notepad will be garbled, but the use of the structure of reading and writing can be read and write without hindrance:

13, then go back to the dialog box in the Resource list, double-click the "Add", "delete", "Modify" button to complete the following message map function, because the form opened and closed when the operation of the file has been involved, there is no need for users to modify the side of the save, the general function and "MFC" Student Information management, Implementation of the list control node additions and deletions (click the open link) is basically the same:

(1) for Add button void Cpriordlg::onbutton3 ()

void Cpriordlg::onbutton3 () {///Todo:add your control notification handler code here//gets the value of the input box suser u; GetDlgItemText (idc_edit1,u.sname,sizeof (u.sname)); GetDlgItemText (idc_edit2,u.spwd,sizeof (U.SPWD));//If the input box has nothing to do, it is not necessary to execute the prompt error if (u.sname[0]== ' | | u.spwd[0]== ' + ') {AfxMessageBox ("The user name or password entered is empty! "); return;} clistctrl* plist= (clistctrl*) GetDlgItem (Idc_list1),//plist->getitemcount () is able to find out how many int ncount= the current list control has. Plist->getitemcount (); for (int i=0;i<ncount;i++) {if (Plist->getitemtext (i,0) ==u.sname) {AfxMessageBox (" The user name you want to insert already exists! ");//query to exist directly interrupt the cycle, there is no need to go on; return;}} If not, insert the last line of the list to Plist->insertitem (ncount,u.sname);//To insert the acquired password into the 2nd column of the newly opened row Plist->setitemtext ( NCOUNT,1,U.SPWD)///The following is the value of the Get drop-down list ccombobox* pcombo= (ccombobox*) GetDlgItem (IDC_COMBO1);//pcombo->getcursel (); The current drop-down list is selected as the number of int Nsel=pcombo->getcursel (), switch (Nsel) {case 0:plist->setitemtext (ncount,2, "normal"); Case 1:plist->setitemtext (ncount,2, "advanced"); After adding empty two input boxes Setdlgitemtext (idc_edit1, ""); SetdlgiteMText (Idc_edit2, "");} 

(2) For the delete button void Cpriordlg::onbutton4 (), where once the user deletes an object, they must traverse the entire list to see if they are normal permissions, and if so, we pop the window and force the last item in the list of controls back to "advanced":

void Cpriordlg::onbutton4 () {//Todo:add your control notification handler code Hereclistctrl *plist= (CListCtrl *) Getdlgi TEM (IDC_LIST1); POSITION pos=plist->getfirstselecteditemposition (); int Nsel=plist->getnextselecteditem (POS); if (nSel<0) AfxMessageBox ("Please select the item you want to delete! ", MB_OK); Else{if (AfxMessageBox (" Confirm Delete: "+plist->getitemtext (nsel,0) +"?) ", Mb_yesno) ==idyes) {Plist->deleteitem (nsel); int Ncount=plist->getitemcount (); BOOL Is_all_putong = true;for (int i=0;i<ncount;i++) {if (Plist->getitemtext (i,2) = = "Advanced") Is_all_putong = FALSE;} if (Is_all_putong) {AfxMessageBox ("must have an advanced rights account!") ");p List->setitemtext (ncount-1,2," Advanced ");}}}

(3) for the modification of the button void Cpriordlg::onbutton5 (), the same should be in the user every time after the modification of a traverse, whether it is normal permissions, if so, we automatically change the user to change the item from "Normal" to force back to "advanced"

void Cpriordlg::onbutton5 () {//Todo:add your control notification handler code Hereclistctrl *plist= (CListCtrl *) Getdlgi TEM (IDC_LIST1); POSITION pos=plist->getfirstselecteditemposition (); int Nsel=plist->getnextselecteditem (POS); if (nSel<0) AfxMessageBox ("Please select the item you want to modify!") ", MB_OK); Else{if (AfxMessageBox (" Confirm the changes? ", Mb_yesno) ==idyes) {CString str; GetDlgItemText (IDC_EDIT1,STR); if (!str. IsEmpty ()) Plist->setitemtext (NSEL,0,STR); GetDlgItemText (IDC_EDIT2,STR); if (!str. IsEmpty ()) Plist->setitemtext (NSEL,1,STR); ccombobox* pcombo= (ccombobox*) GetDlgItem (IDC_COMBO1); int Nselect=pcombo->getcursel (); switch (nselect) {case 0: Plist->setitemtext (nsel,2, "normal"), Break;case 1:plist->setitemtext (nsel,2, "advanced"); int Ncount=plist->getitemcount (); BOOL Is_all_putong = true;for (int i=0;i<ncount;i++) {if (Plist->getitemtext (i,2) = = "Advanced") Is_all_putong = FALSE;} if (Is_all_putong) {AfxMessageBox ("must have an advanced rights account!") ");p List->setitemtext (nsel,2," Advanced ");}}}

14, the entire rights management form to complete, we also want to modify the previous program, complete with the previous "MFC" with the switch implementation of the dialog box to re-login "(click Open link) that program in series.

(1) First to rewrite the control panel to initialize the bool Cisysdlg::oninitdialog () function, because the Control Panel this dialog box in the new project, all this function does not need to add a form message function like Cpriordlg, directly rewrite on the line, See what the user's permissions are to determine whether the open Account Management button, due to the use of the global variables, must be extern cisysapp Theapp;:

extern Cisysapp Theapp; BOOL Cisysdlg::oninitdialog () {cdialog::oninitdialog ();//Set the global login information to the window caption CString wintitle= "Control Panel-Welcome"; SetWindowLong (This->getsafehwnd (), Gwl_exstyle, Ws_ex_appwindow); Wintitle+=theapp.m_info.sname; wintitle+= "Login"; SetWindowText (wintitle);//The EnableWindow method in the call control, EnableWindow (0) disables the button, EnableWindow (1) enables the button//showwindow (0) Then hide this button, see GetDlgItem (Idc_button2)->enablewindow (theapp.m_info. Prior);//Set The icon for this dialog.  The framework does this automatically//when the  application ' s main window was not a Dialogseticon (M_hicon, TRUE);//Se T Big Iconseticon (M_hicon, FALSE);//Set small icon//todo:add extra initialization herereturn TRUE;  Return TRUE  Unless you set the focus to a control}

(2) After the Button2 is the "account management" this button to increase the message mapping function, because to pop up the "Rights Management" modal box, so to introduce the header file PriorDlg.h:

#include "PriorDlg.h" void Cisysdlg::onbutton2 () {//The logic of this code is the same as "re-login" above, hide this dialog box, and then show it//There is no need for any logical judgment, because "rights management" The interface has only one result, close! ShowWindow (Sw_hide); Cpriordlg Dlg;dlg. DoModal (); ShowWindow (sw_show);}

(3) for the previously written re-login button to add the form to set the title of the sentence, mainly after re-login, to refresh the form title

#include "LoginDlg.h" void Cisysdlg::onbutton1 () {//First hide this dialog box ShowWindow (sw_hide);//Popup Login dialog box Clogindlg dlg;// Finally re-display this dialog box, if the user points to "cancel" if not logged in successfully, then because the Login dialog box returns Idcancel,enddialog (-1); be able to exit the entire program if (Idcancel==dlg. DoModal ()) EndDialog ( -1), else{cstring wintitle= "Control Panel-Welcome"; Wintitle+=theapp.m_info.sname; wintitle+= "Login"; SetWindowText (Wintitle); GetDlgItem (Idc_button2)->enablewindow (theapp.m_info. Prior); ShowWindow (Sw_show);}}

15, Theapp in the M_info this global variable of course also to refresh, at the same time, our Login dialog box is no longer the admin and 123 this account to make a simple judgment, so to the "MFC" with the dialog box switch implementation re-login " (Click to open the link) to write the function in the Clogindlg to rewrite, first of all, the inside of the OK button:

extern Cisysapp theapp;void Clogindlg::onok () {//Todo:add extra validation herecstring sid,spwd; GetDlgItemText (IDC_EDIT1,SID); GetDlgItemText (IDC_EDIT2,SPWD); CFile file;if (!file. Open ("User.dat", cfile::moderead| Cfile::sharedenynone) {if (sid== "admin" &&spwd== "123") {strcpy (theApp.m_info.sName, "admin"); strcpy ( THEAPP.M_INFO.SPWD, "123"); Theapp.m_info. prior=1;//Closes this dialog box and returns Idokcdialog::onok () to DoModal ();} Elseafxmessagebox ("Username or password is wrong!") ");} Else{if (CheckUser ())//Close this dialog box and return Idokcdialog::onok () to DoModal (); Elseafxmessagebox ("Username or password is wrong!"). ");}}

We also open a new function for the login account, as before:


Then write in the inside to get the user name and password you entered, if you can find your user name and password in User.dat, then return to success, if not found in the end, then failed:

BOOL Clogindlg::checkuser () {CString sid,spwd; GetDlgItemText (IDC_EDIT1,SID); GetDlgItemText (IDC_EDIT2,SPWD); CFile file;if (!file. Open ("User.dat", cfile::moderead| Cfile::sharedenynone)) {return false;} Suser u;while (file. Read (&u,sizeof (U)) ==sizeof (U)) {if (sid==u.sname&&spwd==u.spwd) {Theapp.m_info=u;return true;}} File. Close (); return false;}


So far, the whole program is done!

"MFC" uses the file to read and write, Theapp global variables to the real login account management system

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.