1. 如何獲取系統(tǒng)日期
CTime tm = CTime :: GetCurrentTime();
CString strTime = tm.Format(_TEXT(“%Y-%M-%d %H:%M:%S));
MessageBox(strTime);
2. 動態(tài)分配二維數(shù)組
int **array;
array = new int*[col];
if(array = = 0) exit(-1);
for(int i=0; i<col; i++){
array[i] = new int[row];
if(array[i] = = 0)
exit(-1); }
//釋放
for(i=0; i<col; i++){
delete [] array[i]; }
delete [] array;
3. 如何定義一個二維字符串數(shù)組
① char **str = “abcdef” ; //一維
② char *str[row][col]={“abc”, “cdf”, “efg”…..}; //row×col個
4. 將一個十六進制”FF”、”FA”等字符串數(shù)組等轉化為十進制數(shù)組
int array[32][32];
int a,b, n=0;
int result1;
char *str;
for(int i=0; i<32; i++)
for(int j=0; j<32; j++){
str = str[i][j];
if(str[0] >= ‘A’ && str[1] >=’A’){ //”AF”
a = str[0] – ‘A’;
b= str[1] – ‘A’;
result1 = (a+10)*16+(b+10)*1;}
else if(str[0] >= ‘A’ && str[1] <’A’){ //”A9”
a = str[0] – ‘A’;
b = ‘A’ – str[1] +1;
result1 = (a+10)*16+b;}
else if(str[0] < ‘A’ && str[1] >=’A’){ //”8B”
a = ‘A’ – str[0]+1;
b = str[1] – ‘A’;
result1 = a*16+(b+10)*1;}
else{ //”87”
a = ‘A’ – str[0]+1;
b = ‘A’ – str[1] +1;
result1 = a*16+b;}
array[i][j] = reslut1;
printf(“%5d”, array[i][j]);
n++;
if(n%32 = = 0) printf(“\n”); }
將這個矩陣數(shù)組在屏幕上顯示:
#i nclude < afxwin.h >
#i nclude < afxext.h >
#i nclude < afxdisp.h >
#i nclude < afxdtctl.h >
DWORD color_;
HDC hMyDC = GetDC(NULL);
for(i=0; i<32; i++)
for(j=0; j<32; j++){
color_ = array[i][j];
color_ = color_*256*256 + color_*256+color_;
SetPixel(hMyDC, j, i, color_); }
5. 將一個整型轉化為一個字符串 _itoa
//將從位圖信息頭得到的圖像寬度和高度顯示出來
char buffer1[20], buffer2[20];
_itoa( width, buffer1, 10);
_itoa( height, buffer2, 10);
char str[80];
strcpy(str, “width=”);
strcat(str, buffer1);
strcat(str, “, hight=”;
strcat(str, buffer2);
AfxMesageBox(str, MB_OK, 0);
6. 當把二維數(shù)組地址用作參數(shù)傳遞,而又要此地址不斷遞增時,可以另外定義一個同類型指針,指向二維數(shù)組第一個元素的地址,把這個賦值放在循環(huán)外:
unsigned char *p;
p = &m_pImage[0][0];
然后在循環(huán)中,可以p + m_count*4096;
7. 改變最近打開文檔的個數(shù)
在InitInstance()中的LoadStdProfileSetting(8); //括號里是要設置的個數(shù)
8. 打開調色板對話框
CColorDialog dlg;
dlg.Domodal();
9. 如何添加工具欄,如何使用Slider?
在OnInitDialog()中添加:
CSliderCtrl *pSliderCtrl=(CSliderCtrl*)GetDlgItem(IDC_SLIDER1);
pSliderCtrl -> SetRange(0,255,TRUE); //設置滑動條的范圍
pSliderCtrl -> SetPos(100); // 設置滑動條的初始位置
在Dlg類中響應WM_HSCROLL消息:
CSliderCtrl *pSliderCtrl=(CSliderCtrl*)GetDlgItem(IDC_SLIDER1);
m_nCur = pSliderCtrl - >GetPos(); //獲得當前的位置值
10. 更改光標
:: SetCursor(:: LoadCursor(NULL, IDC_SIZEALL));
//如果是自己定義的光標資源,則要用MAKEINTRESOURCE 進行轉化,例如:
:: SetCursor(:: LoadCursor(NULL, IDC_CURSOR_CUT));
11. 設置文本顯示的一些函數(shù)
CDC dc(this);
CPen pen(PS_SOLID, 2, RGB(0,0,255)); //初始化一支筆
CBrush *pBush = CBrush :: FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));
dc.SelectObject(pBrush);
dc.SetTextColor(RGB(255,0 ,255));
dc.SetBKMode(TRANSPARENT); //將文本背景設置為透明
12. 將對話框中的圖像拷貝到剪貼板
CWnd* pWnd = GetDlgItem(IDC_IMAGE_SELECT);
WINDOWPLACEMENT *winPlacement;
WinPlacement = new WINDOWPLACEMENT;
pWnd -> GetWindowPlacement(winPlacement); //獲得一個控件的位置
CDC *dcTemp;
dcTemp= new CClientDC(FromHandle(m_hWnd));
CDC memDC;
memDC.CreateCompatibleDC(dcTemp); //創(chuàng)建一個兼容的DC
CBitmap bm;
CSize sz(lWidth, lHeight);
bm.CreateCompatilbleBitmap(dcTemp, sz.cx, sz.cy); //創(chuàng)建一個兼容的位圖
CBitmap* oldbm = memDC.SelectObject(&bm);
memDC.BitBlt(0, 0, sz.cx, sz.cy, dcTemp, winPlacement ->rcNormalPosition.left,
winPlacement ->rcNormalPosition.top, SRCCOPY);
pWnd -> OpenClipboard(); //打開剪貼板,不用pWnd->GetParent()->OpenClipard();
:: EmptyClipard();
:: SetClipardData(CF_BITMAP, bm.m_hObject); //粘貼到剪貼板
CloseClipard();
memDC.SelcetObject(oldbm);
delete dcTemp;
13. VC里獲取一個文件夾路徑
BROWSEINFO bi;
TCHAR szDisplayName[MAX_PATH];
LPITEMIDLIST pidl;
LPMALLOC pMalloc = NULL;
ZeroMemory(&bi, sizeof(bi));
bi.hWndOwner = GetSafeHwnd();
bih.pszDisplayName = szDisplayName;
bi.lpszTitle = TEXT(“Please select a folder:”);
bi.ulFlags = BIF_RETURNONLYFSDIRS;
Pidl = SHBrowseForFolder(&bi);
if(pidl) {
SHGetPathFromIDList(pidl, szDisplayName);
sPath = szDisplayName;
MessageBox(sPath); }
14. 如何設置密碼輸入時顯示的是*號
#i nclude <iostream.h>
#i nclude <conio.h>
char a[8];
void main() {
int i=0;
Cout<<”請輸入密碼:”<<endl;
while(1) {
a[i] = getch();
if( i>=8 || a[i]= = 13)
break;
putch(‘*’);
i++; }
cout<<endl<<a<<endl;
getch(); }
15. 設置菜單:可以使用CMenu:: EnableMenuItem()來設置菜單可用或禁用,但是在MFC中,要使該函數(shù)起作用,需要將CWnd :: m_bAutomenuEnable設置為FALSE.
16. 關閉子窗口
:: SendMessage(:: AfxGetMainWnd() -> m_hWnd, WM_COMMAND, ID_FILE_CLOSE,0);
獲取主窗口的指針 CWinThread :: m_pMainWnd
調用AfxGetMainWnd()可實現(xiàn)
繼續(xù)上面的總結~! To making it count~!。。。。。。
1. 獲取CMain類的指針
CMain* pApp = ((CMain*)AfxGetApp()->m_pMainWnd);
ASSERT_KINDOF(CMain, pAPP); //確保pAPP是CMain的類對象
2. VC++如何獲取應用程序的實例句柄
實例句柄保存在CWinApp m_hInstance中
HANDLE hInstance = AfxGetInstanceHandle();
3. VC++怎樣加載其他的應用程序 三個SDK函數(shù)WinExec, ShellExecute, CreateProcess.
① WinExec最簡單,前一個指定路徑,后一個指定顯示方式;
② ShellExecute(null, null, _T(“1.txt”), NULL, _T(“c:\\temp”), SW_SHOWNORMAL);
③ STARTUPINFO stinfo; //啟動窗口的信息
PROCESSINFO proinfo; //進程的信息
CreateProcess(NULL,_T(“notepad.exe)”,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,NULL,&stinfo,&proinfo);
4. 如何確定頂層菜單所占據(jù)的菜單行數(shù):首先,計算主窗口的高度和客戶區(qū)高度;其次,從主框窗口的高度中減去客戶區(qū)、框邊界以及標題的高度;最后,除以菜單欄的高度
CRect rc, rcClient;
GetWindowRect(rc);
GetClientRect(rcClient);
Int menuHeight;
menuHeight = (rc.Height() – rcClicent.Height()–
::GetSystemMetrics(SM_CYCAPTION) – :: GetSystemMetrics(SM_CY)*2))
- / :: GetSystemMetrics(SM_CYMENU) ;
5. 響應下拉菜單的消息為
ON_CBN_SELECTDOK(ID_TOOL_ZOOM, OnSelectZoomed)
6. 設置工具欄的標題
m_wndTestBar.SetWindowText(“your toolbar title”);
7. 如何獲得應用程序主窗口的指針
CWnd pMainWnd = AfxGetApp() ->m_pMainWnd;
CMain *pMain = ((CMain*)pMainWnd;
CRect rect;
CWnd* pParent = AfxGetApp()->GetMainWnd();
pParent ->GetWindowRect(&rect); //得到應用程序窗口矩形
//移到窗口
pParent -> MoveWindow(rect.left, rect.top, rect.Width()+1,rect.Height()+1,TRUE);
8. 獲得獲得子窗口
CMDIChildWnd* pChild = (CMDIChildWnd*)GetActive();
//或:CMDIChildWnd* pChild=MDIGetActive();
9. 獲得活動子窗口的活動視圖
CMyView* pView = (CMyView*)pChild->GetActiveView();
獲取當前窗口的指針
CWnd :: GetForegoundWindow();
10. 從句柄轉換到指針
HWND hwnd;
hwnd = :: FindWindow(NULL, “TEST”);
CWnd* pWnd = FromHandle(hwnd);
11. 怎樣改變進度條控件的顏色,發(fā)送消息
m_progress.SendMessage(PBM_SETBKCOLOR, 0, RGB(255,0,0)); //背景色
m_progress.SendMessage(PBM_SETBARCOLOR, 0, RGB(0,255,0)); //前景色
12. 定義char num[10];
sprintf(num, “%d”, calnum); //格式化數(shù)字
char unit[]=”矩形”;
sprintf(num, “%s”, unit); //格式化字符串
13. 改變字符串的顯示字體和大小
CFont font;
font.CreatePointFont(300, “華文行楷”,NULL);
CFont *pOldFont=dc.SelectObject(&font);
dc.SelectObject(pOldFont);
14. 將路徑中的單’\’變?yōu)?/span>’\\’
CMyDoc *pDoc=GetDocument();
CString reportPath = pDoc -> strPathName;
int lentemp = reportPath.GetLength();
reportPath = reportPath.Left(lentemp-4);
int lenpath = reportPath.GetLength();
for(int i=0; i<lenpath-1; ) {
if(reportpath.GetAt(i) = = ‘\\’) {
reportpath.Insert(i, ‘\\’);
i+=2; }
i++; }
15. 獲取屏幕分辨率
HDC hSrcDC;
hSrcDC = ::GetDC(AfxGetApp() -> m_pMainWnd->GetSafeHwnd());
int xSrc, ySrc;
xSrc = GetDeviceCaps(hSrcDC, HORIRES); //水平分辨率
ySrc = GetDeviceCaps(hSrcDC, VERTRES); //垂直分辨率
16. 讓Edit控件響應回車鍵:利用獲取消息來完成,調用虛函數(shù)
PreTranslateMessage(MSG* pMsg) {
If( pMsg ->message = = WM_KEYDOWN) {
switch(pMsg -> wParam) {
case VK_RETURN:
GetDlgItem(IDC_BTN_INPUT)->SendMessage(BM_CLICK, 0, 0);
return TRUE; } } }
17. 改變對話框的背景色:在InitInstance()中加入
SetDialogBKColor(RGB(160, 180, 220), RGB(255, 0, 0)); //后面是字體顏色
18. 讓指定的矩形框重畫 InvalidateRect(&rect, TRUE);
19. 怎樣選擇所選的List當前位置
int iTem;
POSITION pos=m_findCtrl.GetFirstSelectedItemPosition();
if(pos = = 0) {
MessageBox(“請選擇需要刪除的記錄”);
return; }
else {
iTem = m_findCtrl.GetNextSelectedItem(pos); }
//刪除List中的某行
m_findCtrl.DeleteItem(iTem);
m_findCtrl.Update(iTem);
20. 動態(tài)創(chuàng)建控件
CEdit m_edit;
CRect rect(0,0,100,200);
M_edit.Create(WS_CHILD | ES_AUTOHCROLL | WS_BORDER, rect, this, ID_EDIT_1);
21. 列表控件的應用
CListCtrl* m_list;
CRect rect_list;
this->GetCientRect(&rect_list);
rect_list.top + =100;
m_list -> Create(WS_CHILD | LVS_REPORT | WS_BORDER | LVS_SINGLESEL, rect_list, this, ID_TABLIST);
this ->m_list->ModifyStyle(LVS_EDITABELS,0L); //禁止標題編輯
m_list->ModifyStyle(0L ,LVS_REPORT); //設置為Report類型
m_list->ModifyStyle(0L, LVS_SHOWSELALWAYS); //始終高亮顯示被選中的表項
m_list->ModifyStyle(0L,LVS_NOSORTHEADER); //禁止標題編輯
m_list->SetBkColor(RGB(0,200,200)); //設置背景顏色
m_list->SetTextBkColor(RGB(0,200,200)); //設置文本背景顏色
m_list->ModifyStyle(LVS_OWNERDRAWFIXED,0L);
m_list->SetExtendedStyle(LVS_EX_FULLROWSELET //整行選中
| LVS_EX_HEADERDARGDROP //允許整列拖動
| LVS_EX_GRIDLINES //畫出網(wǎng)格線
| LVS_EX_FLATSB); // 扁平風格的滾動條
22. 取得當前獲得焦點的窗口句柄
HWND hwnd = ::GetFocus();
int iID = :: GetDlgCtrlID(hwnd); // 根據(jù)句柄取得其資源符號
23. 修改控件的字體
CFont m_font;
m_font.CreateFont(-12,0,0,0,400,FALSE,FALSE,0,GB2312_SHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, VARIABLE_PITCH | FF_, “楷體_GB2312”);
//為想改變字體的控件改變
m_editPh.SetFont(&m_font, true);
1. 如何暫停主線程直到第二個線程的終止?
void CMyTestDialog ::PeekMessageLoop() {
MSG msg;
while ( PeekMessage(&msg, NULL, NULL, NULL, NULL,NULL, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg); } }
Void CMyTestDialog :: WaitForThreadToTerminate( HANDLE hThread) {
//將指示哪個線程需要等待并作進一步處理
DWORD dwRet;
Do {
dwRet = :: MsgWaitForMultipleObject(1, &hThread, FALSE, INFINITE, QS_ALLINPUT);
if(dwRef != WAIT_OBJET_0) {
PeekMessageLoop(); }
}while ( (dwRet != WAIT_OBJET_0) && (dwRet != WAIT_FAILED));
//示例代碼:假設對話框上有一個按鈕,當點擊按鈕時,開始啟動第二個線程,等到第
//二個線程完成后,我們再繼續(xù)主線程:
void CMyTestDialog :: OnButton1() {
m_pUpdateThread = AfxBeginThread(UpdateDeviceContent, (LPVOID)this);
if(m_pUpdateThread) {
WaitForThreadToTerminate(m_pUpdateThread->m_hThread); }
//這里可以加入自己的執(zhí)行代碼
Do whatever you want after the action is finished. }
2. 改變列表框表頭的顏色和字體,發(fā)送一個HDM_GETITEM消息
void CHeaderCtrlEx :: DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) {
ASSERT(lpDrawItemStruct ->ctlType = =ODT_HEADER);
HDITEM hdi;
TCHAR lpBuffer[256];
Hdi.mask = HDI_TEXT;
Hdi.pszText = lpBuffer;
Hdi.uhTextMax = 256;
GetItem(lpDrawItemStruct->itemID,&hdi);
//畫按鈕框
:: DrawControl(lpDrawItemStruct->hdc, &lpDrawItemStruct->rcItem, DFC_BUTTOON, DFCS_BUTTONPUSH);
COLORREF crOldColor = :: SetTextColor(lpDrawItemStruct->hdc, RGB(255,255,0));
:: DrawText(lpDrawItemStruct->hdc, lpBuffer, strlen(lpBuffer), &lpDrawItemStruct->rcItem, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
:: SetTextColor(lpDrawItemStruct->hdc, crOldColor); }
3. 修改標題欄中“無標題-title”
① 修改“無標題”部分,重載文檔中的虛函數(shù)SetTitle,加入:
CDocument:: SetTitle(”your title”);
② 修改后半部分:將字符串資源中的IDR_MAIN修改為
我的程序\n\nChange\n\n\nChangeTitle.Document\nChange Document
或者:在程序的任何地方調用如下語句:
(AfxGetMainWnd()) -> SetWindowText(“your title”);
③ 除去標題中間的”-“,可以通過重載CFramWnd類的OnUpdateTitle函數(shù),這個函數(shù)在VC提供的幫助文件中找不到,必須手工添加:
virtual void OnUpdateTitle(BOOL NaDa);
void CMain :: OnUpdateTitle(BOOL NaDa) {
CString csAppName;
csAppName.Format(AFX_IDS_APP_TITLE);
SetWindowText(csAppName); }
//此時顯示的結果只有字符串資源AFX_IDS_APP_TITLE 所定義的字符串
★ 另一種方法是在CMain的PreCreateWindow函數(shù)中修改的窗口風格:
BOOL CMain :: PreCreateWindow(CREATESTRUCT &cs) {
cs.style &= ~ (LONG)FWS_ADDTOTITLE;
return CWnd :: PreCreateWindow(cs); }
//使用此方法,窗口的標題只顯示IDR_MAIN字符串中第一個\n之前的部分。
4. const的一些用法
int a=0;
const int* b=&a; [1] int const *b=&a;[2] const int* const b=&a; [3]
const char *p=”const”; [1] char const *p=”const”; [2] char const p=”const”; [4]
const char* const p=”const”; [4]
int a=0;
const int &b=a; [1] int const &b=a; [2] int & const b=a; [3] const int & const b=a; [4]
① 如果const位于星號左側,則const用來修改指針所指向的變量,即指針指向的為不可變的;
② 如果const位于星號右側,const就是修飾指針本身,即指針本身是不可變的;
③ [3]中指針本身是不可變的,而指針所指向的內容是可變的,這種情況下不能對指針本身進行更改操作,如b++是錯誤的;
④ [4]中指針本身和指向的內容均為常量
5. const作為參數(shù)用法
void fun0( const A *a) 在函數(shù)體中,按照const所修飾的部分進行常量化,如形參為const A* a,則不能對傳遞進來的指針的內容進行改變,保護了原指針所指向的內容;
void fun1(const A& a) 形參為const A& a,則不能對傳遞進來的引用對象進行改變,保護了原對象的屬性。[注:參數(shù)const通常用于參數(shù)為指針或引用的情況]
const修飾返回值: const A fun2(); const A* fun3()
一般用const修飾返回值為對象本身(非引用和指針)的情況多用于二目操作符重載函數(shù),并產(chǎn)生新的對象的時候。
[總結]: 一般情況下,函數(shù)的返回值為某個對象時,如果將其聲明為const時,多用于操作符的重載。通常,不建議用const修飾函數(shù)的返回值類型為某個對象或對某個對象引用的情況。
6. 類成員函數(shù)中const的使用:一般放在函數(shù)體后void fun() const; 如果一個成員函數(shù)不會修改數(shù)據(jù)成員,那么最好將其聲明為const,因為const成員函數(shù)中不允許對數(shù)據(jù)成員進行修改,如果修改,編譯器會報錯,大大提高了程序的健壯性。
7. 使用const的一些suggestioins:
① 要大膽地使用const,這將給你帶來無盡的益處,但前提是你必須搞清楚原委;
② 在參數(shù)中使用const應使用引用或指針,而不是一般的對象實例;
③ 要避免最一般的賦值操作錯誤,如將const變量賦值;
④ 不要輕易地將函數(shù)的返回類型定為cosnt;
⑤ 除了重載操作符外一般不要將返回值類型定為某個對象的const引用
8. 讓應用程序只運行一個實例: 在App的InitInstance添加如下代碼:
HANDLE hSem = CreateSemaphore(NULL, 1, 1, m_pszAppName);
if(GetLastError() = = ERROR_ALREADY_EXISTS) { //信號量存在,則有一個在運行
CloseHandle(hSem); //關閉信號量句柄
// 尋找先前的實例窗口
HWND hWndPrevious = ::GetWindow(::GetDesktopWindow(), GW_CHILD);
While(:: IsWindow(hWndPrevious)) { //檢查窗口是否有預設的標記
if(::GetProp(hWndPrevious,m_pszAppName)) { //有,則尋找主窗口
if(:: IsIconic(hWndPrevious)) { //窗口最小化,則恢復其大小
::SetForegroundWindow(hWndPrevious); //將主窗口激活
::SetForgoundWindow(::GetLastActivePopup(hWndPrevious));
//將主窗口激活
::ShowWindow(hWndPrevious, SW_NORMAL);
reurn FALSE; } //退出本實例
hWndPrevious = :: GetWindow(hWndPrevious, GW_HWNDNEXT); //繼續(xù)找 }
AfxMessageBox(“only one application program can run!”);
return FALSE; } }
1.獲取本機的IP地址
#i nclude <stdio.h>
#i nclude <winsock2.h>
#pragma comment (lib, “ws2_32.lib”)
Void CheckIP() {
WSADATA wsadata;
Char name[155];
Char *ip;
PHOSTENT hostinfo;
If (WSAStartUp( MAKEWORD(2,0), &wsadate) = = 0) {
If ( gethostname( name, sizeof(name)) = = 0) {
If((hostinfo = gethostbyname(name)) != NULL) {//獲得IP的函數(shù)
Ip = inet_ntoa(*(struct in_addr*)*hostinfo -> h_addr_list);
Printf*”%s\n”, ip); } }
WSACleanup(); } }
2. CWnd:: SetDlgItemInt(); 被對話框設定一個由字符串表示的整型值。
CSemaphore ---à CSyncObject------àCObject
在一個進程或多個進程中允許訪問一種資源的允許線程數(shù),CSemaphore對象維持當前獲取一種指定資源的線程個數(shù)。當計數(shù)大于0時,Semaphore對象的狀態(tài)是有信號狀態(tài);典型應用是用Semaphore去限制使用一種資源的線程個數(shù)。用WaitforSingleObject等待有信號狀態(tài),返回時則減少對Semaphore的計數(shù)。
3. 得到計算機所有驅動函數(shù)GetAllDriverList()
CString tmp = _T(“A:\\”), dir;
for(int i=1; i<=25; i++) {
dir = CString(‘A’+i)+ _T(“:\\”);
if(GetDriveType(dir.GetBuffer(0)) = = DRIVE_NO_ROOT_DIR) continue;
tmp += “;” + dir; }
return tmp;
4. 打開對話框,選擇文件路徑函數(shù) OnBrowse()
BROWSEINFO bi;
char dispname[MAX_PATH], path[MAX_PATH];
ITEMIDLIST *pidl;
bi.hwndOwner = m_hWnd;
bi.pidlRoot = 0;
bi.pszDisplayName = dispname;
bi.ulFlags = BIF_RETUREONLYFSDIRS | BIF_EDITBOX | BIF_DONTGOBELOWDOMAIN;
bi.lpfn = 0;
bi.lParam = 0;
bi.iImage = 0;
if(pidl = SHBrowseForFolder(&bi)) { //顯示一個使用用戶可以選擇的文件打開對話框
SHGetPathFromIDList(pidl, path); //把一個item identifier list轉化為一個文件系統(tǒng)路徑
m_folder = CString(path);
if(m_folder.IsEmpty() ) m_folder = GetAllDirverList();
UpdateData(FALSE); }
SHGetFileInfo(); 返回文件系統(tǒng)中對象的信息,比如文件、folder、路徑、驅動器
5. 如何使用CImageList
CImageList m_iImageList;
m_iImageList.Create(24,24,TRUE,1,0);
HICON hIcon = NULL;
hIcon = (HICON)::LoadImage(::AfxGetInstanceHandle(), MAKEINTRESOURCE(IDI_KEBIAO0, IMAGE_ICON,24,24,0);
m_iImageList.Add(hIcon);
m_FileTree.SetImageList(&m_iImageList, TVSIL_NORMAL); //m_FileTree為TreeList控件
//或者這樣來創(chuàng)建:
m_imageList.DeleteImageList();
m_image.Create(16,16,ILC_COLORDDB,1,100);
m_listCtrl.SetImageList(&m_iImageList, LVSIL_SMALL);
6. 遍歷一個文件夾的文件
OnFindFile(WPARAM wParam, LPARAM lParam) {
CString strFilePath = *((CString*)wParam);
if(strFilePath.Right(1) != “\\”) {
strFilePath +=”\\”; }
strFilePath += “*.*”;
CFileFind finder;
CString strFileName;
BOOL isHave = finder.FindFile(strFilePath);
while(isHave) {
isHave = finder.FindNextFile();
if(!finder.IsDirectory() && !finder.IsDots()) {
strFileName = finder.GetFilePath();
:: PostMessage((HWND)(GetMainWnd()->GetSafeHWnd()), WM_DISPLAY, (WPARAM)&strFileName, NULL); } }
finder.Close(); }
7. 如何來啟動這個查找線程
新建一個類派生于CWinThread;CFindFileThread *pFindFileThread;
pFindFileThread = (CFindFileThread*)AfxBeginThread(RUNTIME_CLASS(CFindFileThread);
pFindFileThread -> PostThreadMessage(WM_FINDFILE, (WPARAM)&strFilePath,NULL);
8. 找到一個則發(fā)送消息WM_DISPLAY,并把文件中全路徑作為參數(shù)返回
獲取一個文件的信息 OnDisplay(WPARAM wParam, LPARAM lParam) {
count++; //統(tǒng)計文件個數(shù)
CString strFileName = *((CString*)wParam);
CFileStatus status;
C: GetStatus(strFileName, status);
CString unit = “Byte”;
float flen = (float)status.m_size;
if(flen>1024) {
flen /= 1024;
if(flen < 1024) unit = “KB”;
else {
flen /= 1024;
unit = “MB”; } }
CString size;
size.Format(“%1.2f”, flen);
int pos = strFileName.ReverseFind(‘\\’);
SHFILEINFO sfi; //文件信息結構體
if(:: SHGetFileInfo(strFileName, FILE_ATTRIBUTE_NORMAL, &sfi,
Sizeof(SHFILEINFO), SHGFI_USEFILEATTRIBUTES |
SHGFI_DISPLAYNAME | SHGFI_TYPENAME | SHGFI_ICON
| SHGFI_SMALLICON)) {
m_imgList.Add(sfi.hIcon);
m_filelist.InsertItem(count-1, sfi.szDisplayName, count-1);
m_filelist.SetItemText(count-1, 1, strFileName, Mid(0,pos));
m_filelist.SetItemText(count-1, 2, (size+unit));
m_filelist.SetItemText(count-1, 3, sfi.szTypeName); }
m_filelist.Update(count-1); }
9. 在圖片中隱藏信息的做法:加社會圖片文件為c:\s.jpg, 文字為d:\w.txt, 在命令行方式窗口中輸入命令 COPY /B C:\s.jpg + d:\w.txt c:\d.jpg
10. 獲得應用程序所在路徑
char szCurPath[_MAX_PATH];
HINSTANCE hInst = NULL;
GetMoudleFileName( hInst, szCurPath, _MAX_PATH); //獲得應用程序所在路徑
char *p = szCurPath;
while( strchr(p, ‘\\’)) {
p= strchr( p, ‘\\’);
p++; }
*p = ‘\0’;
ShellExecute(NULL, NULL, _T(“Your.exe”), NULL, _T(szCurPath), SW_SHOWNORMAL);
總結問題的解決方法,有助于獲得更多的實戰(zhàn)經(jīng)驗,不斷地積累,在編程方面就會有長足的進步~!
學習的過程是一個不斷積累的過程,只有學習的時間累積到一定的程度,才能發(fā)生質的提高。。。
posted on 2008-08-28 16:48
聶文龍 閱讀(1096)
評論(0) 編輯 收藏 引用 所屬分類:
Visual C++