VC編程小技巧

來源:互聯網
上載者:User

1. 如何擷取系統日期

CTime tm = CTime :: GetCurrentTime();

CString strTime = tm.Format(_TEXT(“%Y-%M-%d %H:%M:%S));

MessageBox(strTime);

2 動態分配二維數組

int **array;

array = new int*[col];

if(array = = 0) exit(-1);

for(int i=0; i
array[i] = new int[row];

if(array[i] = = 0)

exit(-1); }

//釋放

for(i=0; i
del ete [] array[i]; }

del ete [] array;

3. 如何定義一個二維字串數組

① ch ar **str = “abcdef” ; //一維

② ch ar *str[row][col]={“abc”, “cdf”, “efg”…..}; //row×col個

4. 將一個十六進位”FF”、”FA”等字串數組等轉化為十進位數組

int array[32][32];

int a,b, n=0;

int result1;

ch ar *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”); }

將這個矩陣數組在螢幕上顯示:

#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

//將從位元影像資訊頭得到的映像寬度和高度顯示出來

ch ar buffer1[20], buffer2[20];

_itoa( width, buffer1, 10);

_itoa( height, buffer2, 10);

ch ar str[80];

strcpy(str, “width=”);

strcat(str, buffer1);

strcat(str, “, hight=”;

strcat(str, buffer2);

AfxMesageBox(str, MB_OK, 0);

6. 當把二維數組地址用作參數傳遞,而又要此地址不斷遞增時,可以另外定義一個同類型指標,指向二維數組第一個元素的地址,把這個賦值放在迴圈外:

unsigned ch ar *p;

p = &m_pImage[0][0];

然後在迴圈中,可以p + m_count*4096;

7. 改變最近開啟文檔的個數

在InitInstance()中的LoadStdProfileSetting(8); //括弧裡是要設定的個數

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. 設定文本顯示的一些函數

CDC dc(this);

CPen pen(PS_SOLID, 2, #0000ff); //初始化一支筆

CBrush *pBush = CBrush :: FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));

dc.se lectObject(pBrush);

dc.SetTextColor(RGB(255,0 ,255));

dc.SetBKMode(TRANSPARENT); //將文本背景設定為透明

12. 將對話方塊中的映像拷貝到剪貼簿

CWnd* pWnd = GetDlgItem(IDC_IMAGE_se lect);

WINDOWPLACEMENT *winPlacement;

WinPlacement = new WINDOWPLACEMENT;

pWnd -> GetWindowPlacement(winPlacement); //獲得一個控制項的位置

CDC *dcTemp;

dcTemp= new CClientDC(FromHandle(m_hWnd));

CDC memDC;

memDC.CreateCompatibleDC(dcTemp); //建立一個相容的DC

CBitmap bm;

CSize sz(lWidth, lHeight);

bm.CreateCompatilbleBitmap(dcTemp, sz.cx, sz.cy); //建立一個相容的位元影像

CBitmap* oldbm = memDC.se lectObject(&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);

del ete dcTemp;

13. VC裡擷取一個檔案夾路徑

BROWSEINFO bi;

Tch ar szDisplayName[MAX_PATH];

LPITEMIDLIST pidl;

LPMALLOC pMalloc = NULL;

ZeroMemory(&bi, sizeof(bi));

bi.hWndOwner = GetSafeHwnd();

bih.pszDisplayName = szDisplayName;

bi.lpszTitle = TEXT(“Please se lect a folder:”);

bi.ulFlags = BIF_RETURNONLYFSDIRS;

Pidl = SHBrowseForFolder(&bi);

if(pidl) {

SHGetPathFromIDList(pidl, szDisplayName);

sPath = szDisplayName;

MessageBox(sPath); }

14. 如何設定密碼輸入時顯示的是*號

#i nclude

#i nclude

ch ar a[8];

void main() {

int i=0;

Cout<<”請輸入密碼:”<
while(1) {

a[i] = getch();

if( i>=8 || a[i]= = 13)

break;

putch(‘*’);

i++; }

cout<
getch(); }

15. 設定菜單:可以使用CMenu:: EnableMenuItem()來設定菜單可用或禁用,但是在MFC中,要使該函數起作用,需要將CWnd :: m_bAutomenuEnable設定為FALSE.

16. 關閉子視窗

:: SendMessage(:: AfxGetMainWnd() -> m_hWnd, WM_COMMAND, ID_FILE_CLOSE,0);

擷取主視窗的指標 CWinThread :: m_pMainWnd

調用AfxGetMainWnd()可實現

繼續上面的總結~! 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函數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. 如何確定頂層菜單所佔據的菜單行數:首先,計算主視窗的高度和客戶區高度;其次,從主框視窗的高度中減去客戶區、框邊界以及標題的高度;最後,除以功能表列的高度

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_se lectDOK(ID_TOOL_ZOOM, Onse lectZoomed)

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. 怎樣改變進度條控制項的顏色,發送訊息

