重写硬盘的引导扇区再格式化,进入纯dos: FDISK /MBR
AnsiString str = “1234|asdf”;
AnsiString str1;
int i = str.AnsiPos(“|”);
str1 = str.SubString(0,i-1);
ShowMessage(str1);
AnsiString ConnStr1;
ConnStr1 = Format(“%d”,ARRAYOFCONST(((int)11)));
ShowMessage(ConnStr1);
return;
TVarRec v[]= {“1111″,”2222″,”3333″,”4444″};
ConnStr1 = Format(“Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=%s;Data Source=%s”,v,ARRAYSIZE(v));
ShowMessage(ConnStr1);
AnsiString ConnStr;
ConnStr = Format(“Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;\
Initial Catalog=%s;Data Source=%s”,ARRAYOFCONST((pwd,Uid,DataBase,connServer)));
//cb 调用存储过程
/* declare @userid varchar(32)
declare @fee numeric(8,2)
declare @manage varchar(32)
declare @type numeric(2,0)
declare @status numeric(1,0)
set @userid = ’20048888′
set @fee = 1.11
set @type = 1
set @manage = ‘manage’
exec sp_pay_for_thirdparty @userid,@fee,@manage,@type,@status output
print @status
*/
ADOStoredProc1->Close();
ADOStoredProc1->Parameters->Items[1]->Value = “20048888″;
ADOStoredProc1->Parameters->Items[2]->Value = “1.15″;
ADOStoredProc1->Parameters->Items[3]->Value = “manage”;
ADOStoredProc1->Parameters->Items[4]->Value = 1;
ADOStoredProc1->ExecProc();
int i = ADOStoredProc1->Parameters->Items[5]->Value;
ShowMessage(i);
/***************************/
/* ShowMessage(ConnStr);
/*VC Studio 使用技巧大全 2.0版本
源代码和技术资料站点
http://www.vchelp.net/ gb
http://www.csdn.net/ gb
http://www.codeguru.com/ en
http://www.codetools.com/ en
http://www.dexv.com/ en
msdn.microsoft.com en
http://www.programmerheaven.com/ en
http://www.freshmeat.net/ en
http://www.sourceforge.net/ en
www-900.ibm.com/developerWorks/ gb
论坛和标准,组织
http://www.linuxaid.com.cn/ gb
http://www.linuxbyte.com/ gb
http://www.aka.org.cn/ gb
http://www.rfc.org/ en gb
/*///////////////////////////////////////////
*1。在工具条下加汉字
*////////////////////////////////////////////
m_wndToolBar.SetButtonText(11,” 启动 “);
m_wndToolBar.SetButtonText(12,” 停止 “);
CRect rc(0, 0, 0, 0);
CSize sizeMax(0, 0);
CToolBarCtrl& bar = m_wndToolBar.GetToolBarCtrl();
for (int nIndex = bar.GetButtonCount() – 1; nIndex >= 0; nIndex–)
{
bar.GetItemRect(nIndex, rc);
rc.NormalizeRect();
sizeMax.cx = __max(rc.Size().cx, sizeMax.cx);
sizeMax.cy = __max(rc.Size().cy, sizeMax.cy);
}
//sizeMax.cx += 10;
m_wndToolBar.SetSizes(sizeMax, CSize(16,15));
/*///////////////////////////////////////////
*2。删除非空目录
*////////////////////////////////////////////
SHFILEOPSTRUCT shfileop;
shfileop.hwnd = NULL;
shfileop.wFunc = FO_DELETE ;
shfileop.fFlags = FOF_SILENT | FOF_NOCONFIRMATION ;
shfileop.pFrom = “c:\\test”;
shfileop.pTo = “”;
shfileop.lpszProgressTitle = “”;
shfileop.fAnyOperationsAborted = TRUE;
int nOK = SHFileOperation(&shfileop);
/////////////////////////////////////////////
/*///////////////////////////////////////////
*3。字符串转整型值
*////////////////////////////////////////////
CString str = “a1b2c3d4″;
unsigned long i;
sscanf(str,”%x”,&i);
/*///////////////////////////////////////////
*4。弹出数字
*////////////////////////////////////////////
void Tanchu(int i)
{
CString str=”";
str.Format(“%d”,i);
AfxMessageBox(str);
}
/*///////////////////////////////////////////
*5。不让界面死掉
*////////////////////////////////////////////
void DoMessageLoop()
{
MSG msg;
while(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
DispatchMessage(&msg);
TranslateMessage(&msg);
}
}
/*///////////////////////////////////////////
*6。弹出无符号数组内容
*////////////////////////////////////////////
void ShowML(unsigned char *buf1,int i)
{
unsigned char *buf=buf1;
CString str=”",str1=”";
for (int j=0;j<i;j++)
{
str.Format(“%02x “,*(buf+j));
str1=str1+str;
}
AfxMessageBox(str1);
}
/*///////////////////////////////////////////
*7。鼠标移到ICO上,变图标 ICO ID为IDC_ABOUT
*////////////////////////////////////////////
BOOL CDemoCeshiDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if(pMsg->message==WM_MOUSEMOVE && pMsg->hwnd==m_myhelp.GetSafeHwnd())
{
SetCursor(AfxGetApp()->LoadStandardCursor(MAK EINTRESOURCE(IDC_HELP)));
}
return CDialog::PreTranslateMessage(pMsg);
}
/*///////////////////////////////////////////
*8。设置对话框的颜色
*////////////////////////////////////////////
SetDialogBkColor(RGB (131,177,210), RGB(0,0,255));
/*///////////////////////////////////////////
*9。在RichEdit中显示字符串
*////////////////////////////////////////////
void CRichEdDlg::Message(CRichEditCtrl *rich,LPCTSTR lpszMessage,COLORREF clr)
{
// if(!GetDocument()->allowshow) return;
CHARFORMAT cf;
cf.cbSize = sizeof(CHARFORMAT);
cf.dwMask = CFM_COLOR | CFM_FACE | CFM_SIZE | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE;
// m_rich.GetSelectionCharFormat(cf);
if (cf.dwEffects & CFE_AUTOCOLOR) cf.dwEffects -= CFE_AUTOCOLOR;
// Get a color from the common color dialog.
cf.crTextColor = clr;
cf.dwMask = CFM_COLOR;
rich->SetSelectionCharFormat(cf);
rich->ReplaceSel(lpszMessage);
//UnlockWindowUpdate();
}
/*///////////////////////////////////////////
*10。ADO中空值的处理,
*////////////////////////////////////////////
_variant_t var;
CString temp;
_bstr_t bstr;
var = m_pRS->GetCollect(“字段1″);
or
m_rs->Fields->Item["avg"]->Value;
or i 从0开始
m_rs->Fields->Item[(long)i]->Value;
if(var.vt != NULL)
{
bstr=variant_inp;
temp.Format(“%s”,(LPCTSTR)(_bstr_t)bstr);
}
/*///////////////////////////////////////////
*11。ADO的连接字符串,
*////////////////////////////////////////////
_bstr_t strConnect=”Provider=SQLOLEDB;Server=202.116.3.27;Database=d atabase_name; uid=user_name; pwd=password”;
/*///////////////////////////////////////////
*12。放置文本数据到粘贴板
*////////////////////////////////////////////
UpdateData(1);
HGLOBAL HMem;
char *pMem;
HMem = (char*)::GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,m_1.GetLeng th()+1);
if (HMem == NULL)
return;
pMem=(char*)::GlobalLock(HMem);
if (pMem == NULL)
{
::GlobalFree(HMem);
return;
}
::lstrcpy(pMem,m_1);
::GlobalUnlock(HMem);
if (!OpenClipboard())
{
::GlobalFree(HMem);
return;
}
::EmptyClipboard();
::SetClipboardData(CF_TEXT,HMem);
HMem=0;
::CloseClipboard();
/*///////////////////////////////////////////
*13。从粘贴板读文本数据到字符串
*////////////////////////////////////////////
if (!IsClipboardFormatAvailable(CF_TEXT))
return ;
if (!OpenClipboard())
return ;
char *lptstr = new char[1024] ;
HGLOBAL hglb = GetClipboardData(CF_TEXT);
if (hglb != NULL)
{
memset(lptstr,0,1024);
lptstr = (char *)GlobalLock(hglb);
if (lptstr != NULL)
{
GlobalUnlock(hglb);
}
}
CloseClipboard();
m_2 += lptstr ;
UpdateData(0);
/*///////////////////////////////////////////
*14。得到选择目录
*////////////////////////////////////////////
CString str;
BROWSEINFO bi;
char name[MAX_PATH];
ZeroMemory(&bi,sizeof(BROWSEINFO));
bi.hwndOwner=GetSafeHwnd();
bi.pszDisplayName=name;
bi.lpszTitle=”Select folder”;
bi.ulFlags=BIF_RETURNONLYFSDIRS;
LPITEMIDLIST idl=SHBrowseForFolder(&bi);
if(idl==NULL)
return;
SHGetPathFromIDList(idl,str.GetBuffer(MAX_PATH));
MessageBox(str);
/*///////////////////////////////////////////
*15。保存当前屏幕到Bmp文件
*////////////////////////////////////////////
void SaveBmp()
{
CDC dc;
dc.CreateDC(“DISPLAY”,NULL,NULL,NULL);
CBitmap bm;
int Width=GetSystemMetrics(SM_CXSCREEN);
int Height=GetSystemMetrics(SM_CYSCREEN);
bm.CreateCompatibleBitmap(&dc,Width,Height);
CDC tdc;
tdc.CreateCompatibleDC(&dc);
CBitmap*pOld=tdc.SelectObject(&bm);
tdc.BitBlt(0,0,Width,Height,&dc,0,0,SRCCOPY);
tdc.SelectObject(pOld);
BITMAP btm;
bm.GetBitmap(&btm);
DWORD size=btm.bmWidthBytes*btm.bmHeight;
LPSTR lpData=(LPSTR)GlobalAllocPtr(GPTR,size);
/////////////////////////////////////////////
BITMAPINFOHEADER bih;
bih.biBitCount=btm.bmBitsPixel;
bih.biClrImportant=0;
bih.biClrUsed=0;
bih.biCompression=0;
bih.biHeight=btm.bmHeight;
bih.biPlanes=1;
bih.biSize=sizeof(BITMAPINFOHEADER);
bih.biSizeImage=size;
bih.biWidth=btm.bmWidth;
bih.biXPelsPerMeter=0;
bih.biYPelsPerMeter=0;
///////////////////////////////////
GetDIBits(dc,bm,0,bih.biHeight,lpData,(BITMAPINFO*)&bih,DIB_RGB_COLORS);
// bm.GetBitmapBits(size,lpData); //此函数在处理5-5-5模式的16位色下会出现颜色混乱
//////////////////////////////
static int filecount=0;
CString name;
name.Format(“pict%04d.bmp”,filecount++);
name=m_Path+name;
BITMAPFILEHEADER bfh;
bfh.bfReserved1=bfh.bfReserved2=0;
bfh.bfType=((WORD)(‘M’<< 8)|’B');
bfh.bfSize=54+size;
bfh.bfOffBits=54;
CFile bf;
if(bf.Open(name,CFile::modeCreate|CFile::modeWrite)){
bf.WriteHuge(&bfh,sizeof(BITMAPFILEHEADER));
bf.WriteHuge(&bih,sizeof(BITMAPINFOHEADER));
bf.WriteHuge(lpData,size);
bf.Close();
nCount++;
}
GlobalFreePtr(lpData);
if(nCount==1)
m_Number.Format(“%d picture captured.”,nCount);
else
m_Number.Format(“%d pictures captured.”,nCount);
UpdateData(FALSE);
}
/*///////////////////////////////////////////
*16。选取文件名。
*////////////////////////////////////////////
第一个参数为true 是打开对话框 .为False 是保存对话框
CFileDialog fileDlg(true,NULL,NULL,NULL,”授权文件 (*.B*)|*.B*||”);
CFileDialog fileDlg(true,NULL,”a.bat”,NULL,”授权文件 (*.B*)|*.B*||”);
if(fileDlg.DoModal()!=IDOK)
return;
m_filename = fileDlg.GetPathName();
/*///////////////////////////////////////////
*17。文件不存在则创建,存在则覆盖。
*////////////////////////////////////////////
CFile f;
if(!f.Open(sfile,CFile::modeReadWrite|CFile::modeNoTru ncate|CFile::typeBinary|CFile::modeCreate))
{
AfxMessageBox(“不能打开出错”);
return;
}
/*///////////////////////////////////////////
*18。屏蔽esc 回车键
*////////////////////////////////////////////
BOOL CCaptureDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg -> message == WM_KEYDOWN)
{
if(pMsg -> wParam == VK_ESCAPE)
return TRUE;
if(pMsg -> wParam == VK_RETURN)
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);
}
/*///////////////////////////////////////////
*19。格式化读取一行文本中的内容
*////////////////////////////////////////////
/*/文件中的内容://////////////
a23456天|123|234|345|哈尔滨|太平|
a27456天|123|34|35|哈尔滨|太平|
*////////////////////////////
CFileDialog fileDlg(true,NULL,NULL,NULL,”文本文件 (*.txt)|*.txt||”);
if(fileDlg.DoModal()!=IDOK)
return;
CString filename = fileDlg.GetPathName();
CStdioFile f;
CString s;
f.Open(filename,CFile::modeRead);
f.ReadString(s);
int a1,a2,a3;
char c1[20],c2[20],c3[20];
memset(c1,0,20);
memset(c2,0,20);
memset(c3,0,20);
int nRet = sscanf( s, “%[^|]|%d|%d|%d|%[^|]|%[^|]|\n”, c1 , &a1 , &a2 , &a3 , c2 , c3 );
f.Close();
/*///////////////////////////////////////////
*20。设置字体
*////////////////////////////////////////////
LOGFONT m_logFont;
memset(&m_logFont,0,sizeof(LOGFONT));
m_logFont.lfHeight=15;
m_logFont.lfWeight=FW_NORMAL;
m_logFont.lfCharSet=134;
m_logFont.lfOutPrecision=OUT_DEFAULT_PRECIS;
m_logFont.lfClipPrecision=CLIP_DEFAULT_PRECIS;
m_logFont.lfQuality=PROOF_QUALITY;
m_logFont.lfPitchAndFamily=FIXED_PITCH;
strcpy(m_logFont.lfFaceName,”宋体”);
CFont font;
font.CreateFontIndirect(&m_logFont);
m_blist.SetFont(&font);
font.DeleteObject();
//------------------------
//从字体对话框中选中字体
LOGFONT lgft;
CFontDialog fd;
CFont m_font;
if(fd.DoModal()==IDOK)
{
fd.GetCurrentFont(&lgft);
m_font.DeleteObject();
m_font.CreateFontIndirect(&lgft);
m_11.SetFont(&m_font);
}
/*///////////////////////////////////////////
*21。读取INI文件
*////////////////////////////////////////////
char IniFile[1024] = “.\\TEL.INI”;//INI文件名,必须是全路径
int a = 10;
a = GetPrivateProfileInt( “ST_TONE” , “ON_TIME” , a , IniFile );
Tanchu(a);
/*///////////////////////////////////////////
*22。用程序创建access Mdb数据库
*////////////////////////////////////////////
HRESULT hr = S_OK;
CString strcnn(_T(“Provider=Microsoft.JET.OLEDB.4.0;Data source = test.mdb”));
try
{
ADOX::_CatalogPtr m_pCatalog = NULL;
hr = m_pCatalog.CreateInstance(__uuidof (ADOX::Catalog));
if(FAILED(hr))
{
_com_issue_error(hr);
}
else
{
m_pCatalog->Create(_bstr_t(strcnn)); //Create MDB
}
}
catch(_com_error &e)
{
AfxMessageBox(_T(“error”));
}
/*///////////////////////////////////////////
*23。连接ACCess Mdb 数据库
*////////////////////////////////////////////
_ConnectionPtr g_pConn;
g_pConn.CreateInstance(__uuidof(Connection));
g_pConn->Open(“Provider=Microsoft.Jet.OLEDB.4.0;Dat a Source=d:\\test.mdb;”,
“”, “”, adConnectUnspecified);
程序退出时,g_pConn->Close();
::CoUninitialize();
/*///////////////////////////////////////////
*24。读取binary数据(variant to byte)
*////////////////////////////////////////////
_CommandPtr m_cmdCard,m_cmdWater;
m_cmdCard.CreateInstance(__uuidof(Command));
m_cmdCard->ActiveConnection=m_ConnCard;
_RecordsetPtr trd;
m_cmdCard->CommandText = “select * from tabidenti”;
trd = m_cmdCard->Execute(NULL,NULL,adCmdText);
_variant_t var1;
CString s,s1;
_bstr_t bstr1;
if(trd->GetCollect(“Fees”).vt == VT_NULL)
{
MessageBox(“为空”);
}
var1 = trd->GetCollect(“Fees”);
COleSafeArray safeArray_inp;
long len,k;
BYTE rxdata[2048];
safeArray_inp = var1;
len = safeArray_inp.GetOneDimSize();
for(k = 0 ;k<len;k++)
{
safeArray_inp.GetElement(&k,rxdata+k);
}
for(k = 0;k<len;k++)
{
BYTE by = *(char*)(rxdata+k);
s.Format(“%02x”,by);
s1+=s;
}
MessageBox(s1);
return;
/*///////////////////////////////////////////
*25。得到路径名,不要文件名
*////////////////////////////////////////////
CString str = “c:\\1\\2\\a.bat”;
str.MakeReverse();
int iiii = str.Find(‘\\’);
str = str.Right(str.GetLength() – iiii);
str.MakeReverse();
MessageBox(str);
return;
/*///////////////////////////////////////////
*26。取得数据库中bigint 数据 到__int64 中
*////////////////////////////////////////////
_variant_t var = pRcs->GetCollect((LONG)0);
CString str;
_bstr_t bstr=var;
str.Format(“%s”,(LPCTSTR)(_bstr_t)bstr);
MessageBox(str);
__int64 tint64 ;
tint64 = _atoi64(str);
/*///////////////////////////////////////////
*27。动态调用DLL
*////////////////////////////////////////////
typedef int(_cdecl *Connect)(int i);
HINSTANCE hinstDLL=NULL;
hinstDLL=LoadLibrary(“vcDll.dll”);
if (hinstDLL)
{
Connect Proc;
Proc = (Connect)GetProcAddress (hinstDLL,”Tanchu”);
int iValue = Proc(1234);
FreeLibrary(hinstDLL);
char * p = new char[10];
sprintf(p,”%d”,iValue);
AfxMessageBox(p);
}
else
{
AfxMessageBox(“没少到dll”);
}
/*///////////////////////////////////////////
*28。注册OCX控件
*////////////////////////////////////////////
void Regkongjian(LPCTSTR kjName)
{
// TODO: Add your control notification handler code here
//ActiveX控件的路径及文件名
LPCTSTR pszDllName=kjName;
//装载ActiveX控件
HINSTANCE hLib = LoadLibrary(pszDllName);
if (hLib < (HINSTANCE)HINSTANCE_ERROR)
{
AfxMessageBox(“不能载入OCX文件!”);
return;
}
//获取注册函数DllRegisterServer地址
FARPROC lpDllEntryPoint;
lpDllEntryPoint = GetProcAddress(hLib,_T(“DllRegisterServer”));
//调用注册函数DllRegisterServer
if(lpDllEntryPoint!=NULL)
{
if(FAILED((*lpDllEntryPoint)()))
{
AfxMessageBox(“调用DllRegisterServer 失败!”);
FreeLibrary(hLib);
return;
}
// MessageBox(“注册成功”,”结果”,MB_OK);
}
else
AfxMessageBox(“调用DllRegisterServer失败!”);
}
/*///////////////////////////////////////////
*28。得到表中各列的名字
*////////////////////////////////////////////
CDatabase mydb;
CRecordset my(&mydb);
try
{
mydb.OpenEx(_T(“DSN=odbcexcel”),CDatabase::openReadOnly |CDatabase::noOdbcDialog);
my.Open(CRecordset::snapshot, (LPCTSTR)(“Select * From [Sheet1$]“));
}
catch(…)
{
AfxMessageBox(“无法打开数据库文件”);
return;
}
if(my.IsBOF()) my.MoveFirst();
while(!my.IsEOF()) my.MoveNext();//空跑一遍,以便取得记录总数
int nRows=my.GetRecordCount();//取得总行数
int nCols=my.GetODBCFieldCount();//取得列数
CStringArray strColTitle;
CODBCFieldInfo fieldinfo;
if(strColTitle.GetSize()) strColTitle.RemoveAll();
for(int i=0;i<nCols;i++)//得到列标题
{
my.GetODBCFieldInfo(i,fieldinfo);
strColTitle.Add(LPCTSTR(fieldinfo.m_strName));
CString str=strColTitle.GetAt(i);
MessageBox(str);
}
//ADO中
_RecordsetPtr m_recordset1;
_CommandPtr m_command1;
m_recordset1.CreateInstance(__uuidof(Recordset));
m_command1.CreateInstance(__uuidof(Command));
m_command1->ActiveConnection=m_connection;
m_command1->CommandText=”SELECT * FROM RTU order by reg_time desc”;
try
{
m_recordset1=m_command1->Execute(NULL,NULL,adCmdTex t);
Fields *fields=NULL;
HRESULT hr;
hr=m_recordset1->get_Fields(&fields);
long iSum;
if(SUCCEEDED(hr))
hr=fields->get_Count(&iSum);
for(long i=0 ;i<iSum;i++)
{
BSTR bStr;
hr=fields->Item->get_Name(&bStr);
CString str;
str=bStr;
AddInfo(str);
}
}
catch(_com_error e)
{
}
fields->Release();
fields = NULL;
/*///////////////////////////////////////////
*28。序列化
*////////////////////////////////////////////
CStdioFile f1;
TCHAR str[MAX_PATH];
GetCurrentDirectory(MAX_PATH,str);
strcat(str, _T(“\\a.txt“));
f1.Open(str, CFile::modeCreate | CFile::modeWrite );
CArchive archive(&f1, CArchive::store);
CString s1 = “a1111bc”;//如不定义成变量,编辑不过去.
archive << s1;
archive.Close();
f1.Close();
f1.Open(str, CFile::modeRead);
f1.SeekToBegin();
CArchive archive2(&f1, CArchive::load);
CString s;
archive2 >> s;
archive2.Close();
f1.Close();
MessageBox(s);
/*///////////////////////////////////////////
*29。CList 用法
*////////////////////////////////////////////
CList<LPTEST, LPTEST>CTestList;这行去掉typedef 就可以用
CTestList.AddTail(&testl);
不过应该这么赋值吧.
TEST test1;
memcpy(test1.chtest1,”ok”,2);
memcpy(test1.chtest2,”no”,2);
CTestList.AddTail(&test1);
/*///////////////////////////////////////////
*30。调用带参数的程序
*////////////////////////////////////////////
SHELLEXECUTEINFO execinfo;
memset(&execinfo, 0, sizeof(execinfo));
execinfo.cbSize = sizeof(execinfo);
execinfo.lpVerb = “Open”;
execinfo.lpFile =”JzqDb.exe”; //所要执行的外部程序
execinfo.lpParameters = “SA”; // file://参数
execinfo.fMask = SEE_MASK_NOCLOSEPROCESS;
execinfo.nShow = SW_NORMAL; //SW_SHOWDEFAULT;显示窗体类型
//SendMessage(WM_MINIMIZE);
ShowWindow(SW_MINIMIZE);
if (ShellExecuteEx(&execinfo))
{
WaitForSingleObject(execinfo.hProcess, INFINITE);
}
ShowWindow(SW_NORMAL);
/*///////////////////////////////////////////
*31。导入lib文件
*////////////////////////////////////////////
#pragma comment( lib , “vcDll.lib” )
/*///////////////////////////////////////////
*32。动态调用Dll中的函数
*////////////////////////////////////////////
typedef void (_cdecl *Connect)(int i);
HINSTANCE hinstDLL=NULL;
hinstDLL=LoadLibrary(“mfcdll.dll”);
if (hinstDLL)
{
Connect Proc;
Proc = (Connect)GetProcAddress (hinstDLL,”DyDialog”);
if(Proc)
{
Proc(11);
}
FreeLibrary(hinstDLL);
}
else
{
AfxMessageBox(“没找到dll”);
}
/*///////////////////////////////////////////
*33。考文件
*////////////////////////////////////////////
if(CopyFile(“aa.txt”,”bb.txt”,0))
MessageBox(“cheng gong”);
/*///////////////////////////////////////////
*34。排序列表
*////////////////////////////////////////////
struct tagBANK
{
int BankSn;
int LocalSn;
};
CList<tagBANK,tagBANK> BankList;
tagBANK *pHead = NULL;
int SortCmp(const void *elem1, const void *elem2 )
{
tagBANK * p1 = ( tagBANK * ) elem1 ;
tagBANK * p2 = ( tagBANK * ) elem2 ;
if( p1->LocalSn > p2->LocalSn ) return 1;
if( p1->LocalSn == p2->LocalSn ) return 0;
if( p1->LocalSn < p2->LocalSn ) return -1;
return 0;
}
//初始化
BankList.RemoveAll();
tagBANK Node;
Node.BankSn = 5;
BankList.AddTail(Node);
Node.BankSn = 6;
BankList.AddTail(Node);
Node.BankSn = 3;
BankList.AddTail(Node);
Node.BankSn = 4;
BankList.AddTail(Node);
Node.BankSn = 2;
BankList.AddTail(Node);
Node.BankSn = 1;
BankList.AddTail(Node);
//排序
tagBANK Node;
POSITION pos = BankList.GetHeadPosition(),prev;
while(pos != NULL)
{
prev = pos;
Node = BankList.GetNext(pos);
Node.LocalSn = Node.BankSn + 10;
BankList.RemoveAt(prev);
BankList.InsertBefore(pos,Node);
}
if( BankList.GetCount() != 0)
pHead = (tagBANK * )malloc(sizeof(tagBANK)*BankList.GetCount() );
pos = BankList.GetHeadPosition(),prev;
int i =0;
while(pos != NULL)
{
prev = pos;
Node = BankList.GetNext(pos);
pHead = Node;
i++;
}
qsort( pHead , BankList.GetCount() , sizeof(tagBANK), SortCmp );
//显示
tagBANK Node;
CString str;
POSITION pos = BankList.GetHeadPosition(),prev;
int i = 0;
while(pos != NULL)
{
prev = pos;
Node = BankList.GetNext(pos);
str.Format(“localsn%d–banksn%d”,Node.LocalSn,Node.BankSn); //显示原有内容
m_list.AddString(str);
str.Format(“localsn%d–banksn%d”,pHead.LocalSn,pHead.BankSn);//显示排序后内容
m_list.AddString(str);
i++;
}
if(pHead != NULL)
free(pHead);
/*///////////////////////////////////////////
*35。DLL中头文件的定义
*////////////////////////////////////////////
#ifndef _CONVFUN_H
#define _CONVFUN_H
#ifndef DATACONV_EXPORTS
#define CONVDLLAPI __declspec(dllimport)
#else
#define CONVDLLAPI __declspec(dllexport)
#endif
/*///////////////////////////////////////////
*36。设置显示器分辨率
*////////////////////////////////////////////
void CMainFrame::SetStartMode()//设置显示器分辨率
{
DEVMODE lpDevMode;
lpDevMode.dmPelsHeight=768;
lpDevMode.dmPelsWidth=1024;
lpDevMode.dmDisplayFrequency=85;
lpDevMode.dmFields=DM_PELSWIDTH|DM_PELSHEIGHT|DM_DISPLAYFREQ UENCY;
ChangeDisplaySettings(&lpDevMode,0);
this->BringWindowToTop();
}
/*///////////////////////////////////////////
*37。备份还原数据库
*////////////////////////////////////////////
CString str = “backup database 数据库名 to disk = ‘完全文件名’”;
“restore database 数据库名 from disk = ‘完全文件名’”;
/*///////////////////////////////////////////
*38。设置日期时间控件的范围
*////////////////////////////////////////////
CTime t = time(NULL);
CTime t1;
CTimeSpan tspan(1,0,0,0);
t1 = t – tspan;
((CDateTimeCtrl*)GetDlgItem(IDC_DATETIMEPICKER1))-> SetRange(&t1,&t);
/*///////////////////////////////////////////
*39。列标控件的可编辑状态//属性设置Edit labels
*////////////////////////////////////////////
void CTmplistctrlDlg::OnEndlabeleditList1(NMHDR* pNMHDR, LRESULT* pResult)
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
// TODO: Add your control notification handler code here
CString str;
m_list.GetEditControl()->GetWindowText(str);
m_list.SetItemText(pDispInfo->item.iItem,pDispInfo- >item.iSubItem,str);
*pResult = 0;
}
void CTmplistctrlDlg::OnEdit()
{
// TODO: Add your control notification handler code here
POSITION pos = m_list.GetFirstSelectedItemPosition();
if(pos!=NULL)
{
int nItem = m_list.GetNextSelectedItem(pos);
m_list.SetFocus();
m_list.EditLabel(nItem);
}
}
void CTmplistctrlDlg::OnDblclkList1(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
OnEdit();
*pResult = 0;
}
/*///////////////////////////////////////////
*40。设置工具条的移动图片
*////////////////////////////////////////////
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0(“Failed to create toolbar\n”);
return -1; // fail to create
}
CImageList img;
if(!img.Create(IDB_MAINFRAME,32,0,RGB(192,192,192)))
{
TRACE0(“Failed to load hot images\n”);
return -1;
}
m_wndToolBar.GetToolBarCtrl().SetHotImageList(&img );
img.Detach();
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0(“Failed to create status bar\n”);
return -1; // fail to create
}
// TODO: Delete these three lines if you don’t want the toolbar to
// be dockable
m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
CBRS_TOOLTIPS | CBRS_FLYBY);
/*///////////////////////////////////////////
*41。float 与 double 0值的比较
*////////////////////////////////////////////
float f ;
if((f>= -EPSINON) && (f<= EPSINON))
{
}
/*///////////////////////////////////////////
*42。关机,与开机函数
*////////////////////////////////////////////
void CTempCListDlg::CloseComputer()
{
// TODO: Add your control notification handler code here
TOKEN_PRIVILEGES tkp;
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEG ES | TOKEN_QUERY, &hToken))
{
MessageBox(“OpenProcessToken failed!”);
}
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid); //获得本地机唯一的标识
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0); //调整获得的权限
if (GetLastError() != ERROR_SUCCESS)
{
MessageBox(“AdjustTokenPrivileges enable failed!”);
}
int fResult =InitiateSystemShutdown(
“192.168.66.41″, // 要关的计算机用户名,可在局域网网中关掉对方的机器,NULL表示关本机
“由于系统不稳定,WINDOWS将在上面的时间内关机,请做好保存工作!”, // 显示的消息
60, // 关机所需的时间
TRUE,
TRUE); //设为TRUE为重起,设为FALSE为关机
if(!fResult)
{
MessageBox(“InitiateSystemShutdown failed.”);
}
tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
if (GetLastError() != ERROR_SUCCESS)
{
MessageBox(“AdjustTokenPrivileges disable failed.”);
}
// ExitWindowsEx(EWX_SHUTDOWN,0); //开始关机
}
void CTempCListDlg::CancelCloseComputer()
{
// TODO: Add your control notification handler code here
if(::AbortSystemShutdown((LPTSTR)(LPCTSTR)”192.168.66. 41″))
{
AfxMessageBox(“取消成功”);
}
}
/*///////////////////////////////////////////
*43。同步线程
*////////////////////////////////////////////
#include <afxmt.h>
CRITICAL_SECTION m_csNodeList;
InitializeCriticalSection( &m_csNodeList );
EnterCriticalSection( &m_csNodeList );
LeaveCriticalSection( &m_csNodeList );
/*///////////////////////////////////////////
*44。播放AVI文件
*////////////////////////////////////////////
stdafx.h 中加入
#include <Vfw.h>
#include <Mmsystem.h>
#include “Digitalv.h”
#pragma comment(lib,”Winmm.lib”)
类中加入成员变量
MCI_DGV_OPEN_PARMS mciOpen;
OnInitDialog()
加入
{
mciOpen.dwCallback= 0L;
mciOpen.wDeviceID= 0;
mciOpen.lpstrDeviceType= NULL;
mciOpen.lpstrElementName= (char *)(LPCTSTR)”123.avi”;
mciOpen.lpstrAlias= NULL;
mciOpen.dwStyle= WS_CHILD;
}
按钮中加入
DWORD D1 = (DWORD)MCI_NOTIFY|MCI_DGV_PLAY_REPEAT|MCI_FROM;
if(mciOpen.wDeviceID!=0)
{
DWORD dwError = mciSendCommand(mciOpen.wDeviceID,MCI_CLOSE,0,0);
if(dwError)
{
char s[80];
mciGetErrorString(dwError,s,80);
AfxMessageBox(s);
return ;
}
}
mciOpen.hWndParent= m_1.GetSafeHwnd();
DWORD dwError;
dwError = mciSendCommand(0, MCI_OPEN,
(DWORD)(MCI_OPEN_ELEMENT|MCI_DGV_OPEN_PARENT|MCI_DGV_O PEN_WS),
(DWORD)&mciOpen);
if(dwError)
{
char s[80];
mciGetErrorString(dwError,s,80);
AfxMessageBox(s);
return ;
}
DWORD wDeviceID=mciOpen.wDeviceID; //保存设备ID
MCI_DGV_PLAY_PARMS mciPlay;
mciPlay.dwCallback = (DWORD)m_1.GetSafeHwnd();
mciPlay.dwFrom = 0;
mciPlay.dwTo = 0;
dwError = mciSendCommand(wDeviceID, MCI_PLAY,
MCI_NOTIFY|MCI_DGV_PLAY_REPEAT|MCI_F ROM,
(DWORD)(LPMCI_DGV_PLAY_PARMS)&mc iPlay);
/*///////////////////////////////////////////
*45。模拟键盘,鼠标操作 定义热键
*////////////////////////////////////////////
keybd_event(VK_MENU ,0,0,0);
Sleep(10);
keybd_event(67 ,0,0,0);
Sleep(100);
keybd_event(67 ,0,KEYEVENTF_KEYUP,0);
Sleep(100);
keybd_event(VK_MENU ,0,KEYEVENTF_KEYUP,0);
if(!RegisterHotKey(this->m_hWnd, 7777, MOD_CONTROL, ‘S’)) //定义热键
{//switch to new desktop
AfxMessageBox(“不能创建热键!”);
}
BOOL CTempkeyDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
switch(pMsg->message)
{
case WM_HOTKEY:
{
if(pMsg->wParam == 7777)
{
SetTimer(1,1000,NULL);
return TRUE; //不加出错
}
if(pMsg->wParam == 8888)
{
KillTimer(1);
return TRUE; //不加出错
}
break;
}
}
return CDialog::PreTranslateMessage(pMsg);
}
CRect rect(452,324,572,444);
SetCursorPos(rect.left-20,rect.top-20);//1
mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
Sleep(80);
mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
/*///////////////////////////////////////////
*46。CFontDialog 的使用
*////////////////////////////////////////////
//m_11为一个静态文本变量
LOGFONT lgft;
CFontDialog fd;
CFont m_font;
if(fd.DoModal()==IDOK)
{
fd.GetCurrentFont(&lgft);
m_font.DeleteObject();
m_font.CreateFontIndirect(&lgft);
m_11.SetFont(&m_font);
m_r = fd.GetColor();
}
Invalidate();
//重载OnCtlColor函数
if(pWnd->m_hWnd == m_11.GetSafeHwnd())
{
pDC->SetTextColor(m_r);
}
/*///////////////////////////////////////////
*47。列表显示风格
*////////////////////////////////////////////
CJzqDbDlg * pMainWnd=(CJzqDbDlg *)AfxGetApp()->m_pMainWnd;
/* case ID_VIEW_DETAILS:
case ID_VIEW_SMALLICON:
case ID_VIEW_LARGEICON:
case ID_VIEW_LIST:
*/
pMainWnd->OnViewStyle(ID_VIEW_LINEUP,m_meterlist);
void CJzqDbDlg::OnViewStyle(UINT nCommandID,CListCtrl &list)
{
// TODO: customize or extend this code to handle choices on the
// View menu.
// CGDC2000View* pView = GetRightPane();
// if the right-hand pane has been created and is a CGDC2000View,
// process the menu commands…
// if (pView != NULL)
// {
DWORD dwStyle = -1;
switch (nCommandID)
{
case ID_VIEW_LINEUP:
{
// ask the list control to snap to grid
// CListCtrl& refListCtrl = pView->GetListCtrl();
list.Arrange(LVA_SNAPTOGRID);
}
break;
// other commands change the style on the list control
case ID_VIEW_DETAILS:
dwStyle = LVS_REPORT;
break;
case ID_VIEW_SMALLICON:
dwStyle = LVS_SMALLICON;
break;
case ID_VIEW_LARGEICON:
dwStyle = LVS_ICON;
break;
case ID_VIEW_LIST:
dwStyle = LVS_LIST;
break;
}
// change the style; window will repaint automatically
if (dwStyle != -1)
list.ModifyStyle(LVS_TYPEMASK, dwStyle);
// }
}
/*///////////////////////////////////////////
*48。列表和树初始化
*////////////////////////////////////////////
CImageList* pImage = new CImageList;
HICON hIcon;
// pImage->Create( IDR_IMAGE, 16, 2, ::GetSysColor(COLOR_WINDOW) );
pImage->Create(16,16,ILC_COLOR16,3,1);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON1);
pImage->Add(hIcon);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON2);
pImage->Add(hIcon);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON3);
pImage->Add(hIcon);
// Add “About…” menu item to system menu.
LONG IStyle;
IStyle=GetWindowLong(m_blist.m_hWnd,GWL_STYLE); //获取当前窗口类型
IStyle&=~LVS_TYPEMASK; //清除显示方式
// IStyle|=LVS_SINGLESEL|LVS_REPORT; //设置显示方式
IStyle|=LVS_REPORT; //设置显示方式
SetWindowLong(m_blist.m_hWnd,GWL_STYLE,IStyle); //设置窗口类型
m_blist.SetImageList( pImage, TVSIL_NORMAL );
CHeaderCtrl* pHeader = NULL;
pHeader=m_blist.GetHeaderCtrl();
m_blist.m_headerctrl.SubclassWindow(pHeader->m_hWnd );
m_blist.m_headerctrl.SetImageList(pImage);
m_blist.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_G RIDLINES|LVS_EX_HEADERDRAGDROP);
LVCOLUMN lvcol;
lvcol.mask = LVCF_IMAGE;
lvcol.fmt = LVCFMT_IMAGE;
lvcol.iSubItem=0;
lvcol.cx=70;
lvcol.pszText=”数 量”;//
/* m_blist.InsertColumn(0,&lvcol);//*/
m_blist.InsertColumn(0,”电表编号”,LVCFMT_LEFT,80,-1);
m_blist.InsertColumn(1,”相序号”,LVCFMT_LEFT,60,-1);
m_blist.InsertColumn(2,”表箱号”,LVCFMT_LEFT,60,-1);
m_blist.InsertColumn(3,”当前表底”,LVCFMT_LEFT,80,-1);
m_blist.InsertColumn(4,”冻结表底”,LVCFMT_LEFT,80,-1);
m_blist.InsertColumn(5,”零抄月”,LVCFMT_LEFT,60,-1);
m_blist.InsertColumn(6,”电表状态”,LVCFMT_LEFT,80,-1);
m_blist.InsertColumn(7,”负载状态”,LVCFMT_LEFT,80,-1);
m_blist.InsertColumn(8,”抄表时间”,LVCFMT_LEFT,160);
m_blist.m_headerctrl.Update();
m_blist.m_headerctrl.SetItemImage(0,0);
m_blist.m_headerctrl.SetItemImage(1,1);
m_blist.m_headerctrl.SetItemImage(2,1);
m_blist.m_headerctrl.SetItemImage(3,1);
/* m_blist.m_headerctrl.SetItemImage(4,0);
m_blist.m_headerctrl.SetItemImage(5,0);
m_blist.m_headerctrl.SetItemImage(6,2);
*/ IStyle=GetWindowLong(m_tree.m_hWnd,GWL_STYLE); //获取当前窗口类型
IStyle&=~LVS_TYPEMASK; //清除显示方式
//IStyle|=LVS_REPORT; //设置显示方式
IStyle|=TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS |TVS_SHOWSELALWAYS;
SetWindowLong(m_tree.m_hWnd,GWL_STYLE,IStyle); //设置窗口类型
m_tree.SetWindowPos(NULL,8,8,0,0,SWP_NOSIZE|SWP_NOZORD ER|SWP_SHOWWINDOW);
m_tree.SetImageList( pImage, TVSIL_NORMAL );
/*///////////////////////////////////////////
*48。CPen
*////////////////////////////////////////////
BOOL CreatePen( int nPenStyle, int nWidth, COLORREF crColor );
CPen( int nPenStyle, int nWidth, COLORREF crColor );
nPenStyle in
/*
PS_SOLID Creates a solid pen.
PS_DASH Creates a dashed pen. Valid only when the pen width is 1 or less, in device units.
PS_DOT Creates a dotted pen. Valid only when the pen width is 1 or less, in device units.
PS_DASHDOT Creates a pen with alternating dashes and dots. Valid only when the pen width is 1 or less, in device units.
PS_DASHDOTDOT Creates a pen with alternating dashes and double dots. Valid only when the pen width is 1 or less, in device units.
PS_NULL Creates a null pen.
PS_INSIDEFRAME Creates a pen that draws a line inside the frame of closed shapes produced by the Windows GDI output functions that specify a bounding rectangle (for example, the Ellipse, Rectangle, RoundRect, Pie, and Chord member functions). When this style is used with Windows GDI output functions that do not specify a bounding rectangle (for example, the LineTo member function), the drawing area of the pen is not limited by a frame.
PS_GEOMETRIC Creates a geometric pen.
PS_COSMETIC Creates a cosmetic pen.
PS_ALTERNATE Creates a pen that sets every other pixel. (This style is applicable only for cosmetic pens.)
PS_USERSTYLE Creates a pen that uses a styling array supplied by the user.
PS_ENDCAP_ROUND End caps are round.
PS_ENDCAP_SQUARE End caps are square.
PS_ENDCAP_FLAT End caps are flat.
PS_JOIN_BEVEL Joins are beveled.
PS_JOIN_MITER Joins are mitered when they are within the current limit set by the::SetMiterLimit function. If the join exceeds this limit, it is beveled.
PS_JOIN_ROUND Joins are round.
*/
/* BLACK_BRUSH Black brush.
DKGRAY_BRUSH Dark gray brush.
GRAY_BRUSH Gray brush.
HOLLOW_BRUSH Hollow brush (equivalent to NULL_BRUSH).
LTGRAY_BRUSH Light gray brush.
NULL_BRUSH Null brush (equivalent to HOLLOW_BRUSH).
WHITE_BRUSH White brush.
BLACK_PEN Black pen.
WHITE_PEN White pen.
SYSTEM_FONT System font. By default, the system uses the system font to draw menus, dialog box controls, and text.
DEFAULT_PALETTE Default palette. This palette consists of the static colors in the system palette. Windows CE versions 1.0 and 1.01 do not support this value.
*/
LOGBRUSH m_lBrush;
LOGPEN m_lPen;
m_lPen.lopnStyle = PS_INSIDEFRAME;
m_lPen.lopnWidth.x = 1;
m_lPen.lopnWidth.y = 1;
m_lPen.lopnColor = RGB(0, 0, 0);
m_lBrush.lbStyle = BS_SOLID;
// m_lBrush.lbStyle = BS_NULL;
m_lBrush.lbColor = RGB(192, 192, 192);
m_lBrush.lbHatch = HS_HORIZONTAL;
CBrush brush;
if (!brush.CreateBrushIndirect(&m_lBrush))
return;
CPen pen;
if (!pen.CreatePenIndirect(&m_lPen))
return;
CBrush* pOldBrush;
CPen* pOldPen;
pOldBrush = pDC->SelectObject(&brush);
pOldPen = pDC->SelectObject(&pen);
//保存时的转换 。详见Mydraw.dsw
enum DRAWSHAPE
{
elliple,
rect
};
if (ar.IsStoring())
{
ar << m_Rect;
ar << (WORD)m_drawshape;
ar.Write(&m_lBrush, sizeof(m_lBrush));
ar.Write(&m_lPen, sizeof(m_lPen));
}
else
{
ar >> m_Rect;
WORD wTemp;
ar >> wTemp ;
m_drawshape = (DRAWSHAPE)wTemp;
ar.Read(&m_lBrush, sizeof(m_lBrush));
ar.Read(&m_lPen, sizeof(m_lPen));
}
}
/*///////////////////////////////////////////
*48。弹出菜单
*////////////////////////////////////////////
CMenu menu;
menu.LoadMenu(IDR_MENU2);
CPoint *lpoint=new CPoint;
GetCursorPos(lpoint);
menu.GetSubMenu(0)->TrackPopupMenu(TPM_LEFTBUTTON|T PM_LEFTALIGN,lpoint->x,lpoint->y,this);
*pResult = 0;
或
LPPOINT lpoint=new tagPOINT;
::GetCursorPos(lpoint);//得到鼠标位置
CMenu menu;
/// menu.LoadMenu(IDR_MENU1); //声明一个弹出式菜单
//增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口(已
//隐藏),将程序结束。
menu.CreatePopupMenu();
menu.AppendMenu(MF_STRING,ID_APP_EXIT,”关闭”);
menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x,l point->y,this);
//资源回收
HMENU hmenu=menu.Detach();
menu.DestroyMenu();
delete lpoint;
/*///////////////////////////////////////////
*48。系统最小化,最大化,关闭后消息
*////////////////////////////////////////////
LRESULT CMainFrame::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
m_bAutoMenuEnable=0;
switch(message){
case WM_SYSCOMMAND:
//如果是系统消息
if(wParam==SC_MINIMIZE){
//接收到最小化消息时主窗口隐藏
{
AfxGetApp()->m_pMainWnd->ShowWindow( SW_HIDE);
WindowShow=!WindowShow;
m_tnid.hIcon=LoadIcon(AfxGetInstanceHandle (),MAKEINTRESOURCE(IDI_ICON4));
::Shell_NotifyIcon(NIM_MODIFY,&m_tnid) ;
}
return 0;
}
break;
}
return CFrameWnd::WindowProc(message, wParam, lParam);
}
/*///////////////////////////////////////////
*49。设置状态条的文本
*////////////////////////////////////////////
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_SEPARATOR,
ID_SEPARATOR,
};
CString s = “就是练习”;
CStatusBar * m_pStatus=&m_wndStatusBar;
m_pStatus->SendMessage(SB_SETTEXT,1,(LPARAM) ((LPCSTR)s) );
/*///////////////////////////////////////////
*49。去掉重复的错误
*////////////////////////////////////////////
project setting ->link->input->Ignore libraries 填入 libc,libcmt
/*///////////////////////////////////////////
*50。画出资源中的bmp文件
*////////////////////////////////////////////
CRect rc;
GetClientRect(rc);
CDC *pDC = GetDC();
CBitmap m_Bmp;
m_Bmp.LoadBitmap(IDB_BITMAP1);
CBitmap *pBitmap = &m_Bmp;
BITMAP BM;
CDC MemDC;
MemDC.CreateCompatibleDC(NULL);
MemDC.SelectObject(pBitmap);
pBitmap->GetObject(sizeof(BM),&BM);
// pDC->StretchBlt(0,0,BM.bmWidth*12,BM.bmHeight*12, &MemDC,0,0,
// BM.bmWidth,BM.bmHeight,SRCCOPY);
pDC->StretchBlt(0,0,rc.right,rc.bottom,&MemDC,0 ,0,
BM.bmWidth,BM.bmHeight,SRCCOPY);
/*///////////////////////////////////////////
*51。配置Odbc数据源 sqlserver
*////////////////////////////////////////////
//建立ODBC 数据源
#include <ODBCinst.h>
在stdafx.h中加入
#pragma comment(lib ,”odbccp32.lib”)
char *sDriver = “SQL Server”;
char *sAttr = “DSN=”
“aic_trans”
“\0Server=(local)\0″
“Database=AIC_TRANS\0″;
SQLConfigDataSource(NULL,ODBC_ADD_DSN,sDriver,sAttr);
/*///////////////////////////////////////////
*51。运行Sql语句,取记录集,连接数据库
*////////////////////////////////////////////
#import “C:\\Program Files\\Common Files\\System\\ado\\msado15.dll” no_namespace rename(“EOF”, “adoEOF”)
bool CPublicData::ExecuteSql(LPCSTR sqlstr)
{
bool bRet = true;
_CommandPtr m_command1;
m_command1.CreateInstance(__uuidof(Command));
m_command1->ActiveConnection=m_connection;
m_command1->CommandText=sqlstr;
try
{
m_command1->Execute(NULL,NULL,adCmdText);
}
catch(_com_error &e)
{
DebugMsg(“运行Sql语句:%s”,sqlstr);
DebugMsg(“运行Sql语句出错:%s :catch(_com_error &e)”,e.ErrorMessage());
bRet = false;
}
catch(…)
{
DebugMsg(“运行Sql语句:%s”,sqlstr);
DebugMsg(“运行就错直接错误catch(…)”);
bRet = false;
}
return bRet;
}
_RecordsetPtr m_rs;
m_rs.CreateInstance(__uuidof(Recordset));
/*///////////////////////////////////////////
*52。运行存储过程
*////////////////////////////////////////////
int CPublicData::ExecuteProc(int UserID, double fee, CString manager, int tyteFlag)
{
/*
CREATE PROCEDURE sp_pay_for_thirdparty
(
@userid VARCHAR(32),
@fee NUMERIC(8,2),
@manager VARCHAR(32),
@type NUMERIC(2), –1表示普通付费,2表示预付待扣款付费.
@status NUMERIC(1) OUTPUT –1表示成功,0表示失败
)
as
declare @tempa2 char(10)
insert into table2(a1,a2,a3,a4) VALUES (@userid,@fee,@manager,@type);
set @status = 0
GO
*/
int iRet = 0;
CString sOtherNo;
iRet = CPublicData::ExistenceUserID(UserID,sOtherNo);
if(iRet != GETDATABASE_SUCCESS)
{
return 0;
}
m_SqlCriSetion.Lock();
try
{
_CommandPtr m_cmd;
m_cmd.CreateInstance(__uuidof(Command));
m_cmd->ActiveConnection=m_connection;
_ParameterPtr pParm;
pParm=m_cmd->CreateParameter(“userid”,adVarCh ar,adParamInput,-1);
pParm->Value = (LPCTSTR)sOtherNo;
m_cmd->Parameters->Append(pParm);
pParm=m_cmd->CreateParameter(“fee”,adDouble,a dParamInput,-1);
pParm->Value = fee;
m_cmd->Parameters->Append(pParm);
pParm=m_cmd->CreateParameter(“manager”,adVarC har,adParamInput,-1);
pParm->Value = (LPCTSTR)manager;
m_cmd->Parameters->Append(pParm);
pParm=m_cmd->CreateParameter(“typeflag”,adInt eger,adParamInput,-1);
pParm->Value = (FLOAT)tyteFlag;
m_cmd->Parameters->Append(pParm);
pParm=m_cmd->CreateParameter(“iflag”,adIntege r,adParamOutput,-1);
m_cmd->Parameters->Append(pParm);
pParm.Release();
// m_cmd->CommandText = “testproc”;
m_cmd->CommandText = “sp_pay_for_thirdparty”;
m_cmd->CommandType = adCmdStoredProc;
m_cmd->Execute(NULL, NULL, adCmdStoredProc);
_variant_t var2;
var2 = m_cmd->Parameters->GetItem(“iflag”)->GetValue();//
if(var2.vt == VT_NULL)
{
iRet = GETDATABASE_NULL;
}
else
{
iRet = (long)var2;
}
}
catch(_com_error &e)
{
iRet = GETDATABASE_ERROR;
DebugMsg(“运行sp_pay_for_thirdparty过程不正确catch(_com_error)”);
DebugMsg(“错误信息:%s”,e.ErrorMessage());
// Tanchu(e.WCode());
}
catch(…)
{
iRet = GETDATABASE_ERROR;
DebugMsg(“运行sp_pay_for_thirdparty过程不正确catch(…)”);
}
m_SqlCriSetion.Unlock();
return iRet;
}
bool CPublicData::RunSqlstr(_RecordsetPtr &m_rs,LPCSTR sqlstr)
{
bool bRet = true;
_CommandPtr m_command1;
m_command1.CreateInstance(__uuidof(Command));
m_command1->ActiveConnection=m_connection;
m_command1->CommandText=sqlstr;
try
{
m_rs=m_command1->Execute(NULL,NULL,adCmdText);
}
catch(_com_error &e)
{
DebugMsg(“取记录Sql语句:%s”,sqlstr);
DebugMsg(“取记录Sql语句出错:%s:catch(_com_error &e)”,e.ErrorMessage());
bRet= false;
}
catch(…)
{
DebugMsg(“取记录Sql语句:%s”,sqlstr);
DebugMsg(“取记录就错直接错误”);
bRet= false;
}
return bRet;
}
bool CPublicData::OpenTable(_RecordsetPtr &m_rs,LPCSTR sqlstr)
{
bool bRetCode = true;
try
{
m_rs->Open((LPCSTR)sqlstr,m_connection.GetInterface Ptr(),adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch(_com_error &e)
{
MessageBox(e.ErrorMessage());
bRetCode = false;
}
return bRetCode;
}
/****************************/
//例子
UpdateData(1);
m_list.DeleteAllItems();
_ParameterPtr pParm;
_variant_t var;
_bstr_t sqlstr;
sqlstr=_bstr_t(“SELECT * FROM METER WHERE (METER_ID like ?) OR (BOX_NO = ?)”);
try{
pCmd.CreateInstance(__uuidof(Command));
pCmd->ActiveConnection=m_connection;
pCmd->CommandText=sqlstr;
}
catch(_com_error &e)
{
// TransmitMessage(e.Description());
MessageBox(“出错了!”);
return;
}
pParm=pCmd->CreateParameter(“meter_id”,adBSTR,adPar amInput,-1);
pCmd->Parameters->Append(pParm);
pParm=pCmd->CreateParameter(“box_no”,adInteger,adPa ramInput,-1);
// pParm=pCmd->CreateParameter(“box_no”,adBSTR,adPar amInput,-1);
pCmd->Parameters->Append(pParm);
pParm.Release();
ParametersPtr p;
p=pCmd->GetParameters();
p->GetItem(“meter_id”)->Value=(_bstr_t)m_sName;
p=pCmd->GetParameters();
p->GetItem(“box_no”)->Value=(long)15;
// p->GetItem(“box_no”)->Value=(_bstr_t)”15″;
try{
pRcs=pCmd->Execute(NULL,NULL,adCmdText);
}
catch(_com_error &e)
{
TRACE(e.Description());
return ;
}
// temp=pRcs->Fields->GetItem(“M_COUNT”)->Valu e;
CString temp;
_bstr_t bstr;
try
{
int i=0;
for(pRcs->MoveFirst();!(pRcs-> adoEOF==VARIANT_TRUE);pRcs->MoveNext())
{
/* var=pRcs->GetCollect(“met er_id”);
long lrtuid=var;
temp.Format(“%d”,lrtuid);
m_list.InsertItem(i,temp);
bstr=pRcs->Fields->GetIt em(“box_no”)->Value;
temp.Format(“%s”,(LPCTSTR)(_bs tr_t)bstr);
m_list.SetItemText(i,1,temp);
*/
bstr=pRcs->Fields->GetIt em(“meter_id”)->Value;
temp.Format(“%s”,(LPCTSTR)(_bs tr_t)bstr);
m_list.InsertItem(i,temp);
bstr=pRcs->Fields->GetIt em(“box_no”)->Value;
temp.Format(“%s”,(LPCTSTR)(_bs tr_t)bstr);
m_list.SetItemText(i,1,temp);
i++;
}
}
catch(…)
{
AfxMessageBox(“777″);
}
pCmd.Release();
pRcs->Close();
pRcs.Release();
//———————————
_RecordsetPtr m_rs;
m_rs.CreateInstance(__uuidof(Recordset));
// CString strsql = “select Accountno,opertime,submoney from tabmylog order by AccountNo compute avg(submoney) by accountno “;
// MessageBox(strsql);
CString strsql = “select * from tabmylog where id = 5″;
if(!OpenTable(m_rs,strsql))
return ;
/* if(!RunSqlstr(m_rs,strsql))
{
MessageBox(“失败”);
return;
}
*/ try
{
m_rs->PutCollect(“accountno”,(long)2004); //数值字段
m_rs->PutCollect(“opertime”,(LPCSTR)”2004-12-12″);//时间字段
// m_rs->Delete(adAffectCurrent); //删除 adAffectCurrent是删除当前条记录
m_rs->Update();
// m_rs->Fields->GetItem((long)1)->put_V alue((_variant_t)(long)100);
}
catch(_com_error &e)
{
MessageBox(e.ErrorMessage());
}
/**************************/
bool CPublicData::ConnectDB(CString computername,CString username,CString passwd)
{
_RecordsetPtr m_recordset;
HRESULT hr;
CString sqlstr;
m_connection = NULL;
sqlstr.Format(“Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Initial Catalog=mytest;Data Source=%s”,passwd,username,computername);
_bstr_t source = (const char *)sqlstr;
// _bstr_t source(“Provider=SQLOLEDB.1;Data Source=zhaowenlong;Initial Catalog=ConCard”);
// _bstr_t user(“sa”);
_bstr_t user = username;
_bstr_t pwd = passwd;
try
{
// m_connection.CreateInstance(
hr = m_connection.CreateInstance(_uuidof(Connection));
if(SUCCEEDED(hr))
hr = m_connection->Open(source, user, pwd, adOpenUnspecified);
if(SUCCEEDED(hr))
// hr = m_recordset.CreateInstance(__uuidof(Recordset));
// if(SUCCEEDED(hr))
return TRUE;
else
return FALSE;
}
catch (_com_error &e)
{
DebugMsg(“连接数据库返回信息:%s:catch(_com_error &e)”,e.ErrorMessage());
m_connection = NULL;
return FALSE;
}
catch(…)
{
m_connection = NULL;
DebugMsg(“连接数据库非法错误! catch(…)\r\n”);
}
return TRUE;
}
//取出记录例子
CString sqlstr;
int iRet = GETDATABASE_SUCCESS;
try
{
_RecordsetPtr m_rs;
m_rs.CreateInstance(__uuidof(Recordset));
// if(!RunSqlstrB(m_rs,”select * from depart order by list”))
sqlstr.Format(“select * from TabRGCard where AccountNo = %d”,userID);
if(!RunSqlstr(m_rs,sqlstr))
{
iRet = GETDATABASE_ERROR;
}
if(m_rs->BOF == VARIANT_TRUE && m_rs->adoEOF == VARIANT_TRUE)
{
iRet = GETDATABASE_NULL;
}
else
{
_variant_t var;
var.Clear();
var=m_rs->GetCollect(“OtherNo”);
if(var.vt !=VT_NULL)
{
CString temp;
temp.Format(“%s”,(LPCTSTR)(_bstr_t)v ar);
lpOtherNo = temp;
}
}
m_rs->Close();
m_rs.Release();
}
catch(_com_error &e)
{
DebugMsg(“查询是否是有效帐号Sql语句:%s”,sqlstr);
DebugMsg(“查询是否是有效帐号:出错信息:%s:catch(_com_error &e)”,e.ErrorMessage());
iRet = GETDATABASE_ERROR;
}
catch(…)
{
DebugMsg(“查询是否是有效帐号Sql语句:%s”,sqlstr);
DebugMsg(“查询是否是有效帐号catch(…)”);
iRet = GETDATABASE_ERROR;
}
return iRet;
/*///////////////////////////////////////////
*53。显示资源中的bmp文件
*////////////////////////////////////////////
CRect rc;
GetClientRect(rc);
CDC *pDC = GetDC();
CBitmap m_BmpUpMark;
m_BmpUpMark.LoadBitmap(IDB_BITMAP1);
BITMAP BM;
CDC MemDC;
MemDC.CreateCompatibleDC(NULL);
MemDC.SelectObject(&m_BmpUpMark);
m_BmpUpMark.GetObject(sizeof(BM),&BM);
// 前两个参数是起始位置,
pDC->StretchBlt(0,0,rc.Width(),rc.Height(),&Mem DC,0,0,
BM.bmWidth,BM.bmHeight,SRCCOPY);
/*///////////////////////////////////////////
*54。查找文件在不在
*////////////////////////////////////////////
CFileFind f;
BOOL bResult = f.FindFile(“c:\\1.txt”);
if(f.FindFile(“c:\\1.txt”))
{
MessageBox(“找到”);
}
/*///////////////////////////////////////////
*55。打印机方向
*////////////////////////////////////////////
//***************************************************
// 重载后的打印流程 *
//***************************************************
//第一步
BOOL CPrintView::OnPreparePrinting(CPrintInfo* pInfo)
{
TRACE(“STEP1\n”);
if(pInfo->m_bPreview==FALSE)MultiPrint.bPrintEnd=FALSE;//打印开始标志
m_bRealPrint=TRUE; //打印流程,允许调用绘图代码
try{PrintInit();} //调用打印查询,不必要,为容错
catch(…){TRACE(“调用PrintInit()出错\n”);}
SwitchHOrV(); //横向,纵向,页面尺寸
//DoPreParePrinting(pInfo)函数显示PRINT公共对话框,并把得到的
//用户选择放到pInfo指向的结构中,供OnBeginPrinting(…)使用.
//pInfo->m_pPD->m_pd.Flags|=PD_USEDEVMODECOPIESA NDCOLLATE;
//还要确定打引机驱动程序是否支持打印多份
BOOL Result=DoPreparePrinting(pInfo);
if((pInfo->m_bPreview==FALSE)&&(Result==FAL SE))
{
//进入打印对话框后按了<取消>键
if(BatchPrint.bIsBatchPrint==FALSE)
{
//批量打印不能在中间阶段清空缓冲区
PrintInterface.ClearBuffer();//清空缓冲区
}
m_bRealPrint=FALSE;//禁用绘图代码
}
return Result;
}
//第二步
void CPrintView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo)
{
if(MultiPrint.bHorVer==TRUE)
{
//横向打印(直接更改设备环境描述,有待评价)
LPDEVMODE lpDevMode=(LPDEVMODE)::GlobalLock(pInfo->m_pPD->m_pd.h DevMode);
lpDevMode->dmOrientation=2;
pDC->ResetDC(lpDevMode);
::GlobalUnlock(pInfo->m_pPD->m_pd.hDevMode );
}
else
{
//纵向打印
LPDEVMODE lpDevMode=(LPDEVMODE)::GlobalLock(pInfo->m_pPD->m_pd.h DevMode);
lpDevMode->dmOrientation=1;
pDC->ResetDC(lpDevMode);
::GlobalUnlock(pInfo->m_pPD->m_pd.hDevMode );
}
//pInfo->SetMinPage()和pInfo->SetMaxPage()用于设定合法的
//文档页下限(默认为1)和上限(默认为65535).
pInfo->SetMinPage(pInfo->GetFromPage()>=Multi Print.nMaxPageToPrint?
MultiPrint.nMaxPageToPrint:pInfo->GetFromPage());//设定文档页下限
pInfo->SetMaxPage(pInfo->GetToPage()>=MultiPr int.nMaxPageToPrint?
MultiPrint.nMaxPageToPrint:pInfo->GetToPage());//设定文档页上限
CScrollView::OnBeginPrinting(pDC,pInfo);
}
//打印循环开始
//第三步
void CPrintView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
/*///////////////////////////////////////////
*56。根据版本不同,显示不同提示
*////////////////////////////////////////////
按钮中加入
#ifdef _DEBUG
ShowMessage(“debug”);
#else
ShowMessage(“release”);
#endif
/*///////////////////////////////////////////
*57。clistctrl 带checked
*////////////////////////////////////////////
CImageList* pImage = new CImageList;
HICON hIcon;
// pImage->Create( IDR_IMAGE, 16, 2, ::GetSysColor(COLOR_WINDOW) );
pImage->Create(18,18,ILC_COLOR16,2,1);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON1);
pImage->Add(hIcon);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON2);
pImage->Add(hIcon);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON3);
pImage->Add(hIcon);
hIcon=AfxGetApp()->LoadIcon(IDI_ICON4);
pImage->Add(hIcon);
m_listctrl.SetImageList(pImage,1);
LONG IStyle;
IStyle=GetWindowLong(m_listctrl.m_hWnd,GWL_STYLE); //获取当前窗口类型
IStyle&=~LVS_TYPEMASK; //清除显示方式
IStyle|=LVS_SINGLESEL|LVS_REPORT; //设置显示方式
SetWindowLong(m_listctrl.m_hWnd,GWL_STYLE,IStyle); //设置窗口类型
m_listctrl.SetExtendedStyle(LVS_EX_CHECKBOXES|LVS_EX_F ULLROWSELECT);
//设置行为选中
m_listctrl.SetItemState(行数,0×2000, LVIS_STATEIMAGEMASK);
//判断是否为选中状态
if(m_listctrl.GetItemState(行数,LVIS_STATEIMAGEMASK)==0×2000)
MessageBox(“选中了!”);
/*///////////////////////////////////////////
*58。得到含有进程的完整的命令行名 .可以得到参数 如: “d:\vcexe\vcexe.exe” /start
*////////////////////////////////////////////
AfxMessageBox(GetCommandLine());
/*///////////////////////////////////////////
*59。调CB写的DLL 一定要用__stdcall 来修饰
*////////////////////////////////////////////
UpdateData(true);
char chBuff[] = “我是文龙!”;
typedef void(_stdcall *MSGBOX)(char *pch);
HINSTANCE hinstDLL=NULL;
hinstDLL=LoadLibrary(“Project1.dll”);
if (hinstDLL)
{
MSGBOX MsgBox;
MsgBox = (MSGBOX)GetProcAddress (hinstDLL,”MsgBox”);
MsgBox(chBuff);
FreeLibrary(hinstDLL);
}
else
{
AfxMessageBox(“没找到dll”);
}
//CB中代码
//新建一个Unit.h
#define CONVDLLAPI __declspec(dllexport)
//extern “C” __declspec(dllexport) __stdcall void MsgBox(char *pch);
extern “C”
{
CONVDLLAPI __stdcall void MsgBox(char *pch);
}
//Unit.cpp
void __stdcall MsgBox(char *pch)
{
ShowMessage(pch);
}
/*///////////////////////////////////////////
*60。SDI中去掉菜单中的子项
*////////////////////////////////////////////
CMenu* pMenu = NULL;
try
{
pMenu = GetMenu()->GetSubMenu(2);
CString str;
UINT iFlag = pMenu->GetMenuState(ID_VIEW_TOOLBAR,MF_BYCOMMAND); //得到状态
switch(iFlag)
{
case MF_CHECKED:// Acts as a toggle with MF_UNCHECKED to place the default check mark next to the item. When the application supplies check-mark bitmaps (see the SetMenuItemBitmaps member function), the “check mark on” bitmap is displayed.
MessageBox(“MF_CHECKED”);
break;
case MF_DISABLED:// Disables the menu item so that it cannot be selected but does not dim it.
MessageBox(“MF_DISABLED”);
break;
case MF_ENABLED: // Enables the menu item so that it can be selected and restores it from its dimmed state. Note that the value of this constant is 0; an application should not test against 0 for failure when using this value.
MessageBox(“MF_ENABLED”);
break;
case MF_GRAYED: // Disables the menu item so that it cannot be selected and dims it.
MessageBox(“MF_GRAYED”);
break;
case MF_MENUBARBREAK: // Places the item on a new line in static menus or in a new column in pop-up menus. The new pop-up menu column will be separated from the old column by a vertical dividing line.
MessageBox(“MF_MENUBARBREAK”);
break;
case MF_MENUBREAK: // Places the item on a new line in static menus or in a new column in pop-up menus. No dividing line is placed between the columns.
MessageBox(“MF_MENUBREAK”);
break;
case MF_SEPARATOR: // Draws a horizontal dividing line. Can only be used in a pop-up menu. This line cannot be dimmed, disabled, or highlighted. Other parameters are ignored.
MessageBox(“MF_SEPARATOR”);
break;
default:
MessageBox(“others”);
}
pMenu->GetMenuString(ID_VIEW_TOOLBAR,str,MF_BYCOMMAND);//得到文本
pMenu->RemoveMenu(0,MF_BYPOSITION );//移去菜单项, 0表示序号
if(str.IsEmpty())
MessageBox(“is null”);
else
MessageBox(str);
TRACE(“\r\n%s\r\n”,str);
}
catch(…)
{
MessageBox(“error”);
}
CMenu* mmenu = GetMenu();
CMenu* submenu = mmenu->GetSubMenu(2);
UINT setStatus = (submenu->GetMenuState(IDM_TEMPCHECK,MF_BYCOMMAND) == 11 ? MF_UNCHECKED:MF_CHECKED);
UINT I = submenu->CheckMenuItem(IDM_TEMPCHECK,setStatus);
/*///////////////////////////////////////////
*61。系统菜单操作,让窗体最前方
*////////////////////////////////////////////
CMainFrame::OnCreate()中加入
DockControlBar(&m_wndToolBar);
//下方加入
CMenu* pSysMenu = GetSystemMenu(FALSE);
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, WM_ALWAYSONTOP,
“&Always On Top”);
加入WM_SYSCOMMAND消息
void CMainFrame::OnSysCommand(UINT nID, LPARAM lParam)
{
// TODO: Add your message handler code here and/or call default
switch ( nID )
{
case WM_ALWAYSONTOP:
if ( GetExStyle() & WS_EX_TOPMOST )
{
SetWindowPos(&wndNoTopMost, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE);
GetSystemMenu(FALSE)->CheckMenuItem(WM_ALWAYSONTOP,
MF_UNCHECKED);
}
else
{
SetWindowPos(&wndTopMost, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE);
GetSystemMenu(FALSE)->CheckMenuItem(WM_ALWAYSONTOP,MF_CHE CKED);
}
break;
default:
CFrameWnd::OnSysCommand(nID, lParam);
}
}
/*///////////////////////////////////////////
*62。在VC中所见即所得打印的简易实现
*////////////////////////////////////////////
void CPrintSameView::OnPrepareDC
(CDC* pDC, CPrintInfo* pInfo)
{
CView::OnPrepareDC(pDC, pInfo);
pDC->SetMapMode(MM_ANISOTROPIC); //转换坐标映射方式
CSize size = CSize(800, 560);
pDC->SetWindowExt(size); //确定窗口大小
//得到实际设备每逻辑英寸的象素数量
int xLogPixPerInch = pDC- >GetDeviceCaps(LOGPIXELSX);
int yLogPixPerInch = pDC- >GetDeviceCaps(LOGPIXELSY);
//得到设备坐标和逻辑坐标的比例
long xExt = (long)size.cx * xLogPixPerInch/96 ;
long yExt = (long)size.cy * yLogPixPerInch/96 ;
pDC->SetViewportExt((int)xExt, (int)yExt);
//确定视口大小
}
/*///////////////////////////////////////////
*63。FILE 操作文件
*////////////////////////////////////////////
int InvoiceDetailStore(struct InvoicePrint *pInvoicePrint)
{
int len;
FILE * fp;
WORD InvoicePrintCount;
if (pInvoicePrint==NULL)
return 0;
fp=fopen(“tax0000.dat”,”r+b”);
if (fp==NULL)
{
fp = fopen(“tax0000.dat”,”wb”);
if (fp==NULL)
return 0;
InvoicePrintCount = 1;
len = fwrite(&InvoicePrintCount,sizeof(WORD),1,fp);
len += fwrite(pInvoicePrint,INVOICEPRINT_SIZE,1,fp);
fclose(fp);
return len;
}
fseek(fp,0,SEEK_END);
int i = ftell(fp);
InvoicePrintCount = (WORD)(ftell(fp)/INVOICEPRINT_SIZE);
if (InvoicePrintCount<INVOICEPRINT_MAXCOUNT)
{
fseek(fp,0,SEEK_END);
len = fwrite(pInvoicePrint,INVOICEPRINT_SIZE,1,fp);
fseek(fp,0,SEEK_SET);
InvoicePrintCount++;
len += fwrite(&InvoicePrintCount,sizeof(WORD),1,fp);
}
else
{
fseek(fp,0,SEEK_SET);
len = fread(&InvoicePrintCount,sizeof(WORD),1,fp);
InvoicePrintCount %= INVOICEPRINT_MAXCOUNT;
fseek(fp,2+(long)InvoicePrintCount*INVOICEPRINT_ SIZE,SEEK_SET);
len = fwrite(pInvoicePrint,INVOICEPRINT_SIZE,1,fp);
fseek(fp,0,SEEK_SET);
InvoicePrintCount++;
len += fwrite(&InvoicePrintCount,sizeof(WORD),1,fp);
}
fclose(fp);
return len;
}
/*///////////////////////////////////////////
*64。C定义数据类型
*////////////////////////////////////////////
typedef unsigned short WORD;
typedef unsigned char BYTE;
typedef unsigned long DWORD;
/*///////////////////////////////////////////
*65。随机数
*////////////////////////////////////////////
srand(time(NULL));//种子,先运行一下
rand() //取随机数
/*///////////////////////////////////////////
*66。发送鼠标点击消息
*////////////////////////////////////////////
CWnd *m_MainWnd = FindWindow( NULL,”1111″);
int xx = 50,yy = 50;
LPPOINT lpPoint = new CPoint();
lpPoint->x = xx;
lpPoint->y = yy;
::ClientToScreen(m_MainWnd->m_hWnd,lpPoint);
LPARAM lParam = MAKELPARAM(xx,yy);//鼠标点击的坐标
::SendMessage(m_MainWnd->m_hWnd,WM_LBUTTONDOWN,MK_LBUTTON,lParam);//发送鼠标DOWN的消息
::SendMessage(m_MainWnd->m_hWnd,WM_LBUTTONUP,MK_LBUTTON,lParam);//发送鼠标UP的消
/*///////////////////////////////////////////
*67。压缩日志
*////////////////////////////////////////////
AnsiString SQLStr = “BACKUP LOG ConCard_fuzhu WITH TRUNCATE_ONLY DBCC SHRINKFILE (‘ConCard_FuZhu_Log’, 50)”;
ADOQuery3->Close();
ADOQuery3->SQL->Clear();
ADOQuery3->SQL->Add(SQLStr);
try
{ ADOQuery3->ExecSQL();
WriteLog(“压缩日志成功”);
}
catch(…)
{
WriteLog(“压缩日志不成功”);
}
/*///////////////////////////////////////////
*68。如何指定对话框的默认按钮
*////////////////////////////////////////////
当建立一个对话框的时候,在默认条件下,确定按钮(IDOK)是默认按钮,如果需要改变默认的按钮有两种方法:
其一: 直接在确定按钮(IDOK)的属性里去掉Default button风格的选项
其二: 在运行的时候用代码实现,如:
//去掉确定按钮(IDOK)的默认按钮
CButton *pokbutton = (CButton *)GetDlgItem(IDOK);
Pokbutton->ModifyStyle(BS_DEFPUSHBUTTON,0);
//添加IDCANCEL的默认按钮风格
CButton *pcancelbutton = (CButton *)GetDlgItem(IDCANCEL);
pcancelbutton->SetButtonStyle(BS_DEFPUSHBUTTON);
/*///////////////////////////////////////////
*69。进程的操作 注入 进程ID 取窗口句柄
*////////////////////////////////////////////
详见 E:\vc\dll\dll注入exe\dll
有详细说明
1: 得到系统时间日期(使用GetLocalTime)
CString sTime,sYear,sMonth,sDay;
SYSTEMTIME CurTime;
GetLocalTime(&CurTime);
sYear.Format(“%d年”,CurTime.wYear);
sMonth.Format(“%d月”,CurTime.wMonth);
sDay.Format(“%d日”,CurTime.wDay);
sTime = sYear+ sMonth + sDay;
// CurTime.wHour
// CurTime.wMinute
// CurTime.wSecond IBM的
AfxMessageBox(sTime);
2: 分离字串
CString str = “4d3f0a2278″;
unsigned char a[12];
long x;
for(int i = 0;i< (str.GetLength()/2);i++)
{
sscanf(str.Mid(2*i,2),”%x”,&x);
a = x;
}
3: 得到当前目录 (GetCurrentDirectory)
char CurPath[MAX_PATH];
DWORD size=MAX_PATH;
GetCurrentDirectory(size,CurPath);
AfxMessageBox(CurPath);
//
CString number;
int len = LineLength(LineIndex(0));
LPTSTR p=number.GetBuffer(len);
this->GetLine(0,p,len);
AfxMessageBox(number);
得到系统目录 (GetSystemDirectory)
4: 从字符串中提取数字
CString strNum;
CString str(“测试125各国87kk”);
strNum = GetStr(str);
AfxMessageBox(strNum);
5: 创建无模对话框
CDlg_Test *aa = new CDlg_Test;
aa->Create(IDD_DIALOG1,NULL);
aa->ShowWindow(SW_SHOW);
6: 得到窗口绝对坐标
CString strNum,strNum1;
CRect rect;
GetClientRect(&rect);
ClientToScreen(&rect);
strNum.Format(“X: %d”,rect.top);
strNum1.Format(“ Y: %d”,rect.left);
strNum = strNum + strNum1;
AfxMessageBox(strNum);
7: 复制文件夹
SHFILEOPSTRUCT Op;
char FromBuf[]=”E:\\temp\0″;
char ToBuf[]=”\\\\SINTEKSERVER\\个人文档\\陈 伟\0″;;
Op.hwnd = NULL;
Op.wFunc = FO_COPY;
Op.pFrom = FromBuf;
Op.pTo = ToBuf;
Op.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION ;
Op.fAnyOperationsAborted = FALSE;
Op.hNameMappings = NULL;
Op.lpszProgressTitle = NULL;
if(SHFileOperation(&Op) == 0)
MessageBox(“复制完毕”,”提示”,MB_OK|MB_ICONINFORMATION);
8: 捕获 Ctrl+鼠标左键 组合
LRESULT CGfdsaDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
switch(message)
{
case WM_LBUTTONDOWN://????wParam ==
if (wParam & MK_CONTROL)
AfxMessageBox(“bbb”);
break;
}
return CDialog::WindowProc(message, wParam, lParam);
}
或
case WM_LBUTTONDOWN:
if(GetKeyState(VK_CONTROL)<0)
MessageBox(hwnd,”aaa”,”bbb”,MB_OK);
break;
>> 本文固定链接: http://www.vcgood.com/archives/572
写得好多。。
呵呵,都是一点一点赚下来的,