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