C++编程常用模块.docx

上传人:b****3 文档编号:5293260 上传时间:2022-12-15 格式:DOCX 页数:57 大小:34.78KB
下载 相关 举报
C++编程常用模块.docx_第1页
第1页 / 共57页
C++编程常用模块.docx_第2页
第2页 / 共57页
C++编程常用模块.docx_第3页
第3页 / 共57页
C++编程常用模块.docx_第4页
第4页 / 共57页
C++编程常用模块.docx_第5页
第5页 / 共57页
点击查看更多>>
下载资源
资源描述

C++编程常用模块.docx

《C++编程常用模块.docx》由会员分享,可在线阅读,更多相关《C++编程常用模块.docx(57页珍藏版)》请在冰豆网上搜索。

C++编程常用模块.docx

C++编程常用模块

1

(一):

连接SQL数据库

一、连接数据库(SQL):

(一)直接写在程序中

1、导入动态连接库

在StdAfx.h中:

#import"C:

\ProgramFiles\CommonFiles\System\ado\msado15.dll"no_namespace\

rename("EOF","adoEOF")rename("BOF","adoBOF")

2、定义Provider宏

在StdAfx.h中:

#defineProvider"Provider=SQLOLEDB.1;IntegratedSecurity=SSPI;\

PersistSecurityInfo=False;InitialCatalog=HRMS"

3、初始化

a).h文件中

private:

HDCm_hDC;

DWORDm_CurrentRecord;

_RecordsetPtrm_pRecordset;

_ConnectionPtrm_pConnection;

b).cpp文件中

CADOOperation:

:

CADOOperation()

{

try{

m_pConnection.CreateInstance(_uuidof(Connection));

m_pConnection->Open(_bstr_t(Provider),"","",adModeUnknown);

}

catch(_com_errore)

{

AfxMessageBox(e.Description(),MB_OK);

exit(0);

}

m_pRecordset.CreateInstance(_uuidof(Recordset));

m_CurrentRecord=-1;

}

4、执行

5、关闭

CADOOperation:

:

~CADOOperation()

{

m_pConnection->Close();

}

(二)通过login.ini文件连接

voidCBbbApp:

:

IniAdo()

{

try

{

CStringtemp;

charfilepath[MAX_PATH];

GetModuleFileName(NULL,filepath,MAX_PATH);

temp=theApp.ExtractFilePath(filepath);//获取可执行文件的路径,也就是程序运行的.exe文件所在路径

//运行后,temp的值为程序文件.exe所在路径

CStringstrAdoConn;

chartemp1[100];

/*********************************************

在同目录下创建login.ini文件,并在其中设置数据库连接字符串,如:

[DatabaseConfig]

Server=.//.表示本机

Database=BookManage

User=sa

PWD=sa

*********************************************/

GetPrivateProfileString("DatabaseConfig","Server","",temp1,100,temp+"login.ini");

strserver=(TCHAR*)temp1;

GetPrivateProfileString("DatabaseConfig","Database","",temp1,100,temp+"login.ini");

strdbName=temp1;

GetPrivateProfileString("DatabaseConfig","User","",temp1,100,temp+"login.ini");

strUser=temp1;

GetPrivateProfileString("DatabaseConfig","PWD","",temp1,100,temp+"login.ini");

strPassword=temp1;

strAdoConn.Format("driver={SQLServer};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s",

strserver,strUser,strPassword,strdbName);

m_pCon.CreateInstance(_uuidof(Connection));

m_pCon->ConnectionString=(_bstr_t)strAdoConn;

m_pCon->Open("","","",NULL);

m_pCom.CreateInstance("ADODB.Command");

m_pRs.CreateInstance(_uuidof(Recordset));

m_pRs1.CreateInstance(_uuidof(Recordset));

//ADOFLAG=TRUE;

}

catch(_com_error)

{

//ADOFLAG=FALSE;

Flag=FALSE;

MessageBox(0,"请检查系统配置信息","数据库连接失败",MB_OK);

return;

}

catch(...)

{

AfxMessageBox("SYSError");

return;

}

}

C++编程常用模块

(二):

连接Access数据库

二、连接数据库(Access2000)

1、在.h文件中导入动态链接库

#import"C:

\ProgramFiles\CommonFiles\System\ado\msado15.dll"no_namespace\

rename("EOF","adoEOF")rename("BOF","adoBOF")

类定义:

classADOConn

{

public:

BOOLExecuteSQL(_bstr_tbstrSQL);

ADOConn();

virtual~ADOConn();

//添加一个指向Connection对象的指针

_ConnectionPtrm_pConnection;

//添加一个指向Recordset对象的指针

_RecordsetPtrm_pRecordset;

_RecordsetPtr&GetRecordSet(_bstr_tbstrSQL);

voidExitConnect();

voidOnInitADOConn();

};

2、建立连接

voidADOConn:

:

OnInitADOConn()

