C編程常用模塊講課講稿_第1頁
C編程常用模塊講課講稿_第2頁
C編程常用模塊講課講稿_第3頁
C編程常用模塊講課講稿_第4頁
已閱讀5頁,還剩74頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

數(shù)據(jù)庫ー、連接數(shù)據(jù)庫(SQL):(-)直接寫在程序中1、導(dǎo)入動(dòng)態(tài)連接庫#import"C:\ProgramFiles\Commonno_namespace\rename("EOF,,,,,adoEOF,,)rename(,,BOF',,',adoBOF")2、定義Provider宏#defineProviderSecurity=SSPI;\PersistSecuritylnfo=False;lnitialCatalog=HRMS,,3、初始化a).h文件中private:HDCm_hDC;DWORDm_CurrentRecord;_RecordsetPtrm_pRecordset;_ConnectionPtrm_pConnection;b).cpp文件中CADOOperation::CADOOperation(){try(m_pConnection->Open(_bstr_t(Provider),,",,m,,adModellnknown);catch(_com_errore)MB_OK);exit(O);)m_CurrentRecord=-1;)4、執(zhí)行5、關(guān)閉CADOOperation::~CADOOperation(){m_pConnection->Close();voidCBbbApp::lniAdo(){try{CStringtemp;charfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);temp=所在路徑CStringstrAdoConn;chartemp1[100];/*********************************************[DatabaseConfig]Server=.〃.表示本機(jī)Database=BookManageUser=saPWD=sa*********************************************/strserver=(TCHAR*)temp1;strdbName=temp1;strUser=temp1;strPassword=temp1;Server};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s';strserver,strUser,strPassword,strdbName);m_pCon->ConnectionString=(_bstr_t)strAdoConn;m_pCon?>Open(““,““,“ヽNULL);//ADOFLAG=TRUE;)catch(_com_error){//ADOFLAG=FALSE;Flag=FALSE;MessageBox?!闭?qǐng)檢查系統(tǒng)配置信息ジ數(shù)據(jù)庫連接失敗”,MBJDK);return;}catch(...){AfxMessageBox("SYSError");return;C++編程常用模塊(二):連接Access數(shù)據(jù)庫二、連接數(shù)據(jù)庫(Access2000)1、在.h文件中導(dǎo)入動(dòng)態(tài)鏈接庫#import,'C:\ProgramFiles\Common\rename(',EOF,';'adoEOF,,)rename(',BOF,,,',adoBOF,')類定義:classADOConn{public:BOOLExecuteSQL(_bstr_tbstrSQL);ADOConn();virtuaHADOConn();〃添加一個(gè)指向Connection對(duì)象的指針_ConnectionPtrm_pConnection;〃添加一個(gè)指向Recordset對(duì)象的指針_RecordsetPtrmjDRecordset;_RecordsetPtr&GetRecordSet(_bstr_tbstrSQL);voidExitConnect();voidOnlnitADOConn();2,建立連接voidADOConn::OnlnitADOConn()〃初始化〇LE/COM庫環(huán)境::Colnitialize(NULL);try(charfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);CStringstrdb;strdb=ExtractFilePath(filepath)+strdb=MDBQ=M+strdb;〃創(chuàng)建connection對(duì)象m_pConnection->ConnectionTimeout=3;〃設(shè)置連接字符串,兩種都可以//_bstr_t_bstr_tstrConnect=HDRIVER={MicrosoftAccessDriver(*.mdb)};uid=;pwd=sm;M;strConnect=strConnect+strdb;//SERVER和UID,PWD的設(shè)置根據(jù)實(shí)際情況來設(shè)置m_pConnection->Open(strConnect,,,M,,H,,adModeUnknown);)〃捕捉異常catch(_com_errore)〃顯示錯(cuò)誤信息}3、執(zhí)行SQL語句〃僅執(zhí)行,無返回BOOLADOConn::ExecuteSQL(_bstr_tbstrSQL)(try{〃是否已連接數(shù)據(jù)庫if(m_pConnection==NULL)OnlnitADOConn();m_pConnection->Execute(bstrSQL,NULL,adCmdText);returntrue;)catch(_com_errore){returnfalse;})〃返回記錄集_RecordsetPtr&ADOConn::GetRecordSet(_bstr_tbstrSQL)tryif(m_pConnection==NULL)OnlnitADOConn();)catch(_com_errore){}returnm_pRecordset;}4、關(guān)閉連接voidADOConn::ExitConnect(){〃關(guān)閉記錄集和連接if(m_pRecordset!=NULL){m_pRecordset->Close();m_pRecordset=NULL;}if(m_pConnection!=NULL)m_pConnection->Close();m_pConnection=NULL;)〃釋放環(huán)境::Collninitialize();}C++編程常用模塊(三):窗體操作三、窗體操作1、顯示對(duì)話框窗體CDIgLoginlogin;若要處理“確定’’或“取消”:intnResponse=if(nResponse==IDOK){//TODO:Placecodeheretohandlewhenthedialogis//dismissedwithOK)elseif(nResponse==IDCANCEL){//TODO:Placecodeheretohandlewhenthedialogis//dismissedwithCancel}2、關(guān)閉對(duì)話框窗體EndDialog(O);或CDialog::OnCancel();或CDialog::OnOK();3、退出應(yīng)用程序exit(O);4、登錄:P308voidCDIgLogin::OnButton1(){CStringc_user,c_password;ifll{MessageBox(”用戶名稱或密碼不能為空“,”用戶登錄信息”);return;}CStringsql;*fromtb_operatorwherename=,%s'andpassword=,%s,,,,c_user,cjDassword);m_pRs->raw_Close();//if(m_pRs->RecordCount>0)或者if->adoEOF){Flag=true;//Flag為全局變量user=m_pRs->GetCollect(,'name").bstrVal;password=m_pRs->GetCollect(,'password',).bstrVal;EndDialog(O);elseuser』"';password="";MessageBox("用戶名或密碼不正確.”,“提示”,64);return;})在程序啟動(dòng)初始化部分BOOLCBbbApp::l制nstance()函數(shù)里完成窗口跳轉(zhuǎn):if(Flag==true){CBbbDIgdlg;〃啟動(dòng)主窗體m_pMainWnd=&dlg;)5、動(dòng)態(tài)創(chuàng)建工具欄:P306方法(一):CToolBarm_toolbar;ClmageListmJmagelist;UINTarray[5];for(inti=0;i<5;i++){array[i]=5000+i;//^'!建索弓I)RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,0);************************押************************押************************#definelDB_bookinfo5000#definelDB_booksell5001#definelDB_sellinfo5002#definelDBset5003#definelDB_cancel5004最后在對(duì)話框的.cpp文件中將控件與響應(yīng)函數(shù)關(guān)聯(lián)起來BEGIN_MESSAGE_MAP(CBbbApp,CWinApp)ON_COMMAND(IDB_bookinfo,OnBooklnfo)ON_COMMAND(IDB_booksellJOnBooklnput)ON_COMMAND(IDB_sellinfoJOnSaleQuery)ON_COMMAND(IDB_set,OnButton4)ON_COMMAND(IDB_cancel,OnCancel)END_MESSAGE_MAP()******************************************************/方法(二):ClmageListmJmageList;CToolBarCtrlm_ToolBar;TBBUTTONtbButton[ICONSUM]={0};32,ILC_COLOR32|ILC_MASK,0,0);|WS_VISIBLE,CRect(0,0,0,0),this,0);for(intj=0;j<ICONSUM;j++)tbButton[j].dwData=NULL;tbButtonO].fsState=TBSTATE_ENABLED;tbButtonO].fsStyle=(BYTE)TBSTYLE_FLAT;tbButton[j].iBitmap=j;}tbButton[0].idCommand=ID_lnfo;tbButton[1].idCommand=ID_MR;tbButton[2].idCommand=ID_QS;tbButton[3].idCommand=ID_XS;tbButton[4].idCommand=ID_HELP;tbButton);|CCS_TOP);6、設(shè)置菜單有效和失效MF_BYCOMMAND|MF_ENABLED);MF_BYCOMMAND|MF_DISABLED|MF_GRAYED);7、設(shè)置狀態(tài)欄CTimeTime;Time=CTime::GetCurrentTime();CStringStr=UINTArray[3];for(inti=0;i<3;i++)Array[i]=10000+i;RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,0);8、設(shè)置菜單欄SetMenu(&m_Menu);9、獲得窗口WindowDCP464CWindowDC*dc=(CWindowDC*)GetWindowDC();10、文檔框架關(guān)閉時(shí),恢復(fù)程序主窗口voidCPrintFram::OnClose(){=NULL;CPrintView*temp=(CPrintView*)this->GetActiveView();if(!temp->ispreview)CFrameWnd::OnClose();}11、窗體標(biāo)題欄加上圖標(biāo)先在頭文件中聲明:HICONm_hlcon;在構(gòu)造函數(shù)中:m_hlcon=AfxGetApp()->Loadlcon(IDI_ICON1);在〇nlnitDialog()中:Setlcon(m_hlcon,TRUE);//SetbigiconSetlcon(m_hlcon,FALSE);//Setsmallicon在〇nPaint()中:voidCSmDlg::OnPaint(){if(lslconic()){CPaintDCdc(this);//devicecontextforpaintingSendMessage(WM_ICONERASEBKGND,(WPARAM)0);//Centericoninclientrectangleintcxlcon=GetSystemMetrics(SM_CXICON);intcylcon=GetSystemMetrics(SM_CYICON);CRectrect;GetClientRect(&rect);intx=-cxlcon+1)/2;inty=-cylcon+1)/2;//Drawtheicony,m_hlcon);}else{CDialog::OnPaint();}}在OnQueryDraglcon()中:HCURSORCSmDlg::OnQueryDraglcon(){return(HCURSOR)m_hlcon;}12、設(shè)置工具欄先添加相應(yīng)的圖標(biāo)資源再在0nl川tDialog。函數(shù)中TBBUTTONtbButton[ICONSUM]={0};32,ILC_COLOR32|ILC_MASK,0,0);|WS_VISIBLE,CRect(0,0,0,0),this,0);for(intj=0;j<ICONSUM;j++){tbButton[j].dwData=NULL;tbButtonO].fsState=TBSTATE_ENABLED;tbButton[j].fsStyle=(BYTE)TBSTYLE_FLAT;tbButton[j].iBitmap=j;}tbButton[0].idCommand=ID_Sw;tbButton[1].idCommand=ID_BI;tbButton[2].idCommand=ID_MR;tbButton[3].idCommand=ID_QR;tbButton[4].idCommand=ID_XR;tbButton[5].idCommand=ID_HELP;tbButton[6].idCommand=ID_Exit;tbButton);|CCS_TOP);13、對(duì)話框的淡入淡出效果#defineAW_CENTER0x0000001〇〃動(dòng)畫#defineAW_HIDE0x00010000〃隱藏BOOLCAutoMsgDIg::〇nlnitDialog()〃淡入CDialog::OnlnitDialog();//TODO:AddextrainitializationhereCenterWindow();DWORDdwStyle=AW_CENTER;HINSTANCEhlnst=typedefBOOL(WINAPIMYFUNC(HWND,DWORD,DWORD));MYFUNC*AnimateWindow;AnimateWindow=(MYFUNC*)::GetProcAddress(hlnst,"AnimateWindow");AnimateWindow(this->m_hWnd,1000,dwStyle);FreeLibrary(hlnst);retumTRUE;〃retumTRUEunlessyousetthefocustoacontrol//EXCEPTION:OCXPropertyPagesshouldreturnFALSE)voidCAutoMsgDlg::OnbtnCancel()〃淡出{//TODO:AddyourcontrolnotificationhandlercodehereDWORDdwStyle=AW_CENTER;HINSTANCEhlnst=typedefBOOL(WINAPIMYFUNC(HWND,DWORD,DWORD));MYFUNC*AnimateWindow;AnimateWindow=(MYFUNC*)::GetProcAddress(hlnst,"AnimateWindow");AnimateWindow(this->GetSafeHwnd(),700,AW_HIDE|dwStyle);FreeLibrary(hlnst);CDialog::OnCancel();}C++編程常用模塊(四):組合框用法四、組合框用法1,獲取控件第一種方法:在向?qū)е刑砑訉?duì)應(yīng)的變量第二種方法:CComboBox*com=(CComboBox*)GetDlgltem(IDC_COMB05);2、清空3、添加內(nèi)容4、移動(dòng)到第一條記錄5,移動(dòng)到下一條記錄6,設(shè)置選項(xiàng)7.根據(jù)內(nèi)容設(shè)值第一種:==0)((CComboBox*)GetDlgltem(IDC_COMBO1))->SetCurSel(0);else((CComboBox*)GetDlgltem(IDC_COMB01))->SetCurSel(1);第二種:8、獲取索引intcurSel=fieldCom->GetCurSel();9、選擇改變嚴(yán)重注意:組合框要設(shè)置成DropList的樣式(Styles)voidCAddlnfo::OnSelchangeCOMBOS(){//TODO:Addyourcontrolnotificationhandlercodehere1=0){)else}10、綁定數(shù)據(jù)voidCDIgSaleBack2::LoadCounterlnfo(){CStringsql;sql=',selectdistinctcounterfromtb_counterinfoH;m_pRs->raw_Close();while(!m_pRs->adoEOF)(*)(_bstr_t)m_pRs->GetFields()->Getltem(',counter")->Value);m_pRs->MoveNext();11、獲取數(shù)據(jù)嚴(yán)重注意:組合框要設(shè)置成DropList的樣式(Styles)C++編程常用模塊(五):控件操作五、控件操作1、控件與變量關(guān)聯(lián)起來在函數(shù)中:voidCAddlnfo::DoDataExchange(CDataExchange*pDX){DDX_Control(pDX,IDC_personlmage,m_personlmage);DDX_Control(pDX,IDC_LIST,m_List);)控件與動(dòng)作關(guān)聯(lián)起來在域中:BEGIN_MESSAGE_MAP(CAddlnfo,CDialog)ON_BN_CLICKED(IDC_btnAdd,OnbtnAdd)ON_BN_CLICKED(IDC_btnModify,OnbtnModify)END_MESSAGE_MAP()2、獲取控件((CDateTimeCtrl*)GetDlgltem(IDC_DATETIMEPICKER1))->GetTime(&sysTime)3、設(shè)置控件的值SetDlgltemText(IDC_EDIT1,str);〃文體框CTimedate=CTime::GetCurrentTime();〃時(shí)間控件((CDateTimeCtrl*)GetDlgltem(IDC_DATETIMEPICKER1))->SetTime(&sysTime);〃時(shí)間控件〃設(shè)置文體框?qū)傩?(CEnt*)GetDlgltem(IDC_EDIT1))->SetFocus();〃定焦((CEdit*)GetDlgltem(IDC_EDIT1))->SetSel(〇,-1)”設(shè)置框內(nèi)容選定狀態(tài)4、從控件中取值〃文件框〃時(shí)間控件((CDateTimeCtrl*)GetDlgltem(IDC_DATETIMEPICKER1))->GetTime(&sysTime);〃時(shí)間控件GetDlgltemText(IDC_COMBO1,str);〃組合框5、隱藏控件GetDlgltem(IDC_SEELIST)->ShowWindow(SW_HIDE);6、設(shè)置控件有效和失效有效:GetDlgltem(IDC_COMBOSGrade)->EnableWindow(true);失效:GetDlgltem(IDC_COMBOSGrade)->EnableWindow(false);7、移動(dòng)焦點(diǎn)到編輯框8.使DateTimePicker只顯示年月CDateTimeCtrrpCtrl=(CDateTimeCtrl*)GetDlgltem(IDC_DATETIMEPICKER1);ASSERT(pCtrl!=NULL);pCtrl->SetFormatLT("yyyy-MM"));9、用!PAdress控件編輯IP地址(1)在。nlnitDialog〇函數(shù)中設(shè)置IP地址的默認(rèn)值CIPAddressCtrrm_Address=(CIPAddressCtrr)GetDlgltem(IDC_IPADDRESS1);m_Address->SetAddress(0,0,0,0);(2)輸入IP地址,并顯示出來CIPAddressCtrl*m_Address=(CIPAddressCtrl*)GetDlgltem(IDC_IPADDRESS1);BYTEnFieldO;BYTEnFieldl;BYTEnField2;BYTEnField3;m_Address->GetAddress(nFieldO,nField1,nField2,nField3);CStringstr_IP;AfxMessageBox(strJP);10、對(duì)編輯框輸入內(nèi)容進(jìn)行控制(1)P艮制輸入框的內(nèi)容為數(shù)字創(chuàng)建一繼承自CEdit類的新類,并在以后使用文本框時(shí)用該類定義,在此類中寫:voidCOnlyNumEdit::OnChar(UINTnChar,UINTnRepCnt,UINTnFlags){//TODO:Addyourmessagehandlercodehereand/orcalldefaultif(nChar==8)//{CEdit::OnChar(nChar,nRepCnt,nFlags);return;)if((nChar<48||nChar>57))//0?O£D1Eate£yXOnChar=O;elseCEdit::OnChar(nChar,nRepCnt,nFlags);}(2)對(duì)輸入的身份證信息進(jìn)行驗(yàn)證1=18)(AfxMessageBox(,^aEeEI-Y0Q2AAeTbD§り;return;)else(intnum=0;charch;for(inti=0;i<17;i++){ch=if(ch>47&&ch<58)num++;)if(i==17){ch=if((ch>47&&ch<58)||(ch==88||ch==120))num++;)if(num!=18)AfxMessageBox(HEaEeE1?YOQeAAeIPD§");return;)else{CStringsyear=intyear=atoi(syear);CStringsmonth=intmonth=atoi(smonth);CStringsday=intday=atoi(sday);BOOLIeap;if(month<1||month>12){AfxMessageBox(咔aEe1?Y0Q5AAeIPD§M);return;)switch(month){easel:case3:case5:case7:case8:case10:case12:if(day<0||day>31){AbcMessageBox(空aEeEi?YOQeAAeIDD§M);return;break;case4:case6:case9:case11:if(day<0||day>30){AfxMessageBox("EaEeE1?YOQeAAeIPD§");return;}break;case2:if(year%4==0){if(year%100!=0)leap=TRUE;elseif(year%400==0)leap=TRUE;elseleap=FALSE;)elseleap=FALSE;if(leap){if(day<0||day>29){AfxMessageBox('tae1?Y0AAeTt>D§");return;elseif(day<0||day>28){AfxMessageBox("£aeEi,Y0AAeTr>D§");return;}break;}))}C++編程常用模塊(六):文件操作六、文件操作1、查找文件CFileFindcf;//strPictureFile文件名2、刪除文件//deltile文件名3、復(fù)制文件CopyFile(strFile,savefilename,false);//strFile源文件,savefilename目標(biāo)文件4、保存到文件voidPrintResult(CString&result){FILE*pFile;pFile="w");if(NULL==pFile)(::MessageBox(NULL,"文件打開出錯(cuò)!","提示",MB_OK);return;)#ifdef_UNICODE2,pFile);1,pFile);#endiffclose(pFile);}5、獲取文件所在路徑charfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);〃可執(zhí)行文件的全部路徑(包括:路徑+文件名)CStringstrFile=ExtractFilePath(filepath)+其中:CStringCBbbApp::ExtractFilePath(LPTSTRfilename)〃返回的僅僅是路徑{CStringappname;appname=AfxGetAppName();〃獲取可執(zhí)行文件的文件名appname=appname+,,.exeM;CStringtemp;intpos;temp=filename;pos=temp=returntemp;)6、獲取程序所在的根目錄:P388GetCurrentDirectory(MAX_PATH,path);7、文件選擇對(duì)話框使用CFileDialogfileDlg(TRUE,"bmp">NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT」位圖文件(*.bmp)「.bmp『’,this);!=IDOK)return;strPictureFile=C++編程常用模塊(七):圖片操作七、圖片操作1、加載圖片并顯示出來charfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);CStringstrFile;strFile=ExtractFilePath(filepath)+"\\lmage\\,'+filename;CFileFindcf;{m_Photo=(HBITMAP)::Loadlmage(::Ab(GetlnstanceHandle(),strFile,IMAGE_BITMAP,150,20〇,LR_LOADFROMFILE|LR_DEFAULTCOLOR|LR_DEFAULTSIZE);〃設(shè)置圖片控件的內(nèi)容}2、保存圖片將圖片文件名保存到數(shù)據(jù)庫,文件本身保存到指定的文件夾中voidCAddlnfo::savelmage(CStringstrTime){CFileFindcf;{charpath[MAX_PATH];GetModuleFileName(NULL,path,MAX_PATH);CStringsavefilename;savefilename=ExtractFilePath(path)+,,\\lmage\\,,+strTime;CopyFile(strPictureFile,savefilename,false);}return;}3、設(shè)置按鈕圖片P463m_BitmapOK=::LoadBitmap(::AfxGetlnstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP?));m_BitmapCancel=::LoadBitmap(::AfxGetlnstanceHandle(),MAKEINTRESOURCE(IDB_BITMAP8));ハ、ListView用法1、初始化|LVS_EX_FULLROWSELECT|LVS_EX_HEADERDRAGDROP|LVS_EX_ONECLICKACTIVATE|LVS_EX_GRIDLINES);〃插入一列列二",LVCFMT_CENTER,80,1);列三",LVCFMT_CENTER,100,2);列四",LVCFMT_CENTER,100,3);列五",LVCFMT_CENTER,80,4);列六",LVCFMT_CENTER,80,4);2、綁定數(shù)據(jù)voidCAddlnfo::BindList(){〃清空ADOConnlc;inti=O;CStringstrsql;*fromt_stable");=〃訪問數(shù)據(jù)庫得到數(shù)據(jù)集〃插入一行i++;}return;}3、單擊voidCAddlnfo::OnClickList(NMHDR*pNMHDR,LRESULT*pResult){//TODO:Addyourcontrolnotificationhandlercodehereintpos=str1=str2=*pResult=O;)4、雙擊voidCDIgBooklnfo1::OnDblclkList1(NMHDR*pNMHDR,LRESULT*pResult){introw=〃獲取單擊列表的行索引if(row!=-1){〃將選中行的信息顯示在編輯框中)*pResult=O;)5,清空6、獲取指定行列的信息GetSubltemRect(row,col,LVIR_LABEL,rect);str=Getltem1ext(row,col);7、設(shè)置列寬P383RECTrect;intwid="〃設(shè)置列寬〃設(shè)置列表擴(kuò)展風(fēng)格九、常用類型操作與變換1ヽCTime到CStringa)第一種:CTimeTime;Time=CTime::GetCurrentTime();CStringSt8〃年一月一日CStringstrNowTime=〃時(shí):分:秒b)第二種:CTimenowTime=CTime::GetCurrentTime();CStringstrTime=_T(,,H);CStringtemp;strTime=strTime+temp;strTime=strTime+temp;strTime=strTime+temp;strTime=strTime+temp;strTime=strTime+temp;strTime=strTime+temp;2、CString至リCTimeSYSTEMTIMEsTime={0};ChangeToDate(str1,&sTime);ChangeToDate(str2,&sTime);m_voidCAddlnfo::ChangeToDate(CStringstr,void*sTime){LPSYSTEMTIMEIpTime=(LPSYSTEMTIME)sTime;intnj;CStringd,m,y;lpTime->wDay=lpTime->wMonth=lpTime->wYear=}3、int到CString”,り;4、float至リCString”,り;5,CString至リintt=atoi(str);6、CString到floatm=atof(str);7、字符串格式化intot_stable(str0,str1,str2,str3,str4,str5,str6)values(1,'%s','%s','%s','%s','%s',"%s")",str11,str22,str33,str44,str55,str66);8、字符串判空9、清除字符串中的空格(I.C++編程常用模塊(十):數(shù)據(jù)庫備份和還原十、數(shù)據(jù)庫備份和還原1、備份P433voidCDBCopy::OnbtnLook()〃瀏覽,選擇文件夾{//TODO:AddyourcontrolnotificationhandlercodehereCStringReturnPach;TCHARszPathLMAX_PATH];BROWS日NFObi;LPITEMIDLISTpltemlDList=SHBrowseForFolder(&bi);if(pltemlDList){if(SHGetPathFromlDList(pltemlDList,szPath))ReturnPach=szPath;)elseReturnPach='n';voidCDBCopy::〇nbtnOk()〃確定備份//TODO:AddyourcontrolnotificationhandlercodehereUpdateData(true);&&{CStringstrpath,strDBSource;strpath=strCopyPath+',\\,,+strSaveAsName4-,,.mdb,';charfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);strDBSource=ExtractFilePath(filepath)+CopyFile(strDBSource,strpath,false);〃復(fù)制文件MessageBox("備份完成!”「提示”,MB_OK|MB」CONEXCLAMATION);CDialog::OnOK();}}2、還原P434voidCDBReturn::OnbtnLook()〃瀏覽,選擇要還原的數(shù)據(jù)庫(//TODO:AddyourcontrolnotificationhandlercodehereCFileDialogdlg(TRUE,”mdb”,NULL,〇FN_HIDEREADONLY|OFN_OVERWRITEPR〇MPT,M(*.mdb)|*.mdbM,NULL);CStringstr;str=}}BOOLCDBReturn::Onln計(jì)Dialog()〃獲取系統(tǒng)數(shù)據(jù)庫{CDialog::OnlnitDialog();//TODO:Addextrainitializationherecharfilepath[MAX_PATH];GetModuleFileName(NULL,filepath,MAX_PATH);strDBExist=ExtractFilePath(filepath)+returnTRUE;//returnTRUEunlessyousetthefocustoacontrol)voidCDBRetum::0nbtnOk()〃還原{//TODO:AddyourcontrolnotificationhandlercodehereCStringstrDBFrom;CopyFile(strDBFrom,strDBExist,false)ル復(fù)制文件MessageBox("還原完成!*');EndDialog(O);}}C++編程常用模塊(十一):窗體上畫線H?ー、窗體上畫線1、普通畫線voidCBaselnfo::OnPaint(){CPaintDCdc(this);//devicecontextforpainting//TODO:AddyourmessagehandlercodehereDrawLine(&dc);//DonotcallCDialog::OnPaint()forpaintingmessages}voidCBaselnfo::DrawLine(CPaintDC*pdc){intij;CPencurpen;pdc->SelectObject(&curpen);pdc->MoveTo(20,40);〃橫線pdc->LineTo(9OO,4O);for(i=3;i<10;i++)pdc->MoveTo(20,i*40);pdc->LineTb(900,i*40);)pdc->MoveTo(120,80);pdc->LineTo(720,80);pdc->MoveTo(780,80);pdc->LineTo(900,80);pdc-〉MoveTo(20,40);〃豎線pdc->Linefb(20,360);pdc->MoveTo(120,40);pdc->Linelb(120,360);for(j=3;j<9;j++)(pdc->MoveTo(j*60,80);pdc->Linelb(j*60,360);}pdc->MoveTo(540,40);pdc->Line7b(540,360);pdc->MoveTo(600,80);pdc->Line7b(600,360);pdc->MoveTo(660,80);pdc->LineTo(660,360);pdc->MoveTo(720,40);pdc->LineTo(720,360);pdc->MoveTo(780,40);pdc->Line7b(780,360);pdc->MoveTo(840,80);pdc->LineTD(840,360);pdc->MoveTo(900,40);pdc->LineTo(900,360);2、動(dòng)態(tài)畫線,獲取鼠標(biāo)單擊點(diǎn)坐標(biāo)voidCWZQDIg::OnLButtonDown(UINTnFlags,CPointpoint){//TODO:Addyourmessagehandlercodehereand/orcalldefaultCCIientDCdc(this);CPencurpen;Invalidate(FALSE);CDialog::OnLButtonDown(nFlags,point);C++編程常用模塊(十二):設(shè)置控件風(fēng)格十二、設(shè)置控件風(fēng)格1、設(shè)置按鈕風(fēng)格I創(chuàng)建CBaseButton類I定義按鈕狀態(tài)I添加函數(shù):virtualvoidDrawltem(LPDRAWITEMSTRUCTIpDrawltemStruct);afx_msgvoidOnLButtonDown(UINTnFlags,CPointpoint);afx_msgvoidOnLButtonllp(UINTnFlags,CPointpoint);afx_msgvoidOnKillFocus(CWnd*pNewWnd);afx_msgvoidOnMouseMove(UINTnFlags,CPointpoint);afx_msgvoidOnPaint();I實(shí)現(xiàn)上述函數(shù)I在需要設(shè)置按鈕風(fēng)格的地方(由文件中)定義按鈕:CBaseButtonm_btnAdd;CBaseButtonm_btnModify;CBaseButtonm_btnDelete;I在.cpp文件中將上述定義關(guān)聯(lián)到控件:voidCAddlnfo::DoDataExchange(CDataExchange*pDX)(DDX_Control(pDX,IDC_btnAdd,m_btnAdd);DDX_Control(pDX,IDC_btnModify,m_btnModify);DDX_Control(pDX,IDC_btnDelete,m_btnDelete);)I具體實(shí)現(xiàn):iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiin//CBaseButtonwindow〃定義按鈕狀態(tài)enumButtonState{bsNormal,bsHot,bsDown};classCBaseButton:publicCButton(//Constructionpublic:CBaseButton();intm_State;//Attributespublic://Operationspublic://Overrides//ClassWizardgeneratedvirtualfunctionoverrides//{{AFX_VIRTUAL(CBaseButton)public:virtualvoidDrawltem(LPDRAWITEMSTRUCTIpDrawltemStruct);//}}AFX_VIRTUAL//Implementationpublic:virtuaHCBaseButton();//Generatedmessagemapfunctionsprotected://{{AFX_MSG(CBaseButton)afx_msgvoidOnLButtonDown(UINTnFlags,CPointpoint);afx_msgvoidOnLButtonllp(UINTnFlags,CPointpoint);afx_msgvoidOnKillFocus(CWnd*pNewWnd);afx_msgvoidOnMouseMove(UINTnFlags,CPointpoint);afx_msgvoidOnPaint();//}}AFX_MSGDECLARE_MESSAGE_MAP());〃〃〃〃〃〃〃〃〃〃〃〃〃〃〃〃ル/〃/〃/〃/〃/〃/〃/〃////〃/〃/〃/〃////〃IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIU//CBaseButtonCBaseButton::CBaseButton()m_State=bsNormal;}CBaseButton::-CBaseButton()(}BEGIN_MESSAGE_MAP(CBaseButton,CButton)//{{AFX_MSG_MAP(CBaseButton)ON_WM_LBUTTONDOWN()ON_WM_LBUTTONUP()ON_WM_KILLFOCUS()ON_WM_MOUSEMOVE()ON_WM_PAINT()//}}AFX_MSG_MAPEND_MESSAGE_MAP()〃〃〃〃〃〃〃〃〃〃ル〃〃〃〃〃〃〃〃〃〃〃〃〃/〃〃〃〃〃〃〃〃〃〃〃〃〃///CBaseButtonmessagehandlersvoidCBaseButton::Drawltem(LPDRAWITEMSTRUCTIpDrawltemStruct)(//TODO:AddyourcodetodrawthespecifieditemOnPaint();CDC*pDC;pDC=CDC::FromHandle(lpDrawltemStruct->hDC);UINTstate=lpDrawltemStruct->itemState;CRectfocRC,RC=lpDrawltemStruct->rcltem;=+2;=-2;=+2;=-2;if(state&ODS_FOCUS)(pDC->DrawFocusRect(&focRC);lpDrawltemStruct->itemAction=ODA_FOCUS;}}voidCBaseButton::OnPaint()(CPaintDCdc(this);//devicecontextforpainting//TODO:AddyourmessagehandlercodehereCWnd*pWnd=this;CRectforRC,RC;CFontFont;CFonfpOldFont;CBrushBrush;CBrush*pOldBrush;CPointPT(2,2);CStringText;OUT_TT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUAUTY,\VARIABLE.PITCHIFF.SWISS/'MSSansSerif");pOldFont=if(m_State==bsNormal)(CBitmapbmp;}elseif(m_State==bsDown)(CBitmapbmp;elseif(m_State==bsHot)CBitmapbmp;}pOldBrush=pWnd->GetClientRect(&RC);HRGNhRgn=pWnd->SetWindowRgn(hRgn,TRUE);DeleteObject(hRgn);pWnd->GetWindowText(Text);//DonotcallCButton::OnPaint()forpaintingmessages}voidCBaseButton::OnLButtonDown(UINTnFlags,CPointpoint)//TODO:Addyourmessagehandlercodehereand/orcalldefaultm_State=bsDown;this->lnvalidateRect(NULL,TRUE);CButton::OnLButtonDown(nFlags,point);}voidCBaseButton::OnLButtonUp(UINTnFlags,CPointpoint)(//TODO:Addyourmessagehandlercodehereand/orcalldefaultif(m_State!=bsNormal)(m_State=bsNormal;ReleaseCapture();this->lnvalidateRect(NULL,TRUE);}::SendMessage(GetParent()->m_hWnd,WM_COMMAND,GetDlgCtrllD(),(LPARAM)m_hWnd);CButton::OnLButtonllp(nFlags,point);}voidCBaseButton::OnKillFocus(CWnd*pNewWnd)(CButton::OnKillFocus(pNewWnd);//TODO:Addyourmessagehandlercodeherem_State=bsNormal;this->lnvalidateRect(NULL,TRUE);voidCBaseButton::OnMouseMove(UINTnFlags,CPointpoint)(//TODO:Addyourmessagehandlercodehereand/orcalldefaultHRGNhRgn=CreateRectRgn(0,0,0,0);GetWindowRgn(hRgn);BOOLret=PtlnRegion(hRgn,);if(ret)(if(m_State==bsDown)return;if(m_State!=bsHot)(m_State=bsHot;InvalidateRect(NULL.TRUE);SetCapture();))else(m_State=bsNormal;lnvalidateRect(NULL,TRUE);ReleaseCapture();DeleteObject(hRgn);CButton::OnMouseMove(nFlags,point);}BOOLCBaseButton::PreTranslateMessage(MSG*pMsg)(//TODO:Addyourspecializedcodehereand/orcallthebaseclassif(pMsg->hwnd==this->GetSafeHwnd()&&pMsg->message==WM_KEYDOWN&&pMsg->wParam==13)(pMsg->IParam=589857;pMsg->message=WM_LBUTTONDOWN;}if(pMsg->hwnd==this->GetSafeHwnd()&&pMsg->message==WM_KEYUP&&pMsg->wParam==13)(pMsg->IParam=589857;pMsg->message=WM_LBUTTONUP;)returnCButton::PreTranslateMessage(pMsg);)1、設(shè)置列表風(fēng)格《書》P201I創(chuàng)建類CBaseHeader和CBaseList!在類CBaseHeader中處理WM_PAINT消息,實(shí)現(xiàn)OnPaint()函數(shù)I改寫CBaseList中的PreSubclassWindow虛方法|具體實(shí)現(xiàn):在類CBaseHeader中:BOOLCBaseHeader::OnEraseBkgnd(CDC*pDC)(retumCHeaderCtrl::0nEraseBkgnd(pDC);}voidCBaseHeader::OnPaint()(CPaintDCdc(this);intltemCount=GetltemCount();CRectcRC;GetClientRect(&cRC);CBrushbrush;CBitmapbmp;CPenpen(PS_SOLID,2,RGB(128,128,128));for(inti=0;i<ltemCount;i++)CRectrc;GetltemRect(i,rc);〃繪制分隔條〃繪制文本chartext[100];memset(text,0,100);CListCtrrpList=(CListCtrr)this->GetParent();if(pList!=NULL)(LVCOLUMNcol;memset(&col,0,sizeof(LVCOLUMN));=LVCF_TEXT;=100;=text;pList->GetColumn(i,&col);CFont*font=GetFont();|DT_VCENTER|DT_WORD_ELLIPSIS|DT_SINGLELINE);)在類CBaseList中:intCBaseList::OnCreate(LPCREATESTRUCTIpCreateStruct)(if(CListCtrl::OnCreate(lpCreateStruct)==-1)return-1;//TODO:AddyourspecializedcreationcodeherereturnO;}voidCBaseList::PreSubclassWindow()(//TODO:Addyourspecializedcodehereand/orcallthebaseclassCListCtrl::PreSubclassWindow();C++編程常用模塊(十三):List的用法十三、List的用法1、初始化voidCMSetDlg::lnitKXList()EUD£");ETT%");0DT%");EUI%");return;}2,綁定數(shù)據(jù)voidCMSetDlg::LoadYXList()(CStringstrsql;NamefromMName");return;)voidCDataBind::BindListBox(CListBox*m_listbox,CStringstrsql,CStringZDName)m_listbox->SetRedraw(FALSE);m_listbox->ResetContent();//E%3yEuODnAEy%YADOConnac;mJistbox->AddString((TCHAR)m_listbox->SetRedraw(TRUE);mjistbox->lnvalidate();return;)3、將數(shù)據(jù)添加到數(shù)據(jù)庫voidCMSetDlg::AddListToDB(){DeleteDBData();CStringstrTemp;for(intAddSNameToDB(strTemp);return;voidCMSetDlg::DeleteDBData(){CStringstrsql;*fromMNameM);return;}voidCMSetDlg::AddSNameToDB(CStringstrM)CStringstrsql;intoMName(MName)values('%s,)',,strM);}return;4、數(shù)據(jù)左右兩個(gè)List中相互移動(dòng)〃從左到右voidCSSetDIg::OnbtnAddToRight(){//TODO:Addyourcontrolnotificationhandlercodehereintindex=if(index!=-1)(CStringstrTemp;return;)〃從右到左voidCSSetDIg::OnbtnDeleteToLeft(){//TODO:Addyourcontrolnotificationhandlercodehereintindex=if(index!=-1)CStringstrTemp;)return;}C++編程常用模塊(十四):Tab卡的用法十四、Tab卡的用法1、初始化CTabCtrlm_SystemSetTab;CDeptNameSetpDeptNameSet;CCIassSetDIgpCIassSet;CSSetDIgpSSet;CMSetDIgpMSet;BOOLCSystemSetDlg::OnlnitDialog()(CDialog::OnlnitDialog();//TODO:Addextrainitializationherestr2M);str3H);str4M);CRectrect;returnTRUE;)2、選擇改變voidCSystemSetDlg::OnSelchangeSystemSetTAB(NMHDR*pNMHDR,LRESULT*pResult)(//TODO:AddyourcontrolnotificationhandlercodehereCRectrect;intswitch(i)caseO:break;}easel:break;}case2:break;}case3:break;}}*pResult=O;}3、確定、取消、應(yīng)用voidCSystemSetDlg::OnbtnCancel()(//TODO:AddyourcontrolnotificationhandlercodehereCDialog:OnCancel();}voidCSystemSetDlg::OnbtnOk()(//TODO:AddyourcontrolnotificationhandlercodehereOnbtnCancel();EndDialog(O);voidCSystemSetDlg::OnbtnApply()//TODO:Addyourcontrolnotificationhandlercodeherereturn;}C++編程常用模塊(十五):其它十五、其它1、消息對(duì)話框MessageBox("請(qǐng)從列表中選擇要?jiǎng)h除的記錄!ッ;if(MessageBox("確定刪除?","提示",MB_YESNO|MB_ICONWARNING)==IDYES)AfxMessageBox("已注銷!");2、打

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論