m_progress.SendMessage(PBM_SETBKCOLOR, 0, #ff0000); //背景色

m_progress.SendMessage(PBM_SETBARCOLOR, 0, #00ff00); //前景色彩

12. 定義ch ar num[10];

sprintf(num, “%d”, calnum); //格式化數字

ch ar unit[]=”矩形”;

sprintf(num, “%s”, unit); //格式化字串

13. 改變字串的顯示字型和大小

CFont font;

font.CreatePointFont(300, “華文行楷”,NULL);

CFont *pOldFont=dc.se lectObject(&font);

dc.se lectObject(pOldFont);

14. 將路徑中的單’"’變為’""’

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
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控制項響應斷行符號鍵:利用擷取訊息來完成,調用虛函數

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(#a0b4dc, #ff0000); //後面是字型顏色

18. 讓指定的矩形框重畫 InvalidateRect(&rect, TRUE);

19. 怎樣選擇所選的List當前位置

int iTem;

POSITION pos=m_findCtrl.GetFirstse lectedItemPosition();

if(pos = = 0) {

MessageBox(“請選擇需要刪除的記錄”);

return; }

else {

iTem = m_findCtrl.GetNextse lectedItem(pos); }

//刪除List中的某行

m_findCtrl.del eteItem(iTem);

m_findCtrl.Update(iTem);

20. 動態建立控制項

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(#00c8c8); //設定背景顏色

m_list->SetTextBkColor(#00c8c8); //設定文本背景顏色

m_list->ModifyStyle(LVS_OWNERDRAWFIXED,0L);

m_list->SetExtendedStyle(LVS_EX_FULLROWSELET //整行選中

| LVS_EX_HEADERDARGDROP //允許整列拖動

| LVS_EX_GRIDLINES //畫出網格線

| LVS_EX_FLATSB); // 扁平風格的捲軸

22. 取得當前獲得焦點的視窗控制代碼

HWND hwnd = ::GetFocus();

int iID = :: GetDlgCtrlID(hwnd); // 根據控制代碼取得其資源符號

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));

//範例程式碼:假設對話方塊上有一個按鈕,當點擊按鈕時,開始啟動第二個線程,等到第

//二個線程完成後,我們再繼續主線程:

void CMyTestDialog :: OnButton1() {

m_pUpdateThread = AfxBeginThread(UpdateDeviceContent, (LPVOID)this);

if(m_pUpdateThread) {

WaitForThreadToTerminate(m_pUpdateThread->m_hThread); }

//這裡可以加入自己的執行代碼

Do whatever you want after the action is finished. }

2. 改變列表框表頭的顏色和字型,發送一個HDM_GETITEM訊息

void CHeaderCtrlEx :: DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) {

ASSERT(lpDrawItemStruct ->ctlType = =ODT_HEADER);

HDITEM hdi;

Tch ar 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, #ffff00);

:: DrawText(lpDrawItemStruct->hdc, lpBuffer, strlen(lpBuffer), &lpDrawItemStruct->rcItem, DT_SINGLELINE | DT_VCENTER | DT_CENTER);

:: SetTextColor(lpDrawItemStruct->hdc, crOldColor); }

3. 修改標題列中“無標題-title”

① 修改“無標題”部分,重載文檔中的虛函數SetTitle,加入:

CDocument:: SetTitle(”your title”);

② 修改後半部分:將字串資源中的IDR_MAIN修改為

我的程式"n"nChange"n"n"nChangeTitle.Document"nChange Document

或者:在程式的任何地方調用如下語句:

(AfxGetMainWnd()) -> SetWindowText(“your title”);

③ 除去標題中間的”-“,可以通過重載CFramWnd類的OnUpdateTitle函數,這個函數在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函數中修改的視窗風格:

BOOL CMain :: PreCreateWindow(CREATESTRUCT &cs) {

cs.style &= ~ (LONG)FWS_ADDTOTITLE;

return CWnd :: PreCreateWindow(cs); }

//使用此方法,視窗的標題只顯示IDR_MAIN字串中第一個"n之前的部分。

((CMainFram*)AfxGetMainWnd())->SetWindowText("****"); 放在App類的InitInstance()函數裡面

4. co nst的一些用法

int a=0;

co nst int* b=&a; [1] int co nst *b=&a;[2] co nst int* co nst b=&a; [3]

co nst ch ar *p=”co nst”; [1] ch ar co nst *p=”co nst”; [2] ch ar co nst p=”co nst”; [4]

co nst ch ar* co nst p=”co nst”; [4]

int a=0;

co nst int &b=a; [1] int co nst &b=a; [2] int & co nst b=a; [3] co nst int & co nst b=a; [4]

① 如果co nst位於星號左側,則co nst用來修改指標所指向的變數,即指標指向的為不可變的;

② 如果co nst位於星號右側,co nst就是修飾指標本身,即指標本身是不可變的;

③ [3]中指標本身是不可變的,而指標所指向的內容是可變的,這種情況下不能對指標本身變更操作,如b++是錯誤的;

④ [4]中指標本身和指向的內容均為常量

5. co nst作為參數用法

void fun0( co nst A *a) 在函數體中,按照co nst所修飾的部分進行常量化,如形參為co nst A* a,則不能對傳遞進來的指標的內容進行改變,保護了原指標所指向的內容;

void fun1(co nst A& a) 形參為co nst A& a,則不能對傳遞進來的引用對象進行改變,保護了原對象的屬性。[註:參數co nst通常用於參數為指標或引用的情況]

co nst修飾傳回值: co nst A fun2(); co nst A* fun3()

一般用co nst修飾傳回值為對象本身(非引用和指標)的情況多用於二目操作符重載函數,併產生新的對象的時候。

[總結]: 一般情況下,函數的傳回值為某個對象時,如果將其聲明為co nst時,多用於操作符的重載。通常,不建議用co nst修飾函數的傳回值類型為某個對象或對某個對象引用的情況。

6. 類成員函數中co nst的使用:一般放在函數體後void fun() co nst; 如果一個成員函數不會修改資料成員,那麼最好將其聲明為co nst,因為co nst成員函數中不允許對資料成員進行修改,如果修改,編譯器會報錯,大大提高了程式的健壯性。

轉自:http://blog.gongkong.com/blog_detail.Asp?Id=371300

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.