{

//初始化OLE/COM库环境

:

:

CoInitialize(NULL);

try

{

charfilepath[MAX_PATH];

GetModuleFileName(NULL,filepath,MAX_PATH);

CStringstrdb;

strdb=ExtractFilePath(filepath)+"sm.mdb";

strdb="DBQ="+strdb;

//创建connection对象

m_pConnection.CreateInstance("ADODB.Connection");

m_pConnection->ConnectionTimeout=3;

//设置连接字符串,两种都可以

_bstr_tstrConnect="DRIVER={MicrosoftAccessDriver(*.mdb)};uid=;pwd=sm;";

strConnect=strConnect+strdb;

//SERVER和UID,PWD的设置根据实际情况来设置

m_pConnection->Open(strConnect,"","",adModeUnknown);

}

//捕捉异常

catch(_com_errore)

{

//显示错误信息

AfxMessageBox(e.Description());

}

}

3、执行SQL语句

//仅执行,无返回

BOOLADOConn:

:

ExecuteSQL(_bstr_tbstrSQL)

{

try

{

//是否已连接数据库

if(m_pConnection==NULL)

OnInitADOConn();

m_pConnection->Execute(bstrSQL,NULL,adCmdText);

returntrue;

}

catch(_com_errore)

{

e.Description();

returnfalse;

}

}

//返回记录集

_RecordsetPtr&ADOConn:

:

GetRecordSet(_bstr_tbstrSQL)

{

try

{

if(m_pConnection==NULL)

OnInitADOConn();

m_pRecordset.CreateInstance(__uuidof(Recordset));

m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);

}

catch(_com_errore)

{

e.Description();

}

returnm_pRecordset;

}

4、关闭连接

voidADOConn:

:

ExitConnect()

{

//关闭记录集和连接

if(m_pRecordset!

=NULL)

{

m_pRecordset->Close();

m_pRecordset=NULL;

}

if(m_pConnection!

=NULL)

{

m_pConnection->Close();

m_pConnection=NULL;

}

//释放环境

:

:

CoUninitialize();

}

C++编程常用模块(三):

窗体操作

三、窗体操作

1、显示对话框窗体

CDlgLoginlogin;

login.DoModal();

若要处理“确定”或“取消”:

intnResponse=login.DoModal();

if(nResponse==IDOK)

{

//TODO:

Placecodeheretohandlewhenthedialogis

//dismissedwithOK

}

elseif(nResponse==IDCANCEL)

{

//TODO:

Placecodeheretohandlewhenthedialogis

//dismissedwithCancel

}

2、关闭对话框窗体

EndDialog(0);

CDialog:

:

OnCancel();

CDialog:

:

OnOK();

3、退出应用程序

exit(0);

4、登录:

P308

voidCDlgLogin:

:

OnButton1()

{

CStringc_user,c_password;

m_user.GetWindowText(c_user);

m_password.GetWindowText(c_password);

if(c_user.IsEmpty()||c_password.IsEmpty())

{

MessageBox("用户名称或密码不能为空","用户登录信息");

return;

}

CStringsql;

sql.Format("select*fromtb_operatorwherename='%s'andpassword='%s'",c_user,c_password);

m_pRs->raw_Close();

m_pRs->Open((_variant_t)sql,m_pCon.GetInterfacePtr(),adOpenKeyset,adLockOptimistic,adCmdText);

//if(m_pRs->RecordCount>0)或者

if(!

myConn.m_pRecordset->adoEOF)

{

Flag=true;//Flag为全局变量

user=m_pRs->GetCollect("name").bstrVal;

password=m_pRs->GetCollect("password").bstrVal;

EndDialog(0);

}

else

{

user="";

password="";

MessageBox("用户名或密码不正确.","提示",64);

return;

}

}

在程序启动初始化部分BOOLCBbbApp:

:

InitInstance()函数里完成窗口跳转:

if(Flag==true)

{

CBbbDlgdlg;//启动主窗体

m_pMainWnd=&dlg;

dlg.DoModal();

}

5、动态创建工具栏:

P306

方法

(一):

CToolBarm_toolbar;

CImageListm_imagelist;

m_imagelist.Create(24,24,ILC_COLOR24|ILC_MASK,1,1);

m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON4));

m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON11));

m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON13));

m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON5));

m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON19));

UINTarray[5];

for(inti=0;i<5;i++)

{

array[i]=5000+i;//创建索引

}

m_toolbar.Create(this);

m_toolbar.SetButtons(array,5);

m_toolbar.SetButtonText(0,"图书信息");

m_toolbar.SetButtonText(1,"图书入库");

m_toolbar.SetButtonText(2,"销售查询");

m_toolbar.SetButtonText(3,"系统配置");

m_toolbar.SetButtonText(4,"系统退出");

m_toolbar.GetToolBarCtrl().SetButtonWidth(60,120);

m_toolbar.GetToolBarCtrl().SetImageList(&m_imagelist);

m_toolbar.SetSizes(CSize(70,60),CSize(28,40));

RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,0);

