VC常用操作源码汇总(推荐)
VC++图形图像处理源代码
delete pData; pData=NULL;
if(m_pBMI!=NULL) delete m_pBMI; m_pBMI=NULL; if(pfi!=NULL)
delete pfi; pfi=NULL; } CAvi::CAviCreate(CString &string)//读文件初始化该类 { HRESULT hr; pfi=new AVIFILEINFO; hr = AVIFileOpen(&pfile, // returned file pointer string, // file name OF_READ, // mode to open file with NULL); hr= AVIFileInfo(pfile, file://获取 AVI 信息,放入 pfi 中 pfi, sizeof(AVIFILEINFO) ); cx=pfi>dwWidth;//图象宽、高 cy=pfi>dwHeight; hr=AVIFileGetStream(//将 AVI 变成视频流 pfile, &pavi, streamtypeVIDEO, 0//LONG lParam ); m_pBMI=new BITMAPINFO;//定义 BMP 信息头 m_pBMI>bmiHeader.biBitCount=24; m_pBMI>bmiHeader.biClrImportant=0; m_pBMI>bmiHeader.biClrUsed=0; m_pBMI>bmiHeader.biCompression=BI_RGB; m_pBMI>bmiHeader.biHeight=cy; m_pBMI>bmiHeader.biWidth=cx; m_pBMI>bmiHeader.biPlanes=1; m_pBMI>bmiHeader.biSize=sizeof(BITMAPINFOHEADER); m_pBMI>bmiHeader.biXPelsPerMeter=0; m_pBMI>bmiHeader.biYPelsPerMeter=0; m_pBMI>bmiHeader.biSizeImage=cx*cy*3; pData=(BYTE*)new char[cx*cy*3];//根据 AVI 中 BMP 图象的信息定义缓冲区 } BOOL CAvi::AviRead(int mFrame)//将 AVI 文件的 M 帧数据读入 PData 缓冲区 { HRESULT hr; hr= AVIStreamRead( pavi, mFrame, 1, pData, cx*cy*3,
VC常用源码
VC常用源码//注意事项===============================================>//先执行OnInitDialog()函数,然后执行构造函数!//98下没有新宋体//XP下窗口高度加8//滚动条处理方法***************************************************************** *****//1,设置范围m_spscroll.SetScrollRange(0,200);SCROLLINFO si;si.cbSize=sizeof(SCROLLINFO);si.nPage=100;si.fMask=SIF_PAGE;//设置页宽m_spscroll.SetScrollInfo(&si);//2,处理消息,垂直滚动条加WM_VSCROLL消息,水平加WM_HSCROLL消息void CPrintView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) {// TODO: Add your message handler code here and/or call defaultif(pScrollBar->GetDlgCtrlID()==IDC_SCROLLBAR1){int nCurrentPos=pScrollBar->GetScrollPos();SCROLLINFO si;si.fMask=SIF_PAGE;//取得页宽pScrollBar->GetScrollInfo(&si);switch(nSBCode){case SB_THUMBTRACK://移动滑块case SB_THUMBPOSITION:pScrollBar->SetScrollPos(nPos);//注意,设置页宽后滚动条的pos会以max/nPage倍数减少,所以在使用时注意把pos值*(max/nPage)才能得到原值break;case SB_LINEUP://点向上小三角pScrollBar->SetScrollPos(nCurrentPos-1);break;case SB_LINEDOWN://点向下小三角pScrollBar->SetScrollPos(nCurrentPos+1);break;case SB_PAGEUP://向上一页pScrollBar->SetScrollPos(nCurrentPos-si.nPage);break;case SB_PAGEDOWN://向下一页pScrollBar->SetScrollPos(nCurrentPos+si.nPage);break;}}CDialog::OnVScroll(nSBCode, nPos, pScrollBar);}//锁定鼠标***************************************************************** ***********bool pOld;CRect rt;SetForegroundWindow();SystemParametersInfo(SPI_SETSCREENSAVERRUNNING,true,&pOld,SPIF_UPDAT EINIFILE);GetWindowRect(rt);ClipCursor(rt);//加到LRESULT CLockDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 会有意外的效果//在列表字符前插入一个负数字符以修改乱码******************************************************int index=m_list.GetSelectionMark();//在列表字符前插入一个负数字符以修改乱码CString cs;cs=m_list.GetItemText(index,0);char insert_char=-87;cs.Insert(0,insert_char);m_list.SetItemText(index,0,cs);//在列表中添加项目最大只能显示259个字符(不含'\0')*************************************************int char_length=cs.GetLength();//cs,ct为CString类对象,是要发到列表框的文本但是可能大于259字节while(char_length>259)//如果大于259字节{ct=cs.Left(259);m_list.InsertItem(0,ct);//在列表中添加项目最大只能显示259个字符(不含'\0')cs=cs.Right(char_length-259);char_length=cs.GetLength();}m_list.InsertItem(0,cs);//在列表中添加项目最大只能显示259个字符(不含'\0')//<================================================== ========//设置NT窗口的透明度*******************************************OSVERSIONINFO osv;osv.dwOSVersionInfoSize=sizeof OSVERSIONINFO;GetVersionEx(&osv);//取得版本信息if(osv.dwPlatformId==VER_PLATFORM_WIN32_NT)//VER_PLATFORM_WIN32_WI NDOWS 98 Me用这个宏{//加入WS_EX_LAYERED扩展属性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;//取得SetLayeredWindowAttributes函数指针fun=(MYFUNC)GetProcAddress(hInst, "SetLayeredWindowAttributes");if(fun)fun(this->GetSafeHwnd(),0,200,//0 ~ 2552);FreeLibrary(hInst);}}//字体对话框的初始化*********************************************LOGFONT lf;lf.lfHeight=-35;lf.lfCharSet=134;lf.lfWeight=400;lf.lfOutPrecision=3;lf.lfClipPrecision=2;lf.lfQuality=1;lf.lfPitchAndFamily=2;strcpy(lf.lfFaceName,"宋体");//以上初始化为宋体26号字CFontDialog cf(&lf);//字体cf.m_cf.rgbColors=textcolor;//颜色//移动没有标题的窗口**********************************************//1定义:CPoint just_point;//2void CClockfortecherDlg::OnLButtonDown(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call defaultjust_point=point;CDialog::OnLButtonDown(nFlags, point);}//3void CClockfortecherDlg::OnMouseMove(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call default WINDOWPLACEMENT wi;GetWindowPlacement(&wi);if(nFlags==MK_LBUTTON)SetWindowPos(&wndTop,wi.rcNormalPosition.left+(point.x-just_point.x),wi.rcNormalPosition.top+(point.y-just_point.y),0,0,SWP_NOSIZE);CDialog::OnMouseMove(nFlags, point);}//线程与信号量***************************************************//1,定义信号量句柄HANDLE event;//2,创建信号量event=CreateEvent(NULL, TRUE, FALSE, NULL);//3,创建线程,//1)定义线程函数,格式必须如下,其中lParam为AfxBeginThread的第二个参数值,可强制转化成所需类型UINT WorkThreadProc(LPVOID lParam)//必须是UINT XXX..XXX(LPVOID lParam) {//代码示例WaitForSingleObject:while(1){//-----------------------注意,如果线程间要求同步或互斥的时候,要在每一层循环体中加入WaitForSingleObjectWaitForSingleObject((HANDLE)lParam, INFINITE);//WaitForSingleObject的使用方法:第一个为信号量HANDLE,是CreateEvent的返回值,第二个参数为等待的毫秒数(1/1000秒)//第二个参数为INFINITE时则一直等待,直到调用SetEvent()设置信号量时函数返回;为数值(如1000)则函数在1秒后返回//(即使你没调用SetEvent()设置信号量)AfxMessageBox("fcuk");//不能用MessageBox()因为这不是在类中了...ResetEvent((HANDLE)lParam);/*重置信号量,以使WaitForSingleObject函数可以继续等待,否则(如果你已经调用过了SetEvent()设置了信号量)WaitForSingleObject函数将会立刻返回*/}}//2)用AfxBeginThread创建一个WorkThreadProc的线程AfxBeginThread(WorkThreadProc,event);//4,在主程序需要的地方调用SetEvent()设置信号量启动线程SetEvent(event);//-----------或者用WaitForMultipleObjects函数static UINT __stdcall WorkThreadProc(void* pThis);/*如果lParam参数为一个对话框的指针,想调用这个对话框的变量或函数那么就得这样定义线程函数,还要将WorkThreadProc改成CWait_forDlg::WorkThreadProc,这样WorkThreadProc就成为CWait_forDlg类的函数,在这个线程里就可以调用该类的变量了,注意得用_beginthreadex函数创建线程*/UINT CWait_forDlg::WorkThreadProc(void * lParam){CWait_forDlg *pThis=(CWait_forDlg *)lParam;HANDLE hObjects[2];hObjects[0] = pThis->event1;hObjects[1]= pThis->event2;while(1){DWORD dwWait = WaitForMultipleObjects(2,hObjects,TRUE,INFINITE);/*第一个参数为信号量个数2,第二个为指针,第三个如果为TRUE函数要等待两个信号量都被SetEvent才返回,返回值为最后一个SetEvent的WAIT_OBJECT_0+i;而为FALSE则只要有一个被SetEvent就返回,返回值为WAIT_OBJECT_0+i 即信号量在数组中的位置+WAIT_OBJECT_0 */if (dwWait == WAIT_OBJECT_0)AfxMessageBox("fcuk 1 ");//开始pingif (dwWait == WAIT_OBJECT_0 + 1)AfxMessageBox("fcuk 2");ResetEvent(hObjects[1]);ResetEvent(hObjects[0]);}}#include <process.h> /* 调用_beginthread, _endthread 得包涵这个头文件*/_beginthreadex(NULL,0,WorkThreadProc,(void*) this,0,0);//第三种创建线程的方法:HANDLE thread;DWORD threadrid; //线程IDDWORD WINAPI sniff(LPVOID no){} //线程函数这样定义thread=CreateThread(NULL, //安全属性0, //栈大小sniff, //要创建的线程名NULL, //参数(一般为调用线程的指针)0, //创建标志&threadrid); //线程IDCloseHandle(thread);//操作数据库**************************************************//在stdafx.h中加入#include <afxdb.h>//1,用类向导,建立基于CRecordset或CDaoRecordset的新子类,并选择数据源m_setComplete//2,添加if ( ! m_setComplete . IsOpen () ) // if the recordset isn't already open..m_setComplete . Open (); // open itm_setComplete . AddNew (); // begin the addm_setComplete . m_strCallsign = strCallsign; // change the recordset members m_setComplete . m_strFrequency = strFrequency;m_setComplete . m_strCity = strCity;m_setComplete . m_strState = strState;m_setComplete . m_strInput = strInput;m_setComplete . Update (); // complete the add by doing an updatem_setComplete . Close (); // close the recordset//3,修改if ( ! m_setComplete . IsOpen () ) // if the recordset isn't already open..m_setComplete . Open (); // open itm_setComplete . Edit (); // begin the editm_setComplete . m_strCallsign = strCallsign; // change the recordset membersm_setComplete . m_strFrequency = strFrequency;m_setComplete . m_strCity = strCity;m_setComplete . m_strState = strState;m_setComplete . m_strInput = strInput;m_setComplete . Update (); // complete the add by doing an updatem_setComplete . Close (); // close the recordset//4,删除/* 1, DAO 数据库,不是ODBCif ( ! m_setComplete . IsOpen () )m_setComplete . Open ();// cycle through the selected listbox elements.strRecordIdQuery =CString ( "[ID]=" ) +CString ( m_lcRepeaterList . GetItemText ( nItemIndex, 0 ) ); // put the ID into the query stringMessageBox(strRecordIdQuery);if ( m_setComplete . FindFirst ( strRecordIdQuery ) ) { // looking for this ID in the database, ID is a unique 'autonumber'm_setComplete . Delete (); // delete the recordm_setComplete . MoveFirst (); // move back to the first recordm_bRecordsWereDeleted = TRUE; // make a note that we changed the database SetDlgItemText ( IDC_DELETE_STATUS, "Repeater Deleted From Database" ); // set the status field}else {// if we EVER end up here, either the database is in the crapper, or I will have screwed up horribly--been known to happen from time to time :) ...// so let's cover our ass-ets just in case.AfxMessageBox ( "Internal failure\n\nCannot find selected repeater in database\nor database is corrupted", MB_ICONSTOP );}m_setComplete . Close (); // close the database*/// ODBC herem_setComplete.m_strFilter="number=200301";//条件查询(where语句)if ( ! m_setComplete . IsOpen () )m_setComplete . Open ();m_setComplete.Delete();m_setComplete . MoveFirst ();m_setComplete . Close (); // close the databasem_setComplete.m_strFilter="";//清空条件(where语句)//查询(where语句)m_setComplete.m_strFilter="number=200301";if ( ! m_setComplete . IsOpen () )m_setComplete . Open ();m_setComplete . Close (); // close the database//不用类向导写连接数据库的程序段,但是我只看明白了连接和查询,不会修改和添加,删除//1,CDatabase m_dbCust; //定义数据库类对象m_dbCust.OpenEx(_T("DSN=MQIS;UID=sa;PWD=1980623")//打开数据库//数据源名,用户名,密码,CDatabase::forceOdbcDialog );//此参数只定是否打开连接确认对话框//MessageBox(m_dbCust.GetDatabaseName());取得数据源名//m_dbCust.ExecuteSQL("select number from works");测试是否支持SQL语句CRecordset cs(&m_dbCust);//定义目录查询对象cs.Open( CRecordset::dynaset,_T( "select * from works" ) );//打开时执行的SQL语句short nFields = cs.GetODBCFieldCount( );//取得字段数,(列数)CDBVariant varValue;//定义通用数据类型CODBCFieldInfo co;//定义字段信息CString cc;while( !cs.IsEOF( ) ){for( short index = 0; index < nFields; index++ ){// do something with varValuecs.GetFieldValue(index,varValue);//取得某列的数据,//cs.GetFieldValue(index,cc); 也可直接取得由某列的数据直接转化成的文本if(varValue.m_dwType==DBVT_LONG)//m_dwType成员用来判断数据类型/* m_dwType Union data memberDBVT_NULL No union member is valid for access.DBVT_BOOL m_boolValDBVT_UCHAR m_chValDBVT_SHORT m_iValDBVT_LONG m_lValDBVT_SINGLE m_fltValDBVT_DOUBLE m_dblValDBVT_DATE m_pdateDBVT_STRING m_pstringDBVT_BINARY m_pbinary*/{cc.Format("%d",varValue.m_lVal);//m_dwType==DBVT_LONG时为LONG型数据,成员为m_lVal,数值在其中MessageBox(cc);}cs.GetODBCFieldInfo(index,co);//取得字段信息/* struct CODBCFieldInfo{CString m_strName;字段名SWORD m_nSQLType;SQL数据类型UDWORD m_nPrecision;SWORD m_nScale;SWORD m_nNullability;};*/}cs.MoveNext( );//下一个}cs.Close();//显示程序段*********************************************CString cstr;cstr.Format("%d", );MessageBox(cstr);if(MessageBox("关闭Windows秘书您可会失去重要的提醒信息,确定要关闭吗?", "Windows秘书",MB_OKCANCEL|MB_DEFBUTTON2|MB_ICONWARNING)==IDOK) MessageBeep(MB_ICONQUESTION);//注册与卸载OCX控件****************************************//1,函数入口宏定义typedef HRESULT (STDAPICALLTYPE *CTLREGPROC)();//2,注册函数BOOL RegisterOcx(CString ocxfilename){BOOL bResult = FALSE ;HMODULE hModule = ::LoadLibrary(ocxfilename) ;//获得注册函数地址CTLREGPROC DLLRegisterServer =(CTLREGPROC)::GetProcAddress(hModule,"DllRegisterServer" ) ;if (DLLRegisterServer != NULL){HRESULT regResult = DLLRegisterServer() ;bResult = (regResult == NOERROR) ;}::FreeLibrary(hModule) ;return bResult ;}//2,卸载函数BOOL UnRegisterOcx(CString ocxfilename){BOOL bResult = FALSE ;HMODULE hModule = ::LoadLibrary(ocxfilename) ;//获得卸载函数地址CTLREGPROC DLLUnregisterServer =(CTLREGPROC)::GetProcAddress( hModule,"DllUnregisterServer" ) ;if (DLLUnregisterServer != NULL){HRESULT regResult = DLLUnregisterServer() ;bResult = (regResult == NOERROR) ;}::FreeLibrary(hModule) ;return bResult ;}//处理文件拖动***************************************************************** **********************//1 添加WM_DROPFILES 静态消息//2 在OnInitDialog()函数中加入DragAcceptFiles(TRUE);//允许拖放//3 WM_DROPFILES 的处理函数为void CCXatDemoDlg::OnDropFiles(HDROP hDropInfo){unsigned int nFiles=DragQueryFile(hDropInfo,0xFFFFFFFF,NULL,0);//取得拖放的文件总数for (unsigned int i=0;i<nFiles;i++)//循环取得文件名{unsigned int nLen=DragQueryFile(hDropInfo,i,NULL,0)+1;//取得文件名长度char *psBuffer=new char[nLen];unsigned int sLen=DragQueryFile(hDropInfo,i,psBuffer,nLen);//取得文件名到psBuffer中,sLen为实际拷贝的字符数//To add code here...delete [] psBuffer;}DragFinish(hDropInfo);//结束}//设置窗口大小和位置******************************************************SetWindowPos(&wndTopMost,0,0,0,0,SWP_NOSIZE|SWP_NOMOVE);//设为最高层/*wndBottomwndTopwndTopMostwndNoTopMost*///在窗体中这样做HWND_NOTOPMOST 为不是最高层::SetWindowPos(AfxGetMainWnd()->m_hWnd,HWND_TOPMOST,-1,-1,-1,-1,SWP _NOMOVE|SWP_NOSIZE);/*HWND_BOTTOMHWND_NOTOPMOSTHWND_TOPHWND_TOPMOSTSWP_DRAWFRAME Draws a frame, defined in the class description of the window, around the window.SWP_FRAMECHANGED Sends a WM_NCCALCSIZE message to the window, even if the size of the window is not being changed. If this flag is not specified,WM_NCCALCSIZE is sent only when the size of the window is being changed. SWP_HIDEWINDOW Hides the window.SWP_NOACTIVATE Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or nontopmost group, depending on the setting of the hWndInsertAfter parameter.SWP_NOMOVE Retains the current position and ignores the X and Y parameters. SWP_NOOWNERZORDER Does not change the position in the Z order of the owner window.SWP_NOREPOSITION Same as the SWP_NOOWNERZORDER flag.SWP_NOSIZE Retains the current size and ignores the cx and cy parameters. SWP_NOZORDER Retains the current Z order and ignores the hWndInsertAfter parameter.SWP_SHOWWINDOW Displays the window.*///在系统栏显示图标*****************************************//1定义结构NOTIFYICONDATA systemicon;//2定义新的消息#define WM_SYSTEMMESSAGE WM_USER+998//3添加消息函数映射ON_MESSAGE(WM_SYSTEMMESSAGE,OnSystemMessage)//4初始化结构systemicon.cbSize=sizeof(NOTIFYICONDATA);systemicon.hWnd=this->m_hWnd;systemicon.uID=IDI_SYSICON; //图标systemicon.uFlags=NIF_MESSAGE|NIF_ICON|NIF_TIP;systemicon.uCallbackMessage=WM_SYSTEMMESSAGE;systemicon.hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDI_SY SICON));strcpy(systemicon.szTip,"Windows秘书");Shell_NotifyIcon(NIM_ADD,&systemicon);//显示strcpy(systemicon.szTip,cs);Shell_NotifyIcon(NIM_MODIFY,&systemicon);//修改Shell_NotifyIcon(NIM_DELETE,&systemicon);//删除//处理函数void OnSystemMessage(WPARAM wParam, LPARAM lParam){if(wParam!=IDI_SYSICON)return;switch(lParam){case WM_RBUTTONUP://右键起来时弹出快捷菜单{CMenu *menu=NULL;LPPOINT mousepoint=new tagPOINT;::GetCursorPos(mousepoint);//得到鼠标位置BCMenu bmpmenu;bmpmenu.LoadMenu(IDR_SYSPOPUPMENU);menu = bmpmenu.GetSubMenu (0);//确定弹出式菜单的位置if(IsWindowVisible())bmpmenu.ModifyODMenuA("隐藏主窗口",ID_SHOWHIDE,IDB_HIDE);elsebmpmenu.ModifyODMenuA("显示主窗口",ID_SHOWHIDE,IDB_SHOW);if(findtxdata->stoplowstep==0)bmpmenu.ModifyODMenuA("停止普通级提醒",ID_STOPALLPT,IDB_STOP);elsebmpmenu.ModifyODMenuA("启用普通级提醒",ID_STOPALLPT,IDB_NOTSTOP);if(topornot)bmpmenu.ModifyODMenuA("窗体不在最上层",ID_NOTONTOP,IDB_NOTTOP);elsebmpmenu.ModifyODMenuA("窗体在最上层",ID_NOTONTOP,IDB_TOP);if(!muteornot)bmpmenu.ModifyODMenuA("静音",IDMUTE,IDB_NOSOUND);elsebmpmenu.ModifyODMenuA("取消静音",IDMUTE,IDB_SOUND); SetForegroundWindow();//必须先调用这个函数才能如果我不选择任何菜单而取消它menu->TrackPopupMenu(TPM_LEFTALIGN,mousepoint->x,mousepoint->y,this); //资源回收//menu->Detach();//menu->DestroyMenu();delete mousepoint;break;}}return;}//浮动鼠标提示*******************************************//1定义CToolTipCtrl tooltip;//2在OnCreate函数中创建tooltip.Create(this);//3在OnInitDialog函数中为控件添加提示字符tooltip.AddTool(GetDlgItem(IDC_DATEANDTIME),"显示日期/时间");tooltip.Activate(TRUE);//启动//4在PreTranslateMessage(MSG* pMsg) 函数中加上tooltip.RelayEvent(pMsg);//tab控件的使用************************************************m_tab.InsertItem(0,"提醒");//定义结构WINDOWPLACEMENT wininfo;//取得窗口信息m_tab.GetWindowPlacement(&wininfo);//注意第一个参数要为&wndTop,如果是&wndTopMost就可能会函数功能无效qita.SetWindowPos(&wndTop,wininfo.rcNormalPosition.left-10,wininfo.rcNormalPo sition.top+20,0,0,SWP_NOSIZE|SWP_HIDEWINDOW);//选择不同的标签void OnSelchangeTab(NMHDR* pNMHDR, LRESULT* pResult){// TODO: Add your control notification handler code hereint i=m_tab.GetCurSel();switch(i){case 0:break;case 1:break;}*pResult = 0;}//注册热键****************************************************//m_filehotkey为热键控件变量m_filehotkey.GetHotKey(WORD virtualkey,WORD flags);//注意要在主窗口中调用这个函数void RegHotKey(WORD virtualkey,WORD flags,int id){if(flags==1||flags==9)//从热键控件中得到的系统键与下函数的标志不同,但有一一对应的关系:{RegisterHotKey(GetSafeHwnd(),id,MOD_SHIFT,virtualkey);}//每个ID只能注册一个热键,up,down,home,end等中部键盘的键的flags为9,10,11,12,13,14,15if(flags==2||flags==10)//其余为1,2,3,4,5,6,7{RegisterHotKey(GetSafeHwnd(),id,MOD_CONTROL,virtualkey);}if(flags==4||flags==12){RegisterHotKey(GetSafeHwnd(),id,MOD_ALT,virtualkey);}if(flags==3||flags==11){RegisterHotKey(GetSafeHwnd(),id,MOD_CONTROL|MOD_SHIFT,virtualkey);}if(flags==5||flags==13){RegisterHotKey(GetSafeHwnd(),id,MOD_ALT|MOD_SHIFT,virtualkey);}if(flags==6||flags==14){RegisterHotKey(GetSafeHwnd(),id,MOD_ALT|MOD_CONTROL,virtualkey);}if(flags==7||flags==15){RegisterHotKey(GetSafeHwnd(),id,MOD_ALT|MOD_CONTROL|MOD_SHIFT,virtualk ey);}}//处理消息LRESULT CWindowsDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam){// TODO: Add your specialized code here and/or call the base classswitch(message){case WM_HOTKEY :switch(wParam){case IDC_HOTKEY:if(IsWindowVisible())ShowWindow(SW_HIDE);elseShowWindow(SW_SHOWNORMAL);SetForegroundWindow();break;case IDC_HOTKEY2:break;}return 0 ;}return CDialog::WindowProc(message, wParam, lParam);}//控制系统音量**********************************************************//在StdAfx.h中加入宏#include <mmsystem.h>//在setting->Link中加入下静态链接库!winmm.lib//播放声音文件名风格:第一个参数为文件名/找不到文件时不播放默认声音PlaySound( "", NULL, SND_FILENAME |SND_NODEFAULT);//定义结构UINT m_nNumMixers; //混合器的数量HMIXER m_hMixer; //当前混合器的句柄MIXERCAPS m_mxcaps; //当前混合器的性能参数CString m_strDstLineName, m_strVolumeControlName; //混合器控件的名称DWORD m_dwMinimum, m_dwMaximum; //最大,最小的音量值DWORD m_dwVolumeControlID; //混合器控件的音量控制IDDWORD m_dwMuteControlID; //混合器控件的静音控制IDBOOL muteornot; //是否静音DWORD nowvolume; //当前值double multiple;double difference; //最大最小差值int volumestep;//步长//加入消息映射函数ON_MESSAGE(MM_MIXM_CONTROL_CHANGE, OnMixerCtrlChange)//当系统音量改变时调用此函数LONG OnMixerCtrlChange(UINT wParam, LONG lParam){//响应控件音量改变的消息,然后获得当前音量并设置滚动条if ((HMIXER)wParam == m_hMixer && (DWORD)lParam ==m_dwVolumeControlID){amdGetMasterVolumeValue(nowvolume);multiple=nowvolume;double percent;}if ((HMIXER)wParam == m_hMixer && (DWORD)lParam == m_dwMuteControlID) {amdGetMasterMuteValue(muteornot);}return 0L;}//在Init函数中加入if (amdInitialize()){//获得音量控制控件的ID和名称amdGetMasterVolumeControl();// 获得当前音量值,并设置滚动条的初始位置amdGetMasterVolumeValue(nowvolume);amdGetMasterMuteValue(muteornot);multiple=nowvolume;difference=(long)(m_dwMaximum-m_dwMinimum);}//函数BOOL amdInitialize()//初始化{//获取当前混合设备数量m_nNumMixers = ::mixerGetNumDevs();m_hMixer = NULL;::ZeroMemory(&m_mxcaps, sizeof(MIXERCAPS));if (m_nNumMixers != 0){//打开混合设备if (::mixerOpen(&m_hMixer,0,(DWORD)this->GetSafeHwnd(),NULL,MIXER_OBJECTF_MIXER | CALLBACK_WINDOW)!= MMSYSERR_NOERROR)return FALSE;// 获取混合器性能if (::mixerGetDevCaps((UINT)m_hMixer, &m_mxcaps, sizeof(MIXERCAPS))!= MMSYSERR_NOERROR)return FALSE;}return TRUE;}BOOL amdGetMasterVolumeControl()//获得音量控制控件的ID和名称{m_strDstLineName.Empty();m_strVolumeControlName.Empty();if (m_hMixer == NULL)return FALSE;//获得混合器性能MIXERLINE mxl;mxl.cbStruct = sizeof(MIXERLINE);mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;if (::mixerGetLineInfo((HMIXEROBJ)m_hMixer,&mxl,MIXER_OBJECTF_HMIXER |MIXER_GETLINEINFOF_COMPONENTTYPE)!= MMSYSERR_NOERROR)return FALSE;MIXERCONTROL mxc;MIXERLINECONTROLS mxlc;mxlc.cbStruct = sizeof(MIXERLINECONTROLS);mxlc.dwLineID = mxl.dwLineID;mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;//此值表示取得音量ontrols = 1;mxlc.cbmxctrl = sizeof(MIXERCONTROL);mxlc.pamxctrl = &mxc;//获得混合器线控件if (::mixerGetLineControls((HMIXEROBJ)m_hMixer,&mxlc,MIXER_OBJECTF_HMIXER |MIXER_GETLINECONTROLSF_ONEBYTYPE)!= MMSYSERR_NOERROR)return FALSE;//记录控件的信息m_strDstLineName = mxl.szName;m_strVolumeControlName = mxc.szName;m_dwMinimum = mxc.Bounds.dwMinimum;m_dwMaximum = mxc.Bounds.dwMaximum;m_dwVolumeControlID = mxc.dwControlID;mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE;//此值表示取得静音与否if (::mixerGetLineControls((HMIXEROBJ)m_hMixer,&mxlc,MIXER_OBJECTF_HMIXER |MIXER_GETLINECONTROLSF_ONEBYTYPE)!= MMSYSERR_NOERROR)return FALSE;m_dwMuteControlID = mxc.dwControlID;return TRUE;}BOOL amdGetMasterVolumeValue(DWORD &dwVal)// 获得当前音量值,并设置滚动条的初始位置{if (m_hMixer == NULL ||m_strDstLineName.IsEmpty() || m_strVolumeControlName.IsEmpty())return FALSE;MIXERCONTROLDETAILS_UNSIGNED mxcdVolume; MIXERCONTROLDETAILS mxcd;mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);mxcd.dwControlID = m_dwVolumeControlID;hannels = 1;mxcd.cMultipleItems = 0;mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);mxcd.paDetails = &mxcdVolume;//获取指定混合器控件if (::mixerGetControlDetails((HMIXEROBJ)m_hMixer,&mxcd,MIXER_OBJECTF_HMIXER |MIXER_GETCONTROLDETAILSF_VALUE)!= MMSYSERR_NOERROR)return FALSE;dwVal = mxcdVolume.dwValue;return TRUE;}BOOL amdGetMasterMuteValue(BOOL &yorn)//是否静音{if (m_hMixer == NULL ||m_strDstLineName.IsEmpty() || m_strVolumeControlName.IsEmpty()) return FALSE;MIXERCONTROLDETAILS_UNSIGNED mxcdVolume; MIXERCONTROLDETAILS mxcd;mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);mxcd.dwControlID = m_dwMuteControlID;hannels = 1;mxcd.cMultipleItems = 0;mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); mxcd.paDetails = &mxcdVolume;//获取指定混合器控件if (::mixerGetControlDetails((HMIXEROBJ)m_hMixer,&mxcd,MIXER_OBJECTF_HMIXER |MIXER_GETCONTROLDETAILSF_VALUE)!= MMSYSERR_NOERROR)return FALSE;yorn = mxcdVolume.dwValue;return TRUE;}BOOL amdSetMasterMuteValue(BOOL &yorn)//设置静音与否{if (m_hMixer == NULL ||m_strDstLineName.IsEmpty() || m_strVolumeControlName.IsEmpty()) return FALSE;MIXERCONTROLDETAILS_UNSIGNED mxcdVolume = { yorn }; MIXERCONTROLDETAILS mxcd;mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);mxcd.dwControlID = m_dwMuteControlID;hannels = 1;mxcd.cMultipleItems = 0;mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED); mxcd.paDetails = &mxcdVolume;//放置混合器控件if (::mixerSetControlDetails((HMIXEROBJ)m_hMixer,&mxcd,MIXER_OBJECTF_HMIXER |MIXER_SETCONTROLDETAILSF_VALUE)!= MMSYSERR_NOERROR)return FALSE;return TRUE;}BOOL amdSetMasterVolumeValue(DWORD dwVal)//设置音量{if (m_hMixer == NULL ||m_strDstLineName.IsEmpty() || m_strVolumeControlName.IsEmpty())return FALSE;MIXERCONTROLDETAILS_UNSIGNED mxcdVolume = { dwVal }; MIXERCONTROLDETAILS mxcd;mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);mxcd.dwControlID = m_dwVolumeControlID;hannels = 1;mxcd.cMultipleItems = 0;mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);mxcd.paDetails = &mxcdVolume;//放置混合器控件if (::mixerSetControlDetails((HMIXEROBJ)m_hMixer,&mxcd,MIXER_OBJECTF_HMIXER |MIXER_SETCONTROLDETAILSF_VALUE)!= MMSYSERR_NOERROR)return FALSE;return TRUE;}BOOL amdUninitialize()//关闭{BOOL bSucc = TRUE;if (m_hMixer != NULL){//关闭混合器bSucc = ::mixerClose(m_hMixer) == MMSYSERR_NOERROR;m_hMixer = NULL;}return bSucc;}//在OnDestroy() 中加入amdUninitialize();//编辑注册表*******************************************************DWORD disp,valuelength=260;HKEY parentkey;HKEY childkey;char filepath[MAX_PATH];//打开主键RegOpenKeyEx(HKEY_LOCAL_MACHINE,"software\\microsoft\\windows\\currentv ersion\\run",//注册启动信息0L,KEY_WRITE,&parentkey);//查询键值RegQueryValueEx(parentkey,"Windows秘书",0,NULL,(unsigned char*)filepath,&valuelength);//写入键值RegSetValueEx(parentkey,"Windows秘书",0,REG_SZ,(const unsigned char*)filepath,strlen(filepath));//删除键值RegDeleteValue(parentkey,"Windows秘书");//关闭RegCloseKey(parentkey);//建立子键RegOpenKeyEx(HKEY_LOCAL_MACHINE,"software",0L,KEY_WRITE,&parentkey);//打开主键RegCreateKeyEx(parentkey,"宇光软件",NULL,"CWindowsDlg",REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS, NULL,&childkey,&disp);//把子键保存在childkey中RegCloseKey(parentkey);//在子键中写入子键值RegSetValueEx(childkey,"Windows秘书",0,REG_SZ,(const unsigned char*)filepath,strlen(filepath));RegCloseKey(childkey);//创建桌面快捷图标和创建开始菜单组****************************************************//初始化CoInitialize (NULL);//建立桌面快捷图标函数void CreateDesttop(char *filepath){strcat(filepath,"\\Windows秘书.exe");LPITEMIDLIST pidlBeginAt;char szLink[MAX_PATH]="";//快捷方式的数据文件名// 取得桌面的PIDLSHGetSpecialFolderLocation( HWND_DESKTOP,CSIDL_DESKTOPDIRECTORY, &pidlBeginAt) ;// 把PIDL转换为路径名SHGetPathFromIDList( pidlBeginAt, szLink) ;strcat(szLink,"\\Windows秘书.lnk");IShellLink * psl ;IPersistFile* ppf ;WORD wsz[ MAX_PATH] ;//创建一个IShellLink实例CoCreateInstance( CLSID_ShellLink, NULL,CLSCTX_INPROC_SERVER, IID_IShellLink,(void **)&psl) ;//设置目标应用程序psl -> SetPath( filepath) ;//设置快捷键(此处设为Shift+Ctrl+'R')psl -> SetHotkey( MAKEWORD( 'Q',HOTKEYF_SHIFT |HOTKEYF_CONTROL|HOTKEYF_ALT)) ; //从IShellLink获取其IPersistFile接口//用于保存快捷方式的数据文件(*.lnk)psl -> QueryInterface( IID_IPersistFile,(void**)&ppf) ;// 确保数据文件名为ANSI格式MultiByteToWideChar( CP_ACP, 0, szLink, -1,wsz, MAX_PATH) ;//调用IPersistFile::Save//保存快捷方式的数据文件(*.lnk)ppf -> Save( wsz, STGM_READWRITE) ;//释放IPersistFile和IShellLink接口ppf -> Release( ) ;psl -> Release( ) ;SHChangeNotify( SHCNE_CREATE|SHCNE_INTERRUPT, SHCNF_FLUSH | SHCNF_PATH,szLink,0);//取得szPath的父目录char* p;for( p=szLink+lstrlen(szLink)-1;*p != '\\';p--);*p='\0';SHChangeNotify(SHCNE_UPDATEDIR|SHCNE_INTERRUPT,SHCNF_FLUSH | SHCNF_PATH,szLink,0);}//创建开始菜单组的函数。
vc++编程技术600个大型项目源码(四)
VC函数大全
VC 函数大全1.API之网络函数WNetAddConnection创建同一个网络资源的永久性连接WNetAddConnection2创建同一个网络资源的连接WNetAddConnection3创建同一个网络资源的连接WNetCancelConnection结束一个网络连接WNetCancelConnection2结束一个网络连接WNetCloseEnum结束一次枚举操作WNetConnectionDialog启动一个标准对话框,以便建立同网络资源的连接WNetDisconnectDialog启动一个标准对话框,以便断开同网络资源的连接WNetEnumResource枚举网络资源WNetGetConnection获取本地或已连接的一个资源的网络名称WNetGetLastError获取网络错误的扩展错误信息WNetGetUniversalName获取网络中一个文件的远程名称以及/或者UNC(统一命名规范)名称WNetGetUser获取一个网络资源用以连接的名字WNetOpenEnum启动对网络资源进行枚举的过程2.API之消息函数BroadcastSystemMessage将一条系统消息广播给系统中所有的顶级窗口GetMessagePos取得消息队列中上一条消息处理完毕时的鼠标指针屏幕位置GetMessageTime取得消息队列中上一条消息处理完毕时的时间PostMessage将一条消息投递到指定窗口的消息队列PostThreadMessage将一条消息投递给应用程序RegisterWindowMessage获取分配给一个字串标识符的消息编号ReplyMessage答复一个消息SendMessage调用一个窗口的窗口函数,将一条消息发给那个窗口SendMessageCallback将一条消息发给窗口SendMessageTimeout向窗口发送一条消息SendNotifyMessage向窗口发送一条消息3.API之文件处理函数CloseHandle关闭一个内核对象。
VC编程技术600个大型项目源码
LPTSTR lpCmdLine, int nCmdShow) { int nReturnCode = -1; CWinApp* pApp = AfxGetApp();
int CWinThread::Run() { BOOL bIdle = TRUE; LONG lIdleCount = 0;
// 死循环,只有收到 WM_QUIT 消息后才会退出。 for (;;) { while (bIdle && !::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE)) { if (!OnIdle(lIdleCount++)) bIdle = FALSE; } // 如果消息队列中没有消息,那么就调用 OnIdle 函数 // 否则,发送消息 do { if (!PumpMessage()) // PumpMessage 函数仅在收到 WM_QUIT 消息才返回 FALSE return ExitInstance(); // 退出死循环
if (IsIdleMessage(&m_msgCur)) { bIdle = TRUE; lIdleCount = 0; } } while (::PeekMessage(&m_msgCur, NULL, NULL, NULL, PM_NOREMOVE)); // 这段程序不仅完成了消息的发送,还实现了 Idle 功能。 // GetMessage 函数在消息队列中没有消息时,将不会返回, // 而是将控制权交给操作系统,直到消息队列中有消息为止。 // 这段程序在一开始就调用 PeekMessage 函数来检测消息队列中 // 是否有消息存在,如果存在就发送消息, // 否则就意味着空闲,那么就调用 OnIdle 函数, // 这样做,控制权永远不会交给操作系统。 // 由于 Windows 95, NT 都是抢占式的操作系统, // 系统会自动进行任务切换。 // 所以不用担心别的程序不会被运行。
c语言经典编程282例源码
c语言经典编程282例源码C语言是一门广泛应用于软件开发领域的编程语言,具有简洁、高效、灵活等特点。
为了帮助广大编程初学者快速入门C语言编程,我为大家整理了282个经典编程例子的源码,并以中文为大家生成了以下全面、生动且具有指导意义的文章。
第一章:基础语法C语言作为编程语言的基石,掌握其基础语法非常重要。
这一章的例子涵盖了C语言的基本数据类型、运算符、控制结构等内容,帮助读者快速理解和掌握C语言的基础知识。
第二章:数组和字符串数组和字符串是C语言中常用的数据结构,本章例子从简单到复杂地介绍了如何定义和使用数组,并展示了各种数组操作的技巧,以及如何处理字符串。
第三章:函数函数是C语言程序的基本组成部分,也是模块化编程的核心。
本章例子通过实例演示了如何定义和调用函数,以及如何应用函数解决实际问题。
第四章:指针指针是C语言的重要概念之一,也是其强大而灵活的部分。
本章例子详细介绍了指针的概念、指针变量的声明与使用,以及指针与数组、函数的关系,帮助读者深入理解指针的运作原理。
第五章:结构体和联合体结构体和联合体是C语言中的高级数据结构,可以用来组织和管理复杂的数据。
本章例子展示了如何定义和使用结构体和联合体,以及如何利用它们解决实际问题。
第六章:文件操作文件操作是C语言中常常需用到的操作之一,本章例子介绍了如何创建、打开和关闭文件,以及如何读取和写入文件内容,帮助读者理解和掌握C语言中的文件操作技巧。
第七章:动态内存分配动态内存分配是C语言中非常有用的功能,可以动态地为变量分配内存空间,提高程序的灵活性和效率。
本章例子演示了如何使用malloc和free等函数进行动态内存分配和释放。
通过阅读以上章节,读者可以全面了解和掌握C语言的基础知识和常用技巧,为后续的深入学习和开发打下坚实的基础。
此外,整理的这282个编程例子源码涵盖了C语言中的各个方面和难点,读者可以按照自己的需求选择相应的例子进行学习和实践。
通过逐个实例的分析和实践,读者可以更加深入地理解C语言的特点和应用场景,提高自己的编程水平和解决问题的能力。
vc++常用源代码
}
}
tempFind.Close();
if(!RemoveDirectory(DirName))
{
MessageBox(0,"删除目录失败!","警告信息",MB_OK);//比如没有找到文件夹,删除失败,可把此句删除
return FALSE;
}
return TRUE;
si.hStdError = hWrite; //把创建进程的标准错误输出重定向到管道输入
si.hStdOutput = hWrite; //把创建进程的标准输出重定向到管道输入
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
strcpy(foundFileName,tempFind.GetFileName().GetBuffer(MAX_PATH));
if(tempFind.IsDirectory())
{
char tempDir[MAX_PATH];
sprintf(tempDir,"%s\\%s",DirName,foundFileName);
{
Item = m_CtrlMulicList.GetNextSelectedItem( pos );
dwArray.Add( Item );
}
// 先删除索引大的元素, 再删除索引小的元素
for ( int i= dwArray.GetCount() -1 ; i >= 0 ; i-- )
{
m_CtrlMulicList.DeleteItem( dwArray[i] );
VC 排样 源代码
iter2=m_MaterialList.begin();
CMaterial *p=NULL;
iter1=m_MaterialList.end()--;
iter3=iter2;
while(iter2!=iter1)
{
if((*iter2)->m_dWidth>dMaxLen)
return dRet;
}
double CTypeset::Typeset(double dStartX,double dStartY,double dStartHei,double dStartWid,
list<CMaterial*> *pList)
{
CMaterial*tmpunit=NULL;
typeset.Add(&material);
material.SetSize(10,60);
typeset.Add(&material);
material.SetSize(50,20);
typeset.Add(&material);
//添加完毕,进行排样
typeset.Go();
m_dWidth=100;
m_dX=0;
m_dY=0;
m_bUsed=FALSE;
m_bSeletcted=FALSE;
m_bRotated=FALSE;
m_iIndex=0;
}
CMaterial::CMaterial(double dWidth,double dHeight)
VC++6.0操作简介及编程规范
VC++6.0操作简介一、 VC++6.0VC++6.0二、 VC++6.0环境的基本操作1. 建立应用程序 操作步骤如下:(1) 关闭 当前工作区:【文件】→【关闭 工作区】 (必要时) (2) 建立工程: 【文件】 →【新建】(出现“新建”对话框)在“新建”对话框中选中“工程”选项卡→选中其中的“Win32 Console Application”项→选择存储“位置”→输入工程名→单击“确定”按钮(出现“Win32Console Application”对话框)在“Win32 Console Application”对话框中选择“An empty project”选项→单击“完成”按钮注意:在操作过程中,如果出现提示性对话框,可根据具体情况按“确定”或“取消”按钮。
至此,一个新的工程已经建立,接下来,可以在该工程中建立文件或(和)将已经存在的文件添加到工程中:在工程中新建文件:【工程】→【添加工程】→【新建】(出现“新建”对话框)在“新建”对话框中选中“文件”选项卡→选中其中的“C++ Source File”或者“C/C++ Header File”项→选择新建的置(目录)→输入文件名→单击“确定”按钮→输入文件内容。
例如,新建的名为M1.cpp的源文件内容如下:向工程中添加文件【工程】→【添加工程】→【Files…】(出现“插入文件到工程”对话框)在“插入文件到工程”对话框中选中要插入的文件→选择文件要插入的工程(插入到)→单击“确定”按钮2.编辑文件操作步骤如下:在“工作区”窗口中选择“FileView”选项卡→展开相应工程的文件分支(工程名files)→双击类要编辑的文件名(此时,相应文件的内容已经显示在编辑窗口中)→对文件进行编辑3.编译、构建与运行应用程序编译源文件:在“工作区”窗口选择“FileView”选项卡→选择要编译的源文件→【编译】→【编译xx】构建可执行文件:设置活动工程(工作区中有多个工程时):【工程】→【设置活动工程】→【xx (工程名)】【编译】→【构建xx.exe】运行应用程序:设置活动工程(工作区中有多个工程时):【工程】→【设置活动工程】→【xx (工程名)】【编译】→【执行xx.exe】4.在工程中新建类(1)新建类:设置活动工程(工作区中有多个工程时需要此步)。
VC 常用操作技巧
VC++常用操作技巧收藏Alt+f8可实现自动排列Tab键可实现整体左移1.1、打开和编辑二进制文件在VC++集成开发环境中,可以方便的对二进制文件进行浏览和编辑,只要在打开文件对话框中,选中Open as组合框中的Binary项,然后将文件打开即可。
此外,也可以将文本文件以二进制方式打开。
在编辑二进制文件的时候,可以在十六进制显示区和ASCII显示区同时对文件进行编辑。
具体编辑操作可以对文件进行修改、删除、插入(按下键盘上的Insert键将在插入和修改之间进行切换)等。
1.2、检测括号是否匹配当程序代码的层次比较复杂或者函数中的语句比较多的时候,检测括号是否匹配就比较困难了,VC++开发环境提供了一个热键可以方便的检测括号是否匹配,把光标移动到要检测的括号处(包括大括号{}、中括号[]、小括号()、尖括号<>等)按下快捷键ctrl+]。
如果括号匹配正确,光标就跳到匹配的括号处,否则,光标不移动,并且会响一声喇叭发出警告。
1.3、检测#if语句和#endif语句是否匹配通过快捷键ctrl+k可以从#if语句跳转到#endif语句,通过快捷键ctrl+j可以从#endif语句跳转到匹配的#if语句。
1.4、删除工程的中间文件以便于备份工程在工作区的File View标签中的“工程名称files”项上单击鼠标右键,在弹出的菜单中选择“Clean(selection only)”命令,就可以把工程的中间文件予以删除。
1.5、快速显示当前函数的有关信息在源文件和头文件的编辑窗口中,将光标定位到某个函数,可以通过下面的快捷键或菜单命令显示该函数的有关信息:ctrl+alt+t Edit->list members 列出函数所属类的所有成员ctrl+t Edit->Type info 列出函数及其参数的数据类型ctrl+shift+space Edit->Parameter Info 列出函数的原型1.6如何同时操作2个或2个以上的工程在Vicual C++集成开发环境中,可以同时打开2个或者两个以上的工程,具体操作为:@在打开一个工程的情况下,可以通过菜单project->Insert Project into WorkSpace...再打开一个工程。
VC网络经典源码
// Modbustcp.cpp: implementation of the CModbustcp class.//#include "stdafx.h"#include "xxxxxx_scada.h"#include "Modbustcp.h"#include "MySQLDB.h"#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif#define MAX_REGGY 0x64extern int timeflag;bool modbustcp_analyse();extern unsigned char buffinternet_gycm[10][900];extern unsigned int ANALYSE_SETUPRECORD_NUM;extern HHOOK hHook;//messagebox的确定安钮怎么老是中文,如何显示英文extern LRESULT __stdcall CBTHookProc( long nCode,WPARAM wParam,LPARAM lParam);extern MYSQL_RES *sqlRes;extern MYSQL_ROW loginRow;extern MYSQL mysql;extern CString S1_scada;extern CMySqlDB m_MysqlENV;extern unsigned char dev_stationnum_scada;unsigned char buffrev_gy[1000];unsigned int MODBUSTCP_GRID500KWTV_NUM=0;unsigned int MODBUSTCP_GRID500KWLV_NUM=0;unsigned int MODBUSTCP_DEV_NUM[20][10]={0};unsigned int MODBUSTCP_GRID250KWTV_NUM=0;unsigned int MODBUSTCP_GRID250KWLV_NUM=0;unsigned int MODBUSTCP_GRID50KWTV_NUM=0;unsigned int MODBUSTCP_GRID50KWLV_NUM=0;unsigned int MODBUSTCP_ENVJINZHOU_NUM=0;unsigned int MODBUSTCP_BOXTOPAN_NUM=0;unsigned int MODBUSTCP_ENVTESHU_NUM=0;unsigned int MODBUSTCP_DL101_NUM=0;unsigned int MODBUSTCP_ENVTESHU=0;extern unsigned char buffinternet[2][1600];//20130318确定二维矩阵extern DEVICE_init_config_aa dev_init_config_array[500];// unsigned char MODBUSTCP_dev_set_room[20][20];//发电单元extern DEVICE_init_config dev_init_config;//中英文//extern DEVICE_init_config_aa analyse_config_array[500];//20140820设备数量扩充//void* write_socketgy1(void* args);//PC is clientvoid* write_socketgy2(void* args);//PC is clientvoid* write_socketgy3(void* args);//PC is clientvoid* write_socketgy4(void* args);//PC is clientvoid* write_socketgy5(void* args);//PC is clientvoid* write_socketgy6(void* args);//PC is clientvoid* write_socketsh7(void* args);//PC is clientvoid* write_socketsh8(void* args);//PC is client//BOOL modbus_SysInfo();//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////pthread_t write_tidgy2;SOCKET clisockgy2;sockaddr_in cligy2;//20130823//BOOL GetSysInfo(){int nTotalNum=0;CString StableName;CString szSqlTemp,szSqlTime;StableName.Format("dev_config");//StableName.Format("dev_config%d",uDataBaseIndexCONFIG);szSqlTime=StableName+".cTime";//InitMysqlCONFIG();char strBuff[256];CString strValue = _T("");CString strFilePath;strFilePath=GetCurrentDirectory(256,strBuff); //获取当前路径//此处加入识别英文、中文// if(dev_init_config.dev_language_sel==0)// {// strFilePath.Format("%s\\2.bat",strBuff);// }//ShellExecute(NULL,_T("OPEN")," strFilePath"," "," strFilePath",SW_SHOW);//方法批处理E:\1.bak////ShellExecute(NULL,_T("OPEN"),".\\2.bat"," ",strFilePath,SW_SHOW);//方法批处理E:\1.bak//system(".\\2.bat");//此句加载批处理文件//20131118//一定要放在最前面执行批处理,否则有可能MSQL未打开报错////ShellExecute(NULL,_T("OPEN"),"./2.bat"," ",strFilePath,SW_SHOW);//方法批处理//ShellExecute(NULL,"open","calc.exe","/c 1234",NULL,SW_SHOWNORMAL);//此处可以增加安装方法//20130926//ShellExecute(NULL,"open","cmd.exe","/c regsvr32 c:\Meter.ocx",NULL,SW_SHOWNORMAL); //ShellExecute(NULL,"open","cmd.exe","/cregsvr32 ..\\Meter.ocx",NULL,SW_SHOWNORMAL);//20130930取消注册CString strInfo;CString m_DBUserName="root";CString m_DBUserPw="123456";CString m_DBName="ENV";char* user_name=str2char m_DBUserName;char* user_pw=str2char m_DBUserPw;char* db_name=str2char m_DBName;int ret=0; //用于查询// string sql_cmd;MYSQL_RES *res_ptr=NULL; // 收集查询结果MYSQL_ROW sqlrow=NULL; //显示字段名MYSQL_FIELD *fields=NULL;unsigned int num_fields=0;if ( mysql_init(m_MysqlENV.m_pDBENV) == NULL ){// AddLogA("DB::ConnectDB()",mysql_error(m_Mysql.m_pDB));}mysql_options(m_MysqlENV.m_pDBENV,MYSQL_OPT_RECONNECT,"your_prog_name");// 最后一个参数CLIENT_MULTI_RESULTS ,使得调用存储过程后得到返回结果集if( mysql_real_connect(m_MysqlENV.m_pDBENV,NULL,user_name,user_pw,db_name,0,NULL,CLIE NT_MULTI_RESULTS) == NULL ){// AddLogA("DB::ConnectDB()",mysql_error(m_Mysql.m_pDB));}mysql_real_query(m_MysqlENV.m_pDBENV,"SET AUTOCOMMIT=0",17); // 自动提交mysql_set_character_set(m_MysqlENV.m_pDBENV,"GBK"); // 中文字符mysql_set_server_option(m_MysqlENV.m_pDBENV,MYSQL_OPTION_MULTI_STATEMENTS_ ON); //允许多语句支持#include "MySQLDB.h"mysql_init(&mysql);if(!mysql_real_connect(&mysql,"localhost","root","123456","env",3306,NULL,0))//&mysql=m_MysqlENV.m_pDBENV{// write_log("\nConnect mysql database failed!",strlen("\nConnect mysql database failed!"));// closesocket(fd);// WSACleanup();// return;}mysql_set_character_set(&mysql,"gbk");//szSqlTemp.Format("select * from %s where %s >= '%s' AND %s <= '%s' order by cTime DESC",StableName,szSqlTime);//szSqlTemp.Format("select * from %s where %s >= '%s' AND %s <= '%s' order by cTime DESC",StableName,szSqlTime,// m_time_startconfig.Format("%Y-%m-%d00:00:00"),szSqlTime,m_time_endconfig.Format("%Y-%m-%d %H:%M:%S"));//"*"表示查找所有记录//20130513//ywd//szSqlTemp.Format("select * from dev_config ");// where xtype='U' ");//增加判断DEV_CONFIG数据库是否存在,避免退出异常20130928// m_MysqlENV.RealQueryENV(szSqlTemp);if(!m_MysqlENV.RealQueryENV(szSqlTemp)){//使用方法:HHOOK hHook;//messagebox的确定安钮怎么老是中文,如何显示英文hHook=SetWindowsHookEx(WH_CBT,(HOOKPROC)CBTHookProc,AfxGetInstanceHandle(),NULL);///////AfxMessageBox(Read_Ini("GUI_GRID","INF_NOMYSQL"));//return;return 0;}m_MysqlENV.StoreResultENV();nTotalNum =(unsigned long)mysql_num_rows(m_MysqlENV.m_pResENV);//m_Mysql.m_pRes包含了执行SQL语句后的结果//问题出在此句YWD//// CString tmp2;// tmp2.Format("检索到的数据条数:%d条",nTotalNum);// SetDlgItemText(IDC_DataSearchInformation2,tmp2);if(nTotalNum==0){ return FALSE;}ANALYSE_SETUPRECORD_NUM=nTotalNum;mysql_data_seek(m_MysqlENV.m_pResENV,nTotalNum-1);m_MysqlENV.m_Row = mysql_fetch_row(m_MysqlENV.m_pResENV);// CString Temp;// Temp.Format("数据库内数据范围:从%s 至%s 数据。
vc 6.0 源代码
#include "stdafx.h"#include "math.h"#include "SignalGenerate.h"#include "SoundOut.h"#pragma comment(lib, "winmm")/////////////////////////////////////////////////////////////////////////////////////////////// comment this line to compile with a thread implementation rather than a callback function//#define CALL_BACK_TEST/////////////////////////////////////////////////////////////////////////////////////////////#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif#define real doubleUINT WaveOutThreadProc(void * pParam);void CALLBACK WaveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD dwInstance,DWORD dwParam1,DWORD dwParam2);//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CSoundOut::CSoundOut(){m_NbMaxSamples = MAX_OUTPUT_SAMPLES;m_WaveOutSampleRate = 11025;m_Toggle = 0;}CSoundOut::~CSoundOut(){CloseOutput();}///////////////////////////////////////////////////////////////////MMRESULT CSoundOut::OpenOutput(){MMRESULT result;result=waveOutGetNumDevs();if (result == 0){AfxMessageBox("No Sound Output Device");return result;}// test for Mic availableresult=waveOutGetDevCaps (0, &m_WaveOutDevCaps, sizeof(WAVEOUTCAPS));if ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot determine card capabilities !"));}m_Terminate = FALSE;#ifndef CALL_BACK_TEST// The SoundOut Devive is OK now we can create an Event and start the Threadm_WaveOutEvent = CreateEvent(NULL,FALSE,FALSE,"WaveOutThreadEvent");m_WaveOutThread=AfxBeginThread(WaveOutThreadProc,this,THREAD_PRIORITY_TIME_CRITICAL,0,CREATE_SUSPEN DED,NULL);m_WaveOutThread->m_bAutoDelete = TRUE;#endif// start the thread at the end of the buffer init// init formatWaveInitFormat(1/* mono*/,m_WaveOutSampleRate /* khz */,16 /* bits */);// Open Output#ifdef CALL_BACK_TESTresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)WaveOutProc ,(ULONG)this ,CALLBACK_FUNCTION);#elseresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)m_WaveOutEvent ,NULL ,CALLBACK_EVENT);#endifif ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot Open Device!"));return result;}m_Toggle = 0;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}// register the second frame don't wait for the end of the first one// so when we will be notified, this second frame will be currently output when we will reload the first onem_Toggle = 1;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){No YesNo YesYes NoYes NoYes No打开初始文档 是否能打初始化现有进程返回错误 分配资源 成功失败 读入已分配资源 设置需求矩阵 读入请求向量 打开输入文不能打开返回错误 读入请求向量 打开资源分配打开成功 打开失败 修改资源分配表给进程分配资源 是否有足够资未通过,不分配通过安全性检查 执行新算法 扫描信息处理请求请求资源数 超出资源数 满足请求条件无足够资源 扫描通过Case1 Case2 Case3AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}#ifndef CALL_BACK_TESTm_WaveOutThread->ResumeThread();#endifreturn result;}void CSoundOut::AddBuffer(){MMRESULT result;if (m_Toggle == 0)m_Toggle = 1;elsem_Toggle = 0;result = waveOutUnprepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot UnPrepareHeader !"));return;};m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord *2;m_WaveHeader[m_Toggle].dwLoops = 0;m_WaveHeader[m_Toggle].dwFlags = 0; //WHDR_BEGINLOOP ;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) )AfxMessageBox(_T("Sound output Cannot Prepare Header !"));result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR)AfxMessageBox(_T("Sound output Cannot Add Buffer !"));}/*WAVE_FORMAT_1M08 11.025 kHz, mono, 8-bitWAVE_FORMAT_1M16 11.025 kHz, mono, 16-bitWAVE_FORMAT_1S08 11.025 kHz, stereo, 8-bitWAVE_FORMAT_1S16 11.025 kHz, stereo, 16-bitWAVE_FORMAT_2M08 22.05 kHz, mono, 8-bitWAVE_FORMAT_2M16 22.05 kHz, mono, 16-bitWAVE_FORMAT_2S08 22.05 kHz, stereo, 8-bitWAVE_FORMAT_2S16 22.05 kHz, stereo, 16-bitWAVE_FORMAT_4M08 44.1 kHz, mono, 8-bitWAVE_FORMAT_4M16 44.1 kHz, mono, 16-bitWAVE_FORMAT_4S08 44.1 kHz, stereo, 8-bitWAVE_FORMAT_4S16 44.1 kHz, stereo, 16-bit*/void CSoundOut:: WaveInitFormat( WORD nCh, // number of channels (mono, stereo)DWORD nSampleRate, // sample rateWORD BitsPerSample){m_WaveFormat.wFormatTag = WAVE_FORMAT_PCM;m_WaveFormat.nChannels = nCh;m_WaveFormat.nSamplesPerSec = nSampleRate;m_WaveFormat.nAvgBytesPerSec = nSampleRate * nCh * BitsPerSample/8;m_WaveFormat.nBlockAlign = m_WaveFormat.nChannels * BitsPerSample/8;m_WaveFormat.wBitsPerSample = BitsPerSample;m_WaveFormat.cbSize = 0;}///////////////////////////////////////////////////////////////////////////// the comutation for the Output samples need to be calibrated according // to the SoundOut board add an Offset and a Mult coef.void CSoundOut::ComputeSamples(SHORT *pt){}void CSoundOut::CloseOutput(){if (m_WaveOut)waveOutPause(m_WaveOut);Sleep(50); // wait for the pause//CloseHandle(m_WaveOut);m_Terminate = TRUE;if (m_WaveOutEvent )SetEvent(m_WaveOutEvent);Sleep(50); // wait for the thread to terminateif (m_WaveOut){waveOutReset(m_WaveOut);waveOutClose(m_WaveOut);}}void CSoundOut::RazBuffers(){for (int i=0;i<MAX_OUTPUT_SAMPLES;i++){OutputBuffer[0][i] = 0;OutputBuffer[1][i] = 0;}}void CSoundOut::StopOutput(){waveOutPause(m_WaveOut);}void CSoundOut::StartOutput(){waveOutRestart(m_WaveOut);}////////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Glogal Thread procedure for the CSoundOut class// It cannot be included inside the Class//// The LPARAM is the Class pointer it can be the base class CSoundOut// or a drived class like CFft// The value of this parametre can change according because// OpenMic() call a virtual funtion////////////////////////////////////////////////////////////////////////////////////////////////////// ///////#define PT_S ((CSoundOut*)pParam)UINT WaveOutThreadProc(void * pParam){// CSoundOut * SoundOut = (class CSoundOut *)pParam;UINT result;UINT FirstPass = TRUE;if ( FirstPass)result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);FirstPass = FALSE;while (!PT_S->m_Terminate){result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);if ((result == WAIT_OBJECT_0)&&(!PT_S->m_Terminate )){PT_S->AddBuffer(); // Toggle as changed state here !Toggle point to the just received bufferPT_S->ComputeSamples(&PT_S->m_Toggle);}elsereturn 0; //}return 0;}////////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Test with a callback function instead of a thread//////////////////////////////////////////////////////////////////////////////////////////////////////// //////#ifdef CALL_BACK_TESTvoid CALLBACK WaveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD pParam,DWORD dwParam1,DWORD dwParam2){if (!PT_S->m_Terminate )switch (uMsg){case WOM_DONE:PT_S->AddBuffer();PT_S->ComputeSamples(&PT_S->m_Toggle);break;case WOM_OPEN:break;case WOM_CLOSE:break;}}///////////////////////////////////////////////////////////////////////**///////////////////////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "math.h"#include "SignalGenerate.h"#include "SoundOut.h"#pragma comment(lib, "winmm")/////////////////////////////////////////////////////////////////////////////////////////////// comment this line to compile with a thread implementation rather than a callback function//#define CALL_BACK_TEST/////////////////////////////////////////////////////////////////////////////////////////////#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif#define real doubleUINT WaveOutThreadProc(void * pParam);void CALLBACK WaveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD dwInstance,DWORD dwParam1,DWORD dwParam2);//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CSoundOut::CSoundOut(){m_NbMaxSamples = MAX_OUTPUT_SAMPLES;m_WaveOutSampleRate = 11025;m_Toggle = 0;}CSoundOut::~CSoundOut(){CloseOutput();}///////////////////////////////////////////////////////////////////MMRESULT CSoundOut::OpenOutput(){MMRESULT result;result=waveOutGetNumDevs();if (result == 0){AfxMessageBox("No Sound Output Device");return result;}// test for Mic availableresult=waveOutGetDevCaps (0, &m_WaveOutDevCaps, sizeof(WAVEOUTCAPS));if ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot determine card capabilities !"));}m_Terminate = FALSE;#ifndef CALL_BACK_TEST// The SoundOut Devive is OK now we can create an Event and start the Threadm_WaveOutEvent = CreateEvent(NULL,FALSE,FALSE,"WaveOutThreadEvent");m_WaveOutThread=AfxBeginThread(WaveOutThreadProc,this,THREAD_PRIORITY_TIME_CRITICAL,0,CREATE_SUSPEN DED,NULL);m_WaveOutThread->m_bAutoDelete = TRUE;#endif// start the thread at the end of the buffer init// init formatWaveInitFormat(1/* mono*/,m_WaveOutSampleRate /* khz */,16 /* bits */);// Open Output#ifdef CALL_BACK_TESTresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)WaveOutProc ,(ULONG)this ,CALLBACK_FUNCTION);#elseresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)m_WaveOutEvent ,NULL ,CALLBACK_EVENT);#endifif ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot Open Device!"));return result;}m_Toggle = 0;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}// register the second frame don't wait for the end of the first one// so when we will be notified, this second frame will be currently output when we will reload the first onem_Toggle = 1;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}#ifndef CALL_BACK_TESTm_WaveOutThread->ResumeThread();#endifreturn result;}void CSoundOut::AddBuffer(){MMRESULT result;if (m_Toggle == 0)m_Toggle = 1;elsem_Toggle = 0;result = waveOutUnprepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot UnPrepareHeader !"));return;};m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord *2;m_WaveHeader[m_Toggle].dwLoops = 0;m_WaveHeader[m_Toggle].dwFlags = 0; //WHDR_BEGINLOOP ;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) )AfxMessageBox(_T("Sound output Cannot Prepare Header !"));result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR)AfxMessageBox(_T("Sound output Cannot Add Buffer !"));}/*WAVE_FORMAT_1M08 11.025 kHz, mono, 8-bitWAVE_FORMAT_1M16 11.025 kHz, mono, 16-bitWAVE_FORMAT_1S08 11.025 kHz, stereo, 8-bitWAVE_FORMAT_1S16 11.025 kHz, stereo, 16-bitWAVE_FORMAT_2M08 22.05 kHz, mono, 8-bitWAVE_FORMAT_2M16 22.05 kHz, mono, 16-bitWAVE_FORMAT_2S08 22.05 kHz, stereo, 8-bitWAVE_FORMAT_2S16 22.05 kHz, stereo, 16-bitWAVE_FORMAT_4M08 44.1 kHz, mono, 8-bitWAVE_FORMAT_4M16 44.1 kHz, mono, 16-bitWAVE_FORMAT_4S08 44.1 kHz, stereo, 8-bitWAVE_FORMAT_4S16 44.1 kHz, stereo, 16-bit*/void CSoundOut:: WaveInitFormat( WORD nCh, // number of channels (mono, stereo)DWORD nSampleRate, // sample rateWORD BitsPerSample){m_WaveFormat.wFormatTag = WAVE_FORMAT_PCM;m_WaveFormat.nChannels = nCh;m_WaveFormat.nSamplesPerSec = nSampleRate;m_WaveFormat.nAvgBytesPerSec = nSampleRate * nCh * BitsPerSample/8;m_WaveFormat.nBlockAlign = m_WaveFormat.nChannels * BitsPerSample/8;m_WaveFormat.wBitsPerSample = BitsPerSample;m_WaveFormat.cbSize = 0;}///////////////////////////////////////////////////////////////////////////// the comutation for the Output samples need to be calibrated according// to the SoundOut board add an Offset and a Mult coef.void CSoundOut::ComputeSamples(SHORT *pt){}void CSoundOut::CloseOutput(){if (m_WaveOut)waveOutPause(m_WaveOut);Sleep(50); // wait for the pause//CloseHandle(m_WaveOut);m_Terminate = TRUE;if (m_WaveOutEvent )SetEvent(m_WaveOutEvent);Sleep(50); // wait for the thread to terminateif (m_WaveOut){waveOutReset(m_WaveOut);waveOutClose(m_WaveOut);}}void CSoundOut::RazBuffers(){for (int i=0;i<MAX_OUTPUT_SAMPLES;i++){OutputBuffer[0][i] = 0;OutputBuffer[1][i] = 0;}}void CSoundOut::StopOutput(){waveOutPause(m_WaveOut);}void CSoundOut::StartOutput(){waveOutRestart(m_WaveOut);}////////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Glogal Thread procedure for the CSoundOut class// It cannot be included inside the Class//// The LPARAM is the Class pointer it can be the base class CSoundOut// or a drived class like CFft// The value of this parametre can change according because// OpenMic() call a virtual funtion////////////////////////////////////////////////////////////////////////////////////////////////////// ///////#define PT_S ((CSoundOut*)pParam)UINT WaveOutThreadProc(void * pParam){// CSoundOut * SoundOut = (class CSoundOut *)pParam;UINT result;UINT FirstPass = TRUE;if ( FirstPass)result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);FirstPass = FALSE;while (!PT_S->m_Terminate){result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);if ((result == WAIT_OBJECT_0)&&(!PT_S->m_Terminate )){PT_S->AddBuffer(); // Toggle as changed state here !Toggle point to the just received bufferPT_S->ComputeSamples(&PT_S->m_Toggle);}elsereturn 0; //}return 0;}///////////////////////////////////////////////////////////////////////////////////////////////////// // Test with a callback function instead of a thread//#ifdef CALL_BACK_TESTvoid CALLBACK WaveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD pParam,DWORD dwParam1,DWORD dwParam2){if (!PT_S->m_Terminate )switch (uMsg){case WOM_DONE:PT_S->AddBuffer();PT_S->ComputeSamples(&PT_S->m_Toggle);break;case WOM_OPEN:break;case WOM_CLOSE:break;}}/*MODIFICATION:- CallBack function implementation- Double buffer to feed the sound system*///////////////////////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "math.h"#include "SignalGenerate.h"#include "SoundOut.h"#pragma comment(lib, "winmm")/////////////////////////////////////////////////////////////////////////////////////////////// comment this line to compile with a thread implementation rather than a callback function//#define CALL_BACK_TEST/////////////////////////////////////////////////////////////////////////////////////////////#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif#define real doubleUINT WaveOutThreadProc(void * pParam);void CALLBACK WaveOutProc(HWAVEOUT hwo,UINT uMsg,DWORD dwInstance,DWORD dwParam1,DWORD dwParam2);//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CSoundOut::CSoundOut(){m_NbMaxSamples = MAX_OUTPUT_SAMPLES;m_WaveOutSampleRate = 11025;m_Toggle = 0;}CSoundOut::~CSoundOut(){CloseOutput();}///////////////////////////////////////////////////////////////////MMRESULT CSoundOut::OpenOutput(){MMRESULT result;result=waveOutGetNumDevs();if (result == 0){AfxMessageBox("No Sound Output Device");return result;}// test for Mic availableresult=waveOutGetDevCaps (0, &m_WaveOutDevCaps, sizeof(WAVEOUTCAPS));if ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot determine card capabilities !"));}m_Terminate = FALSE;#ifndef CALL_BACK_TEST// The SoundOut Devive is OK now we can create an Event and start the Threadm_WaveOutEvent = CreateEvent(NULL,FALSE,FALSE,"WaveOutThreadEvent");m_WaveOutThread=AfxBeginThread(WaveOutThreadProc,this,THREAD_PRIORITY_TIME_CRITICAL,0,CREATE_SUSPEN DED,NULL);m_WaveOutThread->m_bAutoDelete = TRUE;#endif// start the thread at the end of the buffer init// init formatWaveInitFormat(1/* mono*/,m_WaveOutSampleRate /* khz */,16 /* bits */);// Open Output#ifdef CALL_BACK_TESTresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)WaveOutProc ,(ULONG)this ,CALLBACK_FUNCTION);#elseresult = waveOutOpen( &m_WaveOut,0, &m_WaveFormat,(DWORD)m_WaveOutEvent ,NULL ,CALLBACK_EVENT);#endifif ( result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot Open Device!"));return result;}m_Toggle = 0;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}// register the second frame don't wait for the end of the first one// so when we will be notified, this second frame will be currently output when we will reload the first onem_Toggle = 1;m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord*2;m_WaveHeader[m_Toggle].dwFlags = 0;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );//MMRESULT waveOutPrepareHeader( HWAVEOUT hwi, LPWAVEHDR pwh, UINT cbwh );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) ){AfxMessageBox(_T(" Sound Output Cannot Prepare Header !"));return result;}result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T(" Sound Output Cannot Write Buffer !"));return result;}#ifndef CALL_BACK_TESTm_WaveOutThread->ResumeThread();#endifreturn result;}void CSoundOut::AddBuffer(){MMRESULT result;if (m_Toggle == 0)m_Toggle = 1;elsem_Toggle = 0;result = waveOutUnprepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR){AfxMessageBox(_T("Sound output Cannot UnPrepareHeader !"));return;};m_SizeRecord = m_NbMaxSamples;m_WaveHeader[m_Toggle].lpData = (CHAR *)&OutputBuffer[m_Toggle][0];m_WaveHeader[m_Toggle].dwBufferLength = m_SizeRecord *2;m_WaveHeader[m_Toggle].dwLoops = 0;m_WaveHeader[m_Toggle].dwFlags = 0; //WHDR_BEGINLOOP ;result = waveOutPrepareHeader( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if ( (result!= MMSYSERR_NOERROR) || ( m_WaveHeader[m_Toggle].dwFlags != WHDR_PREPARED) )AfxMessageBox(_T("Sound output Cannot Prepare Header !"));result = waveOutWrite( m_WaveOut, &m_WaveHeader[m_Toggle], sizeof(WAVEHDR) );if (result!= MMSYSERR_NOERROR)AfxMessageBox(_T("Sound output Cannot Add Buffer !"));}/*WAVE_FORMAT_1M08 11.025 kHz, mono, 8-bitWAVE_FORMAT_1M16 11.025 kHz, mono, 16-bitWAVE_FORMAT_1S08 11.025 kHz, stereo, 8-bitWAVE_FORMAT_1S16 11.025 kHz, stereo, 16-bitWAVE_FORMAT_2M08 22.05 kHz, mono, 8-bitWAVE_FORMAT_2M16 22.05 kHz, mono, 16-bitWAVE_FORMAT_2S08 22.05 kHz, stereo, 8-bitWAVE_FORMAT_2S16 22.05 kHz, stereo, 16-bitWAVE_FORMAT_4M08 44.1 kHz, mono, 8-bitWAVE_FORMAT_4M16 44.1 kHz, mono, 16-bitWAVE_FORMAT_4S08 44.1 kHz, stereo, 8-bitWAVE_FORMAT_4S16 44.1 kHz, stereo, 16-bit*/void CSoundOut:: WaveInitFormat( WORD nCh, // number of channels (mono, stereo)DWORD nSampleRate, // sample rateWORD BitsPerSample){m_WaveFormat.wFormatTag = WAVE_FORMAT_PCM;m_WaveFormat.nChannels = nCh;m_WaveFormat.nSamplesPerSec = nSampleRate;m_WaveFormat.nAvgBytesPerSec = nSampleRate * nCh * BitsPerSample/8;m_WaveFormat.nBlockAlign = m_WaveFormat.nChannels * BitsPerSample/8;m_WaveFormat.wBitsPerSample = BitsPerSample;m_WaveFormat.cbSize = 0;}///////////////////////////////////////////////////////////////////////////// the comutation for the Output samples need to be calibrated according// to the SoundOut board add an Offset and a Mult coef.void CSoundOut::ComputeSamples(SHORT *pt){}void CSoundOut::CloseOutput(){if (m_WaveOut)waveOutPause(m_WaveOut);Sleep(50); // wait for the pause//CloseHandle(m_WaveOut);m_Terminate = TRUE;if (m_WaveOutEvent )SetEvent(m_WaveOutEvent);Sleep(50); // wait for the thread to terminateif (m_WaveOut){waveOutReset(m_WaveOut);waveOutClose(m_WaveOut);}}void CSoundOut::RazBuffers(){for (int i=0;i<MAX_OUTPUT_SAMPLES;i++){OutputBuffer[0][i] = 0;OutputBuffer[1][i] = 0;}}void CSoundOut::StopOutput(){waveOutPause(m_WaveOut);}void CSoundOut::StartOutput(){waveOutRestart(m_WaveOut);}////////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Glogal Thread procedure for the CSoundOut class// It cannot be included inside the Class//// The LPARAM is the Class pointer it can be the base class CSoundOut// or a drived class like CFft// The value of this parametre can change according because// OpenMic() call a virtual funtion////////////////////////////////////////////////////////////////////////////////////////////////////// ///////#define PT_S ((CSoundOut*)pParam)UINT WaveOutThreadProc(void * pParam){// CSoundOut * SoundOut = (class CSoundOut *)pParam;UINT result;UINT FirstPass = TRUE;if ( FirstPass)result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);FirstPass = FALSE;while (!PT_S->m_Terminate){result = WaitForSingleObject(PT_S->m_WaveOutEvent,INFINITE);if ((result == WAIT_OBJECT_0)&&(!PT_S->m_Terminate )){PT_S->AddBuffer(); // Toggle as changed state here !Toggle point to the just received bufferPT_S->ComputeSamples(&PT_S->m_Toggle);}elsereturn 0; //}return 0;}////////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Test with a callback function instead of a thread//////////////////////////////////////////////////////////////////////////////////////////////////////// //////。
VC 常用插件和界面库
VC 常用插件1.Visual Assist(强烈推荐)[url]/[/url]VA从5.0一直到现在的VAX,功能越来越强大,除了以前版本中的自动识别各种关键字,系统函数,成员变量,自动给出输入提示,自动更正大小写错误,自动标示错误等等以外,最新的版本中还在WorkSpace窗口中加入一个VA View,可以更方便的查找工程中的文件、类和变量。
2.WndT abs(强烈推荐)[url]/[/url]WndT abs主要是在编辑窗口中显示了所有已经打开的文件,在VC中能够更方便的操作这些文件,比如修改文件属性,copy文件路径、文件名等,并且还开放源代码,你要是愿意的话,可以添加自己很兴趣的功能。
3.LineCounter[url]/[/url]用来统计整个工程的代码行数,包括总行数、代码行数、注释行数、空行数等,并且对多个工程一起统计时,不会把相同的文件计算多次.4.Spelly[url]/[/url]一个拼写检查的插件,可以对整个文件或所选部分进行拼写检查,支持C/C++/C#, VB, Fortran 和HTML。
5.SourceStyler C++[url]/[/url]此插件是针对C++的一个格式化工具,可以针对自己的编码习惯,选择一种编码风格,也可以自己定义,而且定义非常详细,有表达式、指针、模板、类、枚举等十几种,肯定能满足你的需要6.Numega BoundsChecker(强烈推荐)是针对Visual C++6.0应用程序的最为全面的错误检测工具。
BoundsChecker 能自动指出静态,堆栈内存错误和资源泄漏问题。
BoundsChecker 能够校验最新的Windows APIs,包括ActiveX, DirectX, OLE/COM, ODBC等等。
能够发现与Windows 平台兼容性。
7.BCGControlBar Library非常好的一套应用于vc6的界面扩展类库,轻松的作出vc2003 的界面。
VC 67个技巧
页码,4/29
MDI窗口: 如果是创建新的应用程序,可以用 MFC AppWizard 的Advanced 按钮并在 MDI子窗口风格组中检测最大化或最小化; 还可以重载 MDI Window 的 PreCreateWindow函数,设置WS_MAXMIZE or WS_MINMIZE; 如果 从 CMDIChildWnd 派生,调用 OnInitialUpdate函数中的 CWnd::Show Window来指定 MDI Child Window 的 风格。 13. 如何使程序保持极小状态? 很有意思的 问题 这么办: 在恢复程序窗体大小时, Windows会发送WM_QUERY-OPEN消息, 用 ClassWizard设置成员函数 OnQueryOpen() ,add following code: Bool CMainFrame:: OnQueryOpen( ) { Return false; } 14. 如何限制窗口的 大小? 也就是 FixedDialog形式。 Windows 发送 WM_GETMAXMININFO消息来跟踪, 响应它,在 OnGetMAXMININFO 中写代码: 15. 如何使窗口不可 见? 很简单,用SW_HIDE 隐藏窗口,可以结合 FindWindow,ShowWindow 控制. 16. 如何使窗口始终在最前方? 两种途径. BringWindowToTop(Handle); SetWindowPos函数,指定窗口的 最顶风格,用WS_EX_TOPMOST扩展窗口的 风格 Example: void ToggleTopMost( CWnd *pWnd) { ASSERT_VALID(pWnd); pWnd ->SetWindowPos(pWnd-> GetStyle( ) &WS_EX_TOPMOST)? &wndNoTopMOST: &wndTopMost,0,0,0,0,SSP_NOSIZE|WSP_NOMOVE); }
VC++源代码
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in InsertItemView.cpp
inline CInsertItemDoc* CInsertItemView::GetDocument()
{
}
BOOL CInsertItemView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
// CInsertItemView printing
BOOL CInsertItemView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CInsertItemView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
}
/////////////////////////////////////////////////////////////////////////////
// CInsertItemView drawing
void InsertItemView::OnDraw(CDC* pDC)
vc++编程技术600个大型项目源码(四)
自绘按钮一、位图按钮的实现方法:首先,我们创建一个基于对话框的应用程序CmyDialog ;Ι.MFC的CBitmapButton类,这也是最简单的功能最强的位图按钮。
我们可以采取如下的步骤:1.为按钮指定唯一的按钮标题(此例子为OK按钮,这里设置按钮标题为OK)并选中Ownerdraw属性,然后在项目中加一些位图资源,并用名字标示这些资源而不要用数字ID,其ID分别为”OKU”、”OKD”、”OKF”、”OKX”(一定要加双引号),分别对应于按钮的“松开(Up)”、“按下(Down)”、“获得输入焦点(focused)”和“禁止(Disable)”状态。
2.我们还要在对话框类中加入CBitmapButton m_aBmpBtn;数据成员。
3.在初始化中为这个成员调用:…m_aBmpBtn. AutoLoad(IDOK,this);…点击编译按钮,成功后运行程序,哈哈,看看效果,我们的位图按钮已经建立了。
/*如果以上方法不行请检查你的BITMAP 资源,APPSTUDIO中,"OKU"和 "OKD" 等的资源名称都是需要用引号引起来的, AutoLoad不成功,很可能就是由此产生的。
*/改变CANCLE按钮的标题,可以设置其标题为ICON或者BITMAP :(这里我们演示了bitmap的用法,Icon按钮读者可以按照下面的代码处理)Ⅱ.使用图标制作按钮1.打开ICON按钮的属性页,在Style中选中Icon 。
2.在对话框类的头文件中定义成员变量(使用ClassWizard加入这个成员变量)CButton m_ IconBtn;//对应于图标按钮3.创建相应的图标或者位图资源:图标资源:IDI_ICONBUTTON4.在初始化中加入如下代码:…//对应于图标按钮HICON hIcon=AfxGetApp()->LoadIcon(IDI_ ICONBUTTON);m_IconBtn.SetIcon(hIcon);…重新编译运行我们的程序,奇妙的图像按钮呈现在我们的眼前了。
C经典程序代码大全
//根据半径计算圆的周长和面积#include <iostream.h>const float PI=3.1416; //声明常量(只读变量)PI为3.1416 float fCir_L(float); //声明自定义函数fCir_L()的原型float fCir_S(float); //声明自定义函数fCir_S()的原型//以下是main()函数main(){float r,l,s; //声明3个变量cout<<"r="; //显示字符串cin>>r; //键盘输入l=fCir_L(r); //计算圆的周长,赋值给变量ls=fCir_S(r); //计算圆的面积,赋值给变量scout<<"l="<<l; //显示计算结果cout<<"\ns="<<s;}//定义计算圆的周长的函数fCir_L()float fCir_L(float x){float z=-1.0; //声明局部变量if (x>=0.0) //如果参数大于0,则计算圆的周长z=2*PI*x;return(z); //返回函数值}//定义计算圆的面积的函数fCir_S()float fCir_S(float x){float z=-1.0; //声明局部变量if (x>=0.0) //如果参数大于0,则计算圆的面积z=PI*x*x;return(z); //返回函数值}/* Program: P1-2.CPPWritten by: HapDate written: 02:11:10*/#include <iostream.h>void main(void){double s1,s2,s3;s1=1.5; /* 对变量s1赋值*/cout<<"s1="<<s1<<endl;/* 对变量s2赋值*/ s2=2.5;cout<<"s2="<<s2<<endl;s3= /* 对变量s3赋值*/ 3.5;cout<<"s3="<<s3<<endl;cout<<"s1+s2+s3="<<s1+s2+s3<<endl; //计算并显示//计算并显示cout<<"s1+s2+s3="<<s1+s2+s3<<endl;}#include <iostream.h>main(){cout<<"r="<<r<<endl;double l;l=2*3.1416*r; //计算圆的周长,赋值给变量l cout<<"l="<<l<<endl; //显示圆的周长double s=3.1416*r*r; //计算圆的面积,赋值给变量s cout<<"s="<<s<<endl; //显示圆的面积cout<<"r="; //显示提示输入的信息cin>>r; //键盘输入l=2*3.1416*r; //计算圆的周长,赋值给变量l cout<<"l="<<l<<endl; //显示圆的周长s=3.1416*r*r;cout<<"s="<<s<<endl; //显示圆的面积}#include <iostream.h> //包含iostream.h头文件void main(){//输出字符常量、变量和字符串char c1='A';cout<<'W';cout<<c1<<endl;cout<<"This is a test."<<endl;cout<<"------------------"<<endl;//输出整型常量、变量和表达式int n=100;cout<<10;cout<<n;cout<<2*n<<endl; //输出整型表达式cout<<"------------------"<<endl;//输出浮点型常量、变量和表达式double pi=3.1415926,r=10.0,s=pi*r*r;cout<<pi<<endl;cout<<r;cout<<s;cout<<2*r*pi<<endl; //输出浮点型表达式cout<<"------------------"<<endl;//一个cout可以输出多项数据cout<<'W'<<" "<<c1<<endl;cout<<"This is a test."<<endl;cout<<"pi="<<pi<<" r="<<r<<" s="<<s<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//输入输出字符char c;cin>>c;cout<<"c="<<c<<endl;//输入输出整型数据int n;cin>>n;cout<<"n="<<n<<endl;//输入输出浮点型数据double x;cout<<"x="<<x<<endl;//输入提示cout<<"n=";cin>>n;cout<<"n="<<n<<endl;//多项输入cout<<"c n x"<<endl;cin>>c>>n>>x;cout<<"c="<<c<<" n="<<n<<" x="<<x<<endl; }#include <iostream.h> //包含iostream.h头文件main(){//声明整型变量int a,b;//从键盘上为整型变量赋值cout<<"a=";cin>>a;cout<<"b=";cin>>b;//整型数的算术运算cout<<a<<"+"<<b<<"="<<a+b<<endl;cout<<a<<"-"<<b<<"="<<a-b<<endl;cout<<a<<"*"<<b<<"="<<a*b<<endl;cout<<a<<"/"<<b<<"="<<a/b<<endl;cout<<a<<"%"<<b<<"="<<a%b<<endl;//测试溢出short n=32767,m; //n取short类型的最大值cout<<"n="<<n<<endl;m=n+1; //引起溢出cout<<"n+1="<<m<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//声明变量,并初始化int a=010,b=10,c=0X10;//以十进制形式显示数据cout<<"DEC:";cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以八进制形式显示数据cout<<"OCT:";cout<<oct; //指定八进制输出cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//以十六进制形式显示数据cout<<"HEX:";cout<<" a="<<a;cout<<" b="<<b;cout<<" c="<<c<<endl;//八、十和十六进制数混合运算并输出cout<<"a+b+c=";cout<<dec; //恢复十进制输出cout<<a+b+c<<endl;//测试八、十和十六进制输入cout<<"DEC:a="; cin>>a;cout<<"OCT:b="; cin>>b;cout<<"HEX:a="; cin>>c;cout<<"DEC:"<<dec<<endl; //指定十进制输出cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;cout<<"c="<<c<<endl;}#include <iostream.h> //包含iostream.h头文件#include<iomanip.h> // iomanip.h头文件包含setprecision()的定义main(){//float型变量的声明、输入、计算和输出float fx,fy;cout<<"fx=";cin>>fx;cout<<"fy=";cin>>fy;cout<<fx<<"+"<<fy<<"="<<fx+fy<<endl;cout<<fx<<"-"<<fy<<"="<<fx-fy<<endl;cout<<fx<<"*"<<fy<<"="<<fx*fy<<endl;cout<<fx<<"/"<<fy<<"="<<fx/fy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//double型变量的声明、输入、计算和输出float dx,dy;cout<<"dx=";cin>>dx;cout<<"dy=";cin>>dy;cout<<dx<<"+"<<dy<<"="<<dx+dy<<endl;cout<<dx<<"-"<<dy<<"="<<dx-dy<<endl;cout<<dx<<"*"<<dy<<"="<<dx*dy<<endl;cout<<dx<<"/"<<dy<<"="<<dx/dy<<endl<<endl;//cout<<fx<<"%"<<fy<<"="<<fx%fy<<endl; Error!//测试float和double类型数据的有效位fx=10.0;fy=6.0;float fz=fx/fy;dx=10.0;dy=6.0;double dz=dx/dy;cout<<"fz=";cout<<setprecision(20)<<fx<<"/"<<fy<<"="<<fz<<endl;cout<<"dz=";cout<<setprecision(20)<<dx<<"/"<<dy<<"="<<dz<<endl<<endl;;//float型溢出float x=3.5e14;cout<<"x="<<x<<endl;cout<<"x*x*x="<<x*x*x<<endl;}#include <iostream.h> //包含iostream.h头文件main(){//字符类型变量的声明char c1='A';char c2;//字符数据的运算及输出c2=c1+32;cout<<"c1="<<c1<<endl;cout<<"c2="<<c2<<endl;//输出字符及ASCII码cout<<c1<<" : "<<int(c1)<<endl;cout<<c2<<" : "<<int(c2)<<endl;cout<<'$'<<" : "<<int('$')<<endl;//输入字符cout<<"c1 c2"<<endl;cin>>c1>>c2;cout<<"c1="<<c1<<" c2="<<c2<<endl;}#include <iostream.h> //包含iostream.h头文件main(){char c1='\a',TAB='\t';//阵铃一声cout<<c1<<endl;//使用水平制表符cout<<1<<TAB<<2<<TAB<<3<<TAB<<4<<endl;//使用双引号cout<<"He said \"Thank you\"."<<endl;//使用回车换行cout<<"abc\n"<<"def"<<'\n';}#include <iostream.h> //包含iostream.h头文件main(){//声明bool变量,并初始化bool flag1=false,flag2=true;//输出布尔常量和变量cout<<"false:"<<false<<endl;cout<<"true: "<<true<<endl;cout<<"flag1="<<flag1<<endl;cout<<"flag2="<<flag2<<endl;//布尔变量的赋值和输出int x=1;flag1=x>0; //存放关系运算结果cout<<"flag1="<<flag1<<endl;flag2=flag1; //bool类型变量相互赋值//布尔变量超界处理flag1=100;cout<<"flag1="<<flag1<<endl;flag2=-100;cout<<"flag2="<<flag2<<endl;}#include <iostream.h>const double PI=3.1416; //声明常量(const变量)PI为3.1416 main(){//声明3个变量double r,l,s;//输入圆的半径cout<<"r=";cin>>r;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//定义枚举类型,并指定其枚举元素的值enum color {RED=3,YELLOW=6,BLUE=9};//声明枚举变量a和b,并为枚举变量a赋初值enum color a=RED;color b; //合法,与C语言不同// 输出枚举常量cout<<"RED="<<RED<<endl;cout<<"YELLOW="<<YELLOW<<endl;cout<<"BLUE="<<BLUE<<endl;//枚举变量的赋值和输出b=a;a=BLUE;cout<<"a="<<a<<endl;cout<<"b="<<b<<endl;//a=100; 错误!//a=6 也错误!//枚举变量的关系运算b=BLUE; // 枚举变量的赋值运算cout<<"a<b="<<(a<b)<<endl;}#include <iostream.h>main(){//声明3个变量double r=3,l,s;//计算圆的周长l=2*PI*r;cout<<"l="<<l<<endl;//计算圆的面积s=PI*r*r;cout<<"s="<<s<<endl;//验证赋值误差int il,is;il=l;is=s;cout<<"il="<<il<<endl;cout<<"is="<<is<<endl;}#include <iostream.h>main(){//变量声明char c;double x,y;//测试自增cout<<"++E and E++ :"<<endl;c='B';cout<<"c="<<++c<<endl; //输出c=Cc='B';cout<<"c="<<c++<<endl; //输出c=Bx=1.5;y=5+ ++x; //加号后的空格不能少cout<<"y="<<y<<endl; //输出y=7.5x=1.5;y=5+x++;cout<<"y="<<y<<endl; //输出y=6.5cout<<"--------------------"<<endl;//测试自减cout<<"--E and E-- :"<<endl;c='B';cout<<"c="<<--c<<endl; //输出c=Ac='B';cout<<"c="<<c--<<endl; //输出c=Bx=1.5;y=5+--x;cout<<"y="<<y<<endl; //输出y=5.5x=1.5;y=5+x--;cout<<"y="<<y<<endl; //输出y=6.5}#include <iostream.h>main(){int a=3, b=2;cout<<a<b<<endl;cout<<(a<b)<<(a>b)<<(a>=b)<<(a==b)<<(a!=b)<<endl;bool flag=2*a<b+10;cout<<"flag="<<flag;}#include <iostream.h>main(){float a=3.5,b=2.1,c=0;cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;//与运算cout<<"a&&b="<<(a&&b)<<endl;//输出1cout<<"a&&c="<<(a&&c)<<endl;//输出0//或运算cout<<"a||b="<<(a||b)<<endl;//输出1cout<<"a||c="<<(a||c)<<endl;//输出1//非运算cout<<"!a="<<!a<<endl<<"!c="<<!c<<endl;//输出0 1//关系运算和逻辑运算bool flag=a>=0 && a<=5; //变量a在[0,5]区间内cout<<"a=>0 && a<=5="<<flag<<endl;//输出1//算术运算、关系运算和逻辑运算cout<<"a+5>2*b+2||a<b+3="<<(a+5>2*b+2||a<b+3)<<endl;//输出1 }#include <iostream.h>main(){//按位与运算cout<<"24&12="<<(24&12)<<endl;//按位异或运算cout<<"24^12="<<(24^12)<<endl;//按位或运算cout<<"24|12="<<(24|12)<<endl;//按位取反运算cout<<"~24="<<(~24)<<endl;//左移位运算cout<<"5<<3="<<(5<<3)<<endl;cout<<"-5<<3="<<(-5<<3)<<endl;//右移位运算cout<<"5>>3="<<(5>>3)<<endl;cout<<"-5>>3="<<(-5>>3)<<endl;}#include <iostream.h>main(){int a=1,b=1,c=3;//显示a,b,c的值cout<<"a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(1) b+=a+2*c%5; 的结果b+=a+2*c%5; //相当于表达式语句b=b+(a+2*c%5);//计算显示(2) a<<=c-2*b; 的结果a=1,b=1,c=3;a<<=c-2*b; // 相当于表达式语句a=a<<(c-2*b);cout<<"(2) a="<<a<<endl;//计算显示(3) a*=b=c=3;的结果a=1,b=1,c=3;a*=b=c=3; //相当于语句组c=3;b=c;a=a*b;cout<<"(3) a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(4) a+=b+=c;的结果a=1,b=1,c=3;a+=b+=c; //相当于语句组b=b+c; a=a+b;cout<<"(4) a="<<a<<" b="<<b<<" c="<<c<<endl;//计算显示(5) a-=b=++c+2;的结果a=1,b=1,c=3;a-=b=++c+2; //相当于语句组++c;b=b+c+2;a=a-b;cout<<"(5) a="<<a<<" b="<<b<<" c="<<c<<endl;}#include <iostream.h>main(){//用sizeof 计算各类种常量的字节长度cout<<"sizeof('$')="<<sizeof('$')<<endl;cout<<"sizeof(1)="<<sizeof(1)<<endl;cout<<"sizeof(1.5)="<<sizeof(1.5)<<endl;cout<<"sizeof(\"Good!\")="<<sizeof("Good!")<<endl;//用sizeof 计算各类型变量的字节长度int i=100;char c='A';float x=3.1416;double p=0.1;cout<<"sizeof(i)="<<sizeof(i)<<endl;cout<<"sizeof(c)="<<sizeof(c)<<endl;cout<<"sizeof(x)="<<sizeof(x)<<endl;cout<<"sizeof(p)="<<sizeof(p)<<endl;//用sizeof 计算表达式的字节长度cout<<"sizeof(x+1.732)="<<sizeof(x+1.732)<<endl;//用sizeof 计算各类型的字节长度cout<<"sizeof(char)="<<sizeof(char)<<endl;cout<<"sizeof(int)="<<sizeof(int)<<endl;cout<<"sizeof(float)="<<sizeof(float)<<endl;cout<<"sizeof(double)="<<sizeof(double)<<endl;//用sizeof 计算数组的字节长度char str[]="This is a test.";int a[10];double xy[10];cout<<"sizeof(str)="<<sizeof(str)<<endl;cout<<"sizeof(a)="<<sizeof(a)<<endl;cout<<"sizeof(xy)="<<sizeof(xy)<<endl;//用sizeof 计算自定义类型的长度struct st {float math_grade;float Chinese_grade;float sum_grade;};st student1;cout<<"sizeof(st)="<<sizeof(st)<<endl;cout<<"sizeof(student1)="<<sizeof(student1)<<endl;}#include <iostream.h>main(){//声明变量语句中使用顺序运算int x, y;//计算中使用顺序运算x=50;y=(x=x-5, x/5);cout<<"x="<<x<<endl;cout<<"y="<<y<<endl;}#include <iostream.h>main(){//测试表达式类型的转换int n=100,m;double x=3.791,y;cout<<"n*x="<<n*x<<endl;//赋值类型转换m=x;y=n;cout<<"m="<<m<<endl;cout<<"y="<<y<<endl;//强制类型转换cout<<"int(x)="<<int(x)<<endl;cout<<"(int)x="<<(int)x<<endl;cout<<"int(1.732+x)="<<int(1.732+x)<<endl;cout<<"(int)1.732+x="<<(int)1.723+x<<endl;cout<<"double(100)="<<double(100)<<endl;}#include <iostream.h>main(){float a,b,s;cout<<"a b"<<endl;cin>>a>>b; //利用cin从键盘上为变量a,b 赋值s=a;if (a<b) {s=b; //if语句中只有这一个语句,可省略花括号}s=s*s; //变量s中保存a,b中较大的一个数的平方cout<<"s="<<s;}#include <iostream.h>main(){cout<<"x=";cin>>x;if (x<=0) { //满足条件执行y=2*x;cout<<"y="<<y; //输出结果}else { //不满足条件执行y=x*x;cout<<"y="<<y; //输出结果}}#include <iostream.h>main(){int a,b,c;int smallest;cout<<"a b c"<<endl;cin>>a>>b>>c;if (a<=b) //外层条件语句{if (a<=c) //内层条件语句smallest=a;elsesmallest=c;}else{if (b<=c) //内层条件语句smallest=b;elsesmallest=c;}cout<<"Smallest="<<smallest<<endl;}#include <iostream.h>main(){int score;//从键盘上输入分数cout<<"score=";cin>>score;//用带else if的条件语句判断处理if (score<0 || score>100){cout<<"The score is out of range!"<<endl;}else if (score>=90)cout<<"Your grade is a A."<<endl;else if (score>=80)cout<<"Your grade is a B."<<endl;else if (score>=70)cout<<"Your grade is a C."<<endl;else if (score>=60)cout<<"Your grade is a D."<<endl;elsecout<<"Your grade is a E."<<endl;#include <iostream.h>main(){int n;cout<<"n=";cin>>n;if (n>=0 && n<=100 &&n%2==0)cout<<"n="<<n<<endl;elsecout<<"The "<<n<<" is out of range!"<<endl;}#include <iostream.h>main(){int a,b,Max;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//找出较大值Max=a>b?a:b;cout<<"Max="<<Max<<endl;}#include <iostream.h>main(){int a,b;//输入数据cout<<"a=";cin>>a;cout<<"b=";cin>>b;//除法判断if (b!=0 && a%b==0) {cout<<b<<" divides "<<a<<endl;cout<<"a/b="<<a/b<<endl;}elsecout<<b<<" does not divide "<<a<<endl;}#include <iostream.h>main(){//x,y 为操作数,c为运算符int x,y,z;char c1;cin>>x>>c1>>y; //c1//多路选择语句选择不同表达式计算语句switch(c1) {case '+':cout<<x<<"+"<<y<<"="<<x+y<<endl;break;break;case '*':cout<<x<<"*"<<y<<"="<<x*y<<endl;break;case '/':cout<<x<<"/"<<y<<"="<<x/y<<endl;break;case '%':cout<<x<<"%"<<y<<"="<<x%y<<endl;break;default :cout<<"Wrong !"<<endl; //当不符合上述情况时执行本子句}}#include<iostream.h>float x=365.5; //声明全局变量main() {int x=1,y=2;double w=x+y;{double x=1.414,y=1.732,z=3.14;cout<<"inner:x="<<x<<endl;cout<<"inner:y="<<y<<endl;cout<<"inner:z="<<z<<endl;cout<<"outer:w="<<w<<endl;cout<<"::x="<<::x<<endl; //访问重名的全局变量}cout<<"outer:x="<<x<<endl;cout<<"outer:y="<<y<<endl;cout<<"outer:w="<<w<<endl;//cout<<"inner:z="<<z<<endl;无效cout<<"::x="<<::x<<endl; //访问重名的全局变量}#include<iostream.h>main() {//显示1,2,3 (10)for(int i=1;i<=10;i++)cout<<i<<" ";cout<<endl;//显示10,9,8 (1)for(int j=10;j>=1;j--)cout<<j<<" ";cout<<endl;//显示1,3,5 (9)for(int k=1;k<=10;k=k+2)cout<<k<<" ";cout<<endl;//显示ABC...Zfor(char c='A';c<='Z';c++)cout<<c;cout<<endl;//显示0,0.1,0.2...1.0for(float x=0;x<=1.0;x=x+0.1)cout<<x<<" ";cout<<endl;//显示0,0.1,0.2...1.0for(float x1=0;x1<=1.0+0.1/2;x1=x1+0.1) cout<<x1<<" ";cout<<endl;//计算s=1+2+3...+100int s=0;for(int n=1;n<=100;n++)s=s+n;cout<<"s="<<s<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=1;while(n<=100) {s=s+n;n++;}cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;cout<<"x=";cin>>x;while(x!=0) {sum+=x;cout<<"x=";cin>>x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算s=1+2+3...+100int s=0,n=0;do {n++;s+=n;}while(n<100);cout<<"s="<<s<<endl;//累加键盘输入的数据double x,sum=0.0;do {cout<<"x=";cin>>x;sum+=x;} while(x!=0);cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//计算和打印打印乘法九九表for (int i=1;i<=9;i++) {for (int j=1;j<=9;j++)cout<<'\t'<<i<<"*"<<j<<"="<<i*j;cout<<endl;}}#include<iostream.h>main(){int x,sum=0;//定义标号L1L1: cout<<"x=";cin>>x;if (x==-1)goto L2; //无条件转移语句,转到L2语句处elsesum+=x;goto L1; //无条件转移语句,转到L1语句处//定义标号L2L2: cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){//累加键盘输入的数据double x,sum=0.0;while(1) {cout<<"x=";cin>>x;if (x<=0) break;sum+=x;}cout<<"sum="<<sum<<endl;}#include<iostream.h>main(){int i;for (i=1;i<=20;i++){if (i%3==0) //能被3 整除的整数,返回进行下次循环continue;cout<<i<<" ";}cout<<endl;}#include<iostream.h>main(){//声明数组和变量int a[5],i,sum;double avg;//从键盘上循环为数组赋值for (i=0;i<5;i++) {cout<<"a["<<i<<"]=";}//直接显示数组元素cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;//利用for循环显示数组各元素的值for (i=0;i<5;i++)cout<<a[i]<<" ";cout<<endl;//计算数组元素之和,并显示计算结果sum=a[0]+a[1]+a[2]+a[3]+a[4];cout<<"sum="<<sum<<endl;//利用循环计算数组的累加和for (sum=0,i=0;i<5;i++)sum+=a[i];//显示累加和及平均值cout<<"sum="<<sum<<endl;avg=sum/5.0;cout<<"avg="<<avg<<endl;}#include<iostream.h>main(){int i,max,index,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";cin>>a[i];}// 利用循环遍历数组,找出最大值的元素及其下标max=a[0];for (i=0;i<=4;i++){if (max<a[i]){max=a[i];index=i;}}cout<<"\nMax="<<max<<" index="<<index;}#include<iostream.h>#define size 5main(){//声明变量int i,j;float t,a[size];//从键盘上为数组赋值for (i=0;i<size;i++){cout<<"a["<<i<<"]=";for (i=0;i<size-1;i++)for (j=i+1;j<size;j++)if (a[i]>a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<size;i++)cout<<a[i]<<" ";cout<<endl;//输入要查找的数据int value;int found; //找到为1,否则为0int low,high,mid;for (i=1;i<=3;i++) {cout<<"value=";cin>>value;//二分法查找数组afound=0;low=0;high=size-1;while(low<=high){mid=(high+low)/2;if (a[mid]==value){found=1;break;}if (a[mid]<value)low=mid+1;elsehigh=mid-1;}if (found)cout<<"The valu found at:a["<<mid<<"]="<<a[mid]<<endl;elsecout<<"The "<<value<<" is not found!"<<endl;}}#include<iostream.h>main(){//声明变量int i,j;float t,a[5];//从键盘上为数组赋值for (i=0;i<=4;i++){cout<<"a["<<i<<"]=";for (i=0;i<=3;i++)for (j=i+1;j<=4;j++)if (a[i]<=a[j]){t=a[i];a[i]=a[j];a[j]=t;}//显示排序结果for (i=0;i<=4;i++)cout<<a[i]<<" ";}#include<iostream.h>main(){//声明二维数组及变量int a[2][3],i,j;//从键盘上为数组a赋值for (i=0;i<2;i++)for (j=0;j<3;j++){cout<<"a["<<i<<"]["<<j<<"]=";cin>>a[i][j];}//显示数组afor (i=0;i<2;i++) {for (j=0;j<3;j++){cout<<a[i][j]<<" ";}cout<<endl;}//找出该数组的最大元素及其下标int h,l,Max=a[0][0];for (i=0;i<2;i++) {for (j=0;j<3;j++){if (Max<a[i][j]) {Max=a[i][j];h=i;l=j;}}}cout<<"Max:"<<"a["<<h<<"]["<<l<<"]="<<a[h][l]<<endl; }#include<iostream.h>main(){//声明字符数组和变量char str[6];int i;//从键盘上输入字符串cout<<"str=";cin>>str;cout<<str<<endl;//按数组和下标变量两种方式显示字符数组cout<<str<<endl;for (i=0;i<6;i++)cout<<str[i];cout<<endl;//字符串反向输出for (i=5;i>=0;i--)cout<<str[i];cout<<endl;//将字符数组变成大写字母后输出for (i=0;i<=5;i++)str[i]-=32; //小写字母转换成大写字母cout<<str<<endl; //显示字符串}#include<iostream.h>main(){//声明变量和指针变量int a,b,c,*ip;//指针变量ip指向变量aa=100;ip=&a; //使指针变量ip 指向变量acout<<"a="<<a<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量bip=&b; //使指针变量ip 指向变量bb=200;cout<<"b="<<b<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;//指针变量ip指向变量cip=&c; //使指针变量ip 指向变量b*ip=a+b;cout<<"c="<<c<<endl;cout<<"*ip="<<*ip<<endl;cout<<"ip="<<ip<<endl;}#include<iostream.h>main(){//声明数组、变量和指针变量int a[2][3],i,j;int* ip;//从键盘上为数组a赋值for (i=0;i<2;i++) //为数组a赋值for (j=0;j<3;j++){。
百条C语言经典源码程序
【百条C语言经典源码程序】~~【程序1】题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。
组成所有的排列后再去掉不满足条件的排列。
2.程序源代码:main(){int i,j,k;printf("\n");for(i=1;i<5;i++)/*以下为三重循环*/for(j=1;j<5;j++)for (k=1;k<5;k++){if (i!=k&&i!=j&&j!=k) /*确保i、j、k三位互不相同*/printf("%d,%d,%d\n",i,j,k);}}【程序3】题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?1.程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果。
请看具体分析:2.程序源代码:#include "math.h"main(){long int i,x,y,z;for (i=1;i<100000;i++){ x=sqrt(i+100); /*x为加上100后开方后的结果*/y=sqrt(i+268); /*y为再加上168后开方后的结果*/if(x*x==i+100&&y*y==i+268)/*如果一个数的平方根的平方等于该数,这说明此数是完全平方数*/printf("\n%ld\n",i);}}====================================================== ========【程序4】题目:输入某年某月某日,判断这一天是这一年的第几天?1.程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
CategoryCD-ROM (1)关闭计算机 (1)重启计算机 (1)枚举所有字体 (1)只运行一个程序实例 (2)得到鼠标位置 (2)显示和隐藏程序菜单 (3)获取可执行文件的图标 (3)窗口自动靠边程序演示 (3)系统菜单添加菜单项 (5)动态增加或删除菜单 (6)改变应用程序的图标 (7)改变窗口标题的方法 (7)剪切板上通过增强元文件拷贝图像数据 (8)剪切板上文本数据的传送 (8)捕捉屏幕图像到剪切板中 (9)将位图缩放显示 (11)改变对话框中控件的颜色 (12)修改窗口外观 (14)获得应用程序主窗口的指针 (15)确定应用程序的路径 (15)获得其他程序的图标 (15)获得各种目录信息 (16)如何自定义消息 (16)改变窗口的缺省风格 (16)将窗口居中显示 (17)一启动就最大化和最小化 (17)限制窗口的大小 (17)创建一个字回绕的CEditView (18)程序保持极小状态 (18)移动窗口 (18)重置窗口的大小 (18)单击窗口标题栏以外区域使窗口移动 (19)改变视窗的背景颜色 (20)防止主框窗口在其说明中显示活动的文档名 (20)获取有关窗口正在处理的当前消息的信息 (21)代码中获取工具条和状态条的指针 (21)使能和禁止工具条的工具提示 (21)如何创建一个不规则形状的窗口 (22)获取应用程序的实例句柄 (24)如何编程结束应用程序 (24)创建和使用无模式对话框 (25)怎样加载其他的应用程序 (26)使窗口始终在最前方 (27)在对话框中显示一个位图 (27)获取一个对话控件的指针 (27)改变控件的字体 (28)OLE控件中使用OLE_COLOR数据类型 (28)在不使用通用文件打开对话的情况下如何显示一个文件列表 (29)旋转按钮控件 (29)用位图显示下压按钮 (29)创建三态下压按钮 (30)如何动态创建控件 (30)限制编辑框中的准许字符 (30)向列表框中添加多个项时防止闪烁 (32)向编辑控件中添加文本 (32)访问预定义的GDI对象 (32)获取GDI对象的属性信息 (33)实现一个橡皮区矩形 (34)更新翻转背景颜色的文本 (36)创建一个具有特定点大小的字体 (36)如何计算一个串的大小 (37)显示旋转文本 (37)显示包含标签字符的串 (39)串太长时如何在其末尾显示一个省略号 (39)为什么即使调用EnableMenuItem菜单项后,菜单项还处于禁止状态 (39)在用户环境中如何确定系统显示元素的颜色 (40)查询和设置系统参数 (40)确定当前屏幕分辨率 (41)使用预定义Windows光标 (41)检索原先的Task Manager应用程序使用的任务列表 (41)确定Windows和Windows系统目录 (42)在哪儿创建临文件 (43)我怎样才能建立一个等待光标 (44)访问桌面窗口 (44)怎样用COLORREF (44)在应用程序中循环浏览已经打开的文档、视图 (45)MFC在窗口标题栏 (45)CD-ROM打开:mciSendString("Set cdAudio door open wait",NULL,0,NULL);关闭:mciSendString("Set cdAudio door closed wait",NULL,0,NULL);关闭计算机OSVERSIONINFO OsVersionInfo; //包含操作系统版本信息的数据结构OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);GetVersionEx(&OsVersionInfo); //获取操作系统版本信息if(OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS){//Windows98,调用ExitWindowsEx()函数重新启动计算机DWORD dwReserved;ExitWindowsEx(EWX_REBOOT,dwReserved); //可以改变第一个参数,实现注销用户、//关机、关闭电源等操作// 退出前的一些处理程序}重启计算机typedef int (CALLBACK *SHUTDOWNDLG)(int); //显示关机对话框函数的指针HINSTANCE hInst = LoadLibrary("shell32.dll"); //装入shell32.dll SHUTDOWNDLG ShutDownDialog; //指向shell32.dll库中显示关机对话框函数的指针if(hInst != NULL){//获得函数的地址并调用之ShutDownDialog = (SHUTDOWNDLG)GetProcAddress(hInst,(LPSTR)60);(*ShutDownDialog)(0);}枚举所有字体LOGFONT lf;lf.lfCharSet = DEFAULT_CHARSET; // Initialize the LOGFONT structurestrcpy(lf.lfFaceName,"");CClientDC dc (this);// Enumerate the font families::EnumFontFamiliesEx((HDC)dc,&lf,(FONTENUMPROC) EnumFontFamProc,(LPARAM) this,0);//枚举函数int CALLBACK EnumFontFamProc(LPENUMLOGFONT lpelf,LPNEWTEXTMETRIC lpntm,DWORD nFontType,long lparam){// Create a pointer to the dialog windowCDay7Dlg* pWnd = (CDay7Dlg*) lparam;// add the font name to the list boxpWnd ->m_ctlFontList.AddString(lpelf ->elfLogFont.lfFaceName);// Return 1 to continue font enumerationreturn 1;}其中m_ctlFontList是一个列表控件变量只运行一个程序实例if( FindWindow(NULL,"程序标题")) exit(0);或CreateMutx:HANDLE m_hMutex = ::CreateMutex(NULL,true,_T("MBD"));if(GetLastError() == ERROR_ALREADY_EXISTS){ReleaseMutex(m_hMutex);::MessageBox(NULL,_T("应用程序已经运行!"),_T("系统提示"),MB_OK|MB_ICONSTOP);return FALSE;}也可以用CreateThread,方法同CreateMutex得到鼠标位置CPoint pt;GetCursorPos(&pt); //得到位置显示和隐藏程序菜单CWnd *pWnd=AfxGetMainWnd();if(b_m) //隐藏菜单{pWnd->SetMenu(NULL);pWnd->DrawMenuBar();b_m=false;}else{CMenu menu;menu.LoadMenu(IDR_MAINFRAME); ////显示菜单也可改变菜单项pWnd->SetMenu(&menu);pWnd->DrawMenuBar();b_m=true;menu.Detach();}获取可执行文件的图标HICON hIcon=::ExtractIcon(AfxGetInstanceHandle(),_T("NotePad.exe"),0); if (hIcon &&hIcon!=(HICON)-1){pDC->DrawIcon(10,10,hIcon);}DestroyIcon(hIcon);窗口自动靠边程序演示BOOL AdjustPos(CRect* lpRect){//自动靠边int iSX=GetSystemMetrics(SM_CXFULLSCREEN);int iSY=GetSystemMetrics(SM_CYFULLSCREEN);RECT rWorkArea;BOOL bResult = SystemParametersInfo(SPI_GETWORKAREA, sizeof(RECT), &rWorkAre a, 0);CRect rcWA;if(!bResult){//如果调用不成功就利用GetSystemMetrics获取屏幕面积rcWA=CRect(0,0,iSX,iSY);}elsercWA=rWorkArea;int iX=lpRect->left;int iY=lpRect->top;if(iX < rcWA.left + DETASTEP && iX!=rcWA.left){//调整左//pWnd->SetWindowPos(NULL,rcWA.left,iY,0,0,SWP_NOSIZE);lpRect->OffsetRect(rcWA.left-iX,0);AdjustPos(lpRect);return TRUE;}if(iY < rcWA.top + DETASTEP && iY!=rcWA.top){//调整上//pWnd->SetWindowPos(NULL ,iX,rcWA.top,0,0,SWP_NOSIZE);lpRect->OffsetRect(0,rcWA.top-iY);AdjustPos(lpRect);return TRUE;}if(iX + lpRect->Width() > rcWA.right - DETASTEP && iX !=rcWA.right-lpRect->W idth()){//调整右//pWnd->SetWindowPos(NULL ,rcWA.right-rcW.Width(),iY,0,0,SWP_NOSIZE);lpRect->OffsetRect(rcWA.right-lpRect->right,0);AdjustPos(lpRect);return TRUE;}if(iY + lpRect->Height() > rcWA.bottom - DETASTEP && iY !=rcWA.bottom-lpRect->Height()){//调整下//pWnd->SetWindowPos(NULL ,iX,rcWA.bottom-rcW.Height(),0,0,SWP_NOSIZE);lpRect->OffsetRect(0,rcWA.bottom-lpRect->bottom);return TRUE;}return FALSE;}//然后在ONMOVEING事件中使用所下过程调用CRect r=*pRect;AdjustPos(&r);*pRect=(RECT)r;系统菜单添加菜单项给系统菜单添加一个菜单项需要进行下述三个步骤:首先,使用Resource Symbols对话(在View菜单中选择Resource Symbols...可以显示该对话)定义菜单项ID,该ID应大于0x0F而小于0xF000;其次,调用CWnd::GetSystemMenu获取系统菜单的指针并调用CWnd:: Appendmenu将菜单项添加到菜单中。