/**************************原理************************

先创建索引,再在resource.h中定义控件代表的索引,如

#defineIDB_bookinfo5000

#defineIDB_booksell5001

#defineIDB_sellinfo5002

#defineIDB_set5003

#defineIDB_cancel5004

最后在对话框的.cpp文件中将控件与响应函数关联起来

BEGIN_MESSAGE_MAP(CBbbApp,CWinApp)

ON_COMMAND(IDB_bookinfo,OnBookInfo)

ON_COMMAND(IDB_booksell,OnBookInput)

ON_COMMAND(IDB_sellinfo,OnSaleQuery)

ON_COMMAND(IDB_set,OnButton4)

ON_COMMAND(IDB_cancel,OnCancel)

END_MESSAGE_MAP()

******************************************************/

方法

(二):

CImageListm_ImageList;

CToolBarCtrlm_ToolBar;

TBBUTTONtbButton[ICONSUM]={0};

m_ImageList.Create(32,32,ILC_COLOR32|ILC_MASK,0,0);

m_ImageList.Add(:

:

AfxGetApp()->LoadIcon(IDI_ICON4));

m_ImageList.Add(:

:

AfxGetApp()->LoadIcon(IDI_ICON6));

m_ImageList.Add(:

:

AfxGetApp()->LoadIcon(IDI_ICON5));

m_ImageList.Add(:

:

AfxGetApp()->LoadIcon(IDI_ICON2));

m_ImageList.Add(:

:

AfxGetApp()->LoadIcon(IDI_ICON3));

m_ToolBar.Create(WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,0);

m_ToolBar.SetImageList(&m_ImageList);

for(intj=0;j

{

tbButton[j].dwData=NULL;

tbButton[j].fsState=TBSTATE_ENABLED;

tbButton[j].fsStyle=(BYTE)TBSTYLE_FLAT;

tbButton[j].iBitmap=j;

}

tbButton[0].idCommand=ID_Info;

tbButton[1].idCommand=ID_MR;

tbButton[2].idCommand=ID_QS;

tbButton[3].idCommand=ID_XS;

tbButton[4].idCommand=ID_HELP;

m_ToolBar.AddButtons(ICONSUM,tbButton);

m_ToolBar.AutoSize();

m_ToolBar.SetStyle(TBSTYLE_FLAT|CCS_TOP);

6、设置菜单有效和失效

有效:

m_Menu.EnableMenuItem(ID_USER_REGISTER,MF_BYCOMMAND|MF_ENABLED);

失效:

m_Menu.EnableMenuItem(ID_USER_REGISTER,MF_BYCOMMAND|MF_DISABLED|MF_GRAYED);

7、设置状态栏

CTimeTime;

Time=CTime:

:

GetCurrentTime();

CStringStr=Time.Format("%Y-%m-%d");

UINTArray[3];

for(inti=0;i<3;i++)

{

Array[i]=10000+i;

}

m_Statusbar.Create(this);

m_Statusbar.SetIndicators(Array,3);

m_Statusbar.SetPaneInfo(0,Array[0],0,150);

m_Statusbar.SetPaneInfo(1,Array[1],0,450);

m_Statusbar.SetPaneInfo(2,Array[2],0,150);

m_Statusbar.SetPaneText(0,"用户:

"+theApp.userID);

m_Statusbar.SetPaneText(1,"CopyRightV1.0");

m_Statusbar.SetPaneText(2,"当前时间:

"+Str,true);

RepositionBars(AFX_IDW_CONTROLBAR_FIRST,AFX_IDW_CONTROLBAR_LAST,0);

8、设置菜单栏

m_Menu.LoadMenu(IDR_MainMENU);

SetMenu(&m_Menu);

9、获得窗口WindowDCP464

CWindowDC*dc=(CWindowDC*)GetWindowDC();

10、文档框架关闭时,恢复程序主窗口

voidCPrintFram:

:

OnClose()

{

theApp.m_mainfram=NULL;

CPrintView*temp=(CPrintView*)this->GetActiveView();

if(!

temp->ispreview)

theApp.m_pMainWnd=theApp.m_main;

CFrameWnd:

:

OnClose();

}

11、窗体标题栏加上图标

先在头文件中声明:

HICONm_hIcon;

在构造函数中:

m_hIcon=AfxGetApp()->LoadIcon(IDI_ICON1);

在OnInitDialog()中:

SetIcon(m_hIcon,TRUE);//Setbigicon

SetIcon(m_hIcon,FALSE);//Setsmallicon

在OnPaint()中:

voidCSmDlg:

:

OnPaint()

{

if(IsIconic())

{

CPaintDCdc(this);//devicecontextforpainting

SendMessage(WM_ICONERASEBKGND,(WPARAM)dc.GetSafeHdc(),0);

//Centericoninclientrectangle

intcxIcon=GetSystemMetrics(SM_CXICON);

intcyIcon=GetSystemMetrics(SM_CYICON);

CRectrect;

GetClientRect(&rect)

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1