c++学习笔记

1、控件随窗口大小而自动缩放

void CDVRDlg::OnSize(UINT nType, int cx, int cy)
{
RECT rcClient;
if (GetDlgItem(IDC_STATIC_aa))
{
GetClientRect(&rcClient);
rcClient.left+=10;
rcClient.right-=10;
rcClient.top+=10;
rcClient.bottom-=10;
GetDlgItem(IDC_STATIC_aa)->MoveWindow(&rcClient);
}
}

2、CButtonST

Short shBtnColor = 30;
m_bGogo.SetIcon(IDI_HALLOWEEN2, IDI_HALLOWEEN1);//设置按钮图标
m_bGogo.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, shBtnColor);//设置按钮亮度
m_bGogo.DrawBorder(FALSE);//设置按钮边框
m_bGogo.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 128, 0));//设置按钮字体颜色
m_bGogo.SetAlign(CButtonST::ST_ALIGN_HORIZ_RIGHT);//设置按钮图标位置
m_bGogo.DrawFlatFocus(TRUE);//设置虚线框

// HyperLink button
m_btnHyperLink.SetIcon(IDI_WEB2);
m_btnHyperLink.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, shBtnColor);
m_btnHyperLink.SetURL(IDS_WEBADDR);
m_btnHyperLink.SetTooltipText(IDS_WEBADDR);
m_btnHyperLink.SetBtnCursor(IDC_HAND2);

3、解析字符串
CString a = "aaa,sss,ddd,fff";
CString b[100000];
int bb = 0;
for ( int i=0; i<a.GetLength(); i++ )
if ( a[i]==',' )
{
bb ++;
}
else
{
b[bb] = b[bb] + a[i];
}

4、取得本地IP
char name[255];
CString ip;
PHOSTENT hostinfo;
if(gethostname ( name, sizeof(name)) == 0)
{
//如果能够获取计算机主机信息的话,则获取本机IP地址
if ((hostinfo = gethostbyname(name)) != NULL)
{
//获取本机IP地址
LPCSTR ip=inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
//输出IP地址
AfxMessageBox(ip);
}
}

5、类似CTabCtrl的CPropertySheet

m_PropertySheet.AddPage(&page1);
m_PropertySheet.AddPage(&page2);

//m_PropertySheet.SetActivePage(&page2);
m_PropertySheet.Create(this, WS_CHILD | WS_VISIBLE, 0); //创建非摸态

的属性表
m_PropertySheet.ModifyStyleEx (0, WS_EX_CONTROLPARENT); // 当对话框

搜索下一 个Tab项时,WS_EX_CONTROLPARENT标记避免了死循环发生的可

能性,他可以让对话框搜索到属性表中的子窗体控件,就象对话框窗体上的其他普通控件一样
m_PropertySheet.ModifyStyle( 0, WS_TABSTOP ); //允许用户TAB键切换到属性表


CRect rcRect;
GetWindowRect(&rcRect);
m_PropertySheet.MoveWindow(rcRect);

6、不要一次发那么大,分成1K大小,循环发送,检查每次发送的返回值
#define SOCK_BUF 1024
DWORD dwSend = 0;
DWORD dwToSend = 0;
while(dwSend < dwDataLen)
{
dwToSend = dwDataLen - dwSend;
if(dwToSend > SOCK_BUF) dwToSend = SOCK_BUF;
int nRet = m_pSockMsg->Send(pDataBuf + dwSend,dwToSend);
if(nRet == SOCKET_ERROR)
{
DWORD dwError = GetLastError();
CString str;
str.Format("发送错误,错误代码:%d",dwError);
AfxMessageBox(str);
break;
}
dwSend += nRet;
}

7、工具条图标
// Set up hot bar p_w_picpath lists.
CImageList p_w_picpathList;
CBitmap bitmap;

// Create and set the normal toolbar p_w_picpath list.
bitmap.LoadBitmap(IDB_TOOLBAR);
p_w_picpathList.Create(29, 29, ILC_COLORDDB|ILC_MASK, 13, 1);
p_w_picpathList.Add(&bitmap, RGB(255,0,255));
m_wndToolBar.SendMessage(TB_SETIMAGELIST, 0, (LPARAM)p_w_picpathList.m_hImageList);
p_w_picpathList.Detach();
bitmap.Detach();

// Create and set the hot toolbar p_w_picpath list.
bitmap.LoadBitmap(IDB_TOOLBARHOT);
p_w_picpathList.Create(29, 29, ILC_COLORDDB|ILC_MASK, 13, 1);
p_w_picpathList.Add(&bitmap, RGB(255,0,255));
m_wndToolBar.SendMessage(TB_SETHOTIMAGELIST, 0, (LPARAM)p_w_picpathList.m_hImageList);
p_w_picpathList.Detach();
bitmap.Detach();

// Create and set the hot toolbar p_w_picpath list.
bitmap.LoadBitmap(IDB_TOOLBARDISABLE);
p_w_picpathList.Create(29, 29, ILC_COLORDDB|ILC_MASK, 13, 1);
p_w_picpathList.Add(&bitmap, RGB(255,0,255));
m_wndToolBar.SendMessage(TB_SETDISABLEDIMAGELIST, 0, (LPARAM)p_w_picpathList.m_hImageList);
p_w_picpathList.Detach();
bitmap.Detach();

8、bmp位图
1位 2种颜色
2位 4种颜色
4位 16种颜色
8位 256种颜色
16位 65536种颜色
24位 1677万种颜色
32位 1677万种颜色和256级灰度值
36位 687亿种颜色和4096级灰度值

9、贴图
m_bmpBackground.LoadBitmap(IDB_MAINWND);
BITMAP bmp;
if (m_bmpBackground.GetBitmap(&bmp))
{
SIZE sizeWnd = {bmp.bmWidth, bmp.bmHeight};
sizeWnd.cx += GetSystemMetrics(SM_CXBORDER) * 2;
sizeWnd.cy += GetSystemMetrics(SM_CYBORDER) * 2 + GetSystemMetrics(SM_CYCAPTION);

SetWindowPos(NULL, 0, 0, sizeWnd.cx, sizeWnd.cy, SWP_NOMOVE | SWP_NOZORDER);
CenterWindow();
}


10、//-----------返回符合条件的记录总数----------------------------
int CTreeDataDlg::TreeSumRecordCount(CString strFieldValue)
{
int Sum=0;
//----------------使用到的变量进行定义----------
_RecordsetPtr m_pRecordset; //用于创建一个查询记录集
//----------------------------------------------
CString strSQL,strCurItem;
//-----------------------------------------------
strSQL="SELECT * FROM TreeItem where ParentItem like '%" ;
strSQL=strSQL+strFieldValue+"%'";
try
{
HRESULT hTRes;
hTRes = m_pRecordset.CreateInstance(_T("ADODB.Recordset"));
if (SUCCEEDED(hTRes))
{
//----------------------------------------------------
hTRes = m_pRecordset->Open((LPTSTR)strSQL.GetBuffer(130),
_variant_t((IDispatch

*)(((CTreeDataApp*)AfxGetApp())->m_pTreeConn),true),
adOpenDynamic,adLockPessimistic,adCmdText);
if(SUCCEEDED(hTRes))
{
TRACE(_T("连接成功!\n"));
//------------------------------------------
if(!m_pRecordset->BOF )
{
m_pRecordset->MoveFirst ();
while(!m_pRecordset->adoEOF)
{
Sum+=1;
m_pRecordset->MoveNext ();
}
}
//---------------------------------------
}
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
MessageBox("求符合条件的记录总数出错!",strFieldValue);
}
return Sum;
}

11、递归树
void CTreeDataDlg::TreeAddSubTree(CString ParTree, HTREEITEM hPartItem)
{
//----------------使用到的变量进行定义----------
_RecordsetPtr m_pTreeRecordset; //用于创建一个查询记录集
_variant_t vChild;
//--------------Tree控件操作变量------------------------
HTREEITEM hCurrent;
//----------------------------------------------
CString strSQL,strCurItem;
//-----------------------------------------------
strSQL="SELECT * FROM TreeItem where ParentItem like '%" ;
strSQL=strSQL+ParTree+"%'";
try
{
HRESULT hTRes;
hTRes = m_pTreeRecordset.CreateInstance(_T("ADODB.Recordset"));
if (SUCCEEDED(hTRes))
{
//----------------------------------------------------
hTRes = m_pTreeRecordset->Open((LPTSTR)strSQL.GetBuffer(130),
_variant_t((IDispatch

*)(((CTreeDataApp*)AfxGetApp())->m_pTreeConn),true),
adOpenDynamic,adLockPessimistic,adCmdText);
if(SUCCEEDED(hTRes))
{
TRACE(_T("连接成功!\n"));
//------------------------------------------
m_pTreeRecordset->MoveFirst();
if (!(m_pTreeRecordset->adoEOF))
{

while(!m_pTreeRecordset->adoEOF)
{
hCurrent =

m_ctrlTree.InsertItem((LPCTSTR)(_bstr_t)\
(m_pTreeRecordset->GetCollect("Name")),

hPartItem, NULL);
if (TreeSumRecordCount(VariantToCString\

(m_pTreeRecordset->GetCollect("Name")))>0)
{//递归

TreeAddSubTree(VariantToCString(m_pTreeRecordset->GetCollect("Name")),
hCurrent);
}

if (!(m_pTreeRecordset->adoEOF))
{
m_pTreeRecordset->MoveNext();
}
}
}
//---------------------------------------
}
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
MessageBox("创建City记录集失败!",ParTree);
}
}

12、CListCtrl

m_p_w_picpathlist.Create(16,16,TRUE,2,2);
m_p_w_picpathlist.Add(AfxGetApp()->LoadIcon(IDI_ICON1));
m_p_w_picpathlist.Add(AfxGetApp()->LoadIcon(IDR_MAINFRAME));
m_list.SetImageList(&m_p_w_picpathlist,LVSIL_SMALL);


m_font.CreateFont(16, 0,0,0,FW_NORMAL, 0,0,0,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial");
m_list.SetFont(&m_font);


/*-----------------------------------------------------------*/
m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
m_list.SetBkColor(RGB(247,247,255));
m_list.SetTextColor(RGB(0,0,255));
m_list.SetTextBkColor(RGB(247,247,255));
m_list.InsertColumn(0, "学号", LVCFMT_LEFT, 110);
m_list.InsertColumn(1, "姓名", LVCFMT_LEFT, 130);
m_list.InsertColumn(2, "成绩", LVCFMT_LEFT, 47);

m_list.InsertItem(0,"2002112105");
m_list.SetItemText(0,1,"程红秀");
m_list.SetItemText(0,2,"96");

//////////////////////////////////////////////////////////////////////////////////////
得到List索引
//////////////////////////////////////////////////////////////////////////////////////

OnDblclkList(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
POSITION pos = m_list.GetFirstSelectedItemPosition();
m_nIndex = m_list.GetNextSelectedItem(pos); // 得到项目索引

CString a = m_list.GetItemText(m_nIndex,0);
CString b = m_list.GetItemText(m_nIndex,1);
CString c = m_list.GetItemText(m_nIndex,2);
}
//////////////////////////////////////////////////////////////////////////////////////
保存成文本
//////////////////////////////////////////////////////////////////////////////////////
void CListCtrlDlg::OnButtonSave()
{
// TODO: Add your control notification handler code here
CStdioFile file;
if(file.Open("record.txt",CFile::modeCreate | CFile::modeWrite))
{
CString strOut = "学号\t\t姓名\t\t成绩\r\n";
file.WriteString(strOut);
for(int i=0;i<m_list.GetItemCount();i++)
{
strOut=m_list.GetItemText(i,0) + "\t"+m_list.GetItemText(i,1)+"\t

"+m_list.GetItemText(i,2) +"\r\n";
file.WriteString(strOut);
}
file.Close();
MessageBox("保存成功!","提示",MB_ICONINFORMATION);
}
else
{
MessageBox("保存失败!","提示",MB_ICONINFORMATION);
}
}

13、程序自动启动
m_bAutoStart = !m_bAutoStart;
AfxGetApp()->WriteProfileInt(_T("User Info"), _T("AutoStart"), m_bAutoStart);

HKEY hKey;
LPCTSTR lpSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\0");
RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0L, KEY_ALL_ACCESS, &hKey);
if (m_bAutoStart)
{

TCHAR AppPathName[MAX_PATH];
GetModuleFileName(NULL, AppPathName, MAX_PATH);
LPCTSTR lpValue = AppPathName;
RegSetValueEx(hKey, _T("nsserver"), 0L, REG_SZ, (const BYTE *)lpValue, strlen(lpValue) +

1);
}
else
{
RegDeleteValue(hKey, _T("nsserver"));
}

14、新建文档视图
void CMainFrame::OnInputUnit()
{
// TODO: Add your command handler code here
m_currentwin=1;//录入
if(m_pInput!=NULL)
{
m_pInput->MDIActivate();
return;
}
m_pInput=new CRaChildFrame();
CCreateContext context;
context.m_pNewViewClass=RUNTIME_CLASS(CInputCertView);
if(!m_pInput->LoadFrame(IDI_ICON3,WS_MAXIMIZE|WS_OVERLAPPEDWINDOW,this,&context))
return;
m_pInput->ShowWindow(SW_SHOWMAXIMIZED);
m_pInput->InitialUpdateFrame(NULL,true);
}

另外一种写法
CChildFrame* pFrame = new CChildFrame();
CCreateContext context;
context.m_pCurrentDoc=mp_doc; //that's the way I avoid to create new document every time I open

a new view
context.m_pNewViewClass=RUNTIME_CLASS(CTSMLView);
context.m_pNewDocTemplate=pDocTemplate;
context.m_pLastView=(((CMainFrame *)m_pMainWnd)->GetActiveFrame() ? ((CMainFrame

*)m_pMainWnd)->GetActiveFrame()->GetActiveView() : NULL);
context.m_pCurrentFrame=((CMainFrame *)m_pMainWnd)->GetActiveFrame();
if (!pFrame->LoadFrame(IDR_TSMLTYPE,WS_OVERLAPPEDWINDOW | FWS_PREFIXTITLE ,m_pMainWnd, &context

))return;
pFrame->InitialUpdateFrame(mp_doc,TRUE);


15、只能运行一个实例

//此程序只能运行一次,用互斥量来判断程序是否已运行
HANDLE m_hMutex=CreateMutex(NULL,TRUE, m_pszAppName);
if(GetLastError()==ERROR_ALREADY_EXISTS)
{
AfxMessageBox("程序已经运行!");
return FALSE;
}

16、在多文档界面下,自动生成一个新的子窗口,而一个实际的应用系统往往
是由用户操作后再生成新的窗口。为了去掉开始的子窗口,可在应用程序文件
分析命令行的语句

  CCommandLineInfo cmdInfo;

  ParseCommandLine(cmdInfo);

  后加入:

  cmdInfo.m_nShellCommand=CCommandLineInfo::FileNothing

17、if(AfxMessageBox("真的要退出吗?",MB_YESNO)==IDYES)
{
CDialog::OnOK();
}

18、ACCESS和SQL2000日期

access表示为:#1981-28-12# date BETWEEN #2005-04-28 23:59:59# AND #2005-05-24

23:59:59#
SQLSERVER2000表示为:'1981-02-12' date BETWEEN '2005-03-21' AND '2005-05-24'

19、初始化应用程序的大小

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
int xsize=::GetSystemMetrics(SM_CXSCREEN);
int ysize=::GetSystemMetrics(SM_CYSCREEN);
cs.cx=xsize*5/10;
cs.cy=ysize*5/10;
cs.x=(xsize-cs.cx)/2;
cs.y=(ysize-cs.cy)/2;
} 其中的5/10是你的初始界面占屏幕的百分比,可以自己修改。如果想使应用程序大小固定添加

cs.style&=~WS_THICKFRAME;

20、全屏FRAME
void CTestView::ShowFullScreen()
{
CMainFrame *pFrame=(CMainFrame *)(AfxGetApp()->m_pMainWnd);
if(m_bFullScreen)
{
pFrame->ModifyStyle(0,WS_CAPTION);
pFrame->ModifyStyle(0,WS_THICKFRAME);

pFrame->ShowWindow(SW_SHOWNORMAL);
m_bFullScreen=0;
}
else
{
pFrame->ModifyStyle(WS_CAPTION,0);
pFrame->ModifyStyle(WS_THICKFRAME,0);

pFrame->ShowWindow(SW_MAXIMIZE);
m_bFullScreen=1;
}
}

21、如何在对话框中从磁盘读出一个bitmap文件画在上面?

BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
HBITMAP m_hBmp = (HBITMAP)::LoadImage(0,
"D:\\\\bitmap.bmp",
IMAGE_BITMAP,
0,
0,
LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE);
_ASSERT(m_hBmp!=NULL);
m_pBmp = CBitmap::FromHandle(m_hBmp);
return TRUE;
}

void CAboutDlg::OnPaint()
{
CPaintDC dc(this);
BITMAP bm;
CDC dcMem;
VERIFY(m_pBmp->GetObject(sizeof(bm),(LPVOID)&bm));
dcMem.CreateCompatibleDC(&dc);
CBitmap *pOldBMP=(CBitmap *)dcMem.SelectObject(m_pBmp);
BitBlt(dc.m_hDC,0, 0, bm.bmWidth, bm.bmHeight, dcMem.m_hDC, 0, 0, SRCCOPY);
dcMem.SelectObject(pOldBMP);
// Do not call CDialog::OnPaint() for painting messages
}


22、全屏显示Dialog
if(m_bFullScreen)
{
SetWindowPlacement(&m_OldWndPlacement);
}
else
{
GetWindowPlacement(&m_OldWndPlacement); //取得原始窗口位置
int nFullWidth = GetSystemMetrics(SM_CXSCREEN);
int nFullHeight = GetSystemMetrics(SM_CYSCREEN);

RECT WindowRect, ClientRect;
GetWindowRect(&WindowRect);
GetDlgItem(IDC_VIEW)->GetWindowRect(&ClientRect);

RECT FullScreenRect;
FullScreenRect.left = WindowRect.left - ClientRect.left;
FullScreenRect.top = WindowRect.top - ClientRect.top;
FullScreenRect.right = WindowRect.right - ClientRect.right + nFullWidth -

FullScreenRect.left;
FullScreenRect.bottom = WindowRect.bottom - ClientRect.bottom + nFullHeight -

FullScreenRect.top;

WINDOWPLACEMENT wndpl;
wndpl.length = sizeof(WINDOWPLACEMENT);
wndpl.flags = 0;
wndpl.showCmd = SW_SHOWNORMAL;
wndpl.rcNormalPosition = FullScreenRect;
SetWindowPlacement(&wndpl);

GetDlgItem(IDC_VIEW)->SetWindowPos(NULL, 0, 0, nFullWidth, nFullHeight, SWP_NOMOVE);
}
m_bFullScreen = !m_bFullScreen;

23、数据库连接串
//连接SQL SERVER
m_pConnection->Open("Driver=SQL

Server;Database=test;Server=127.0.0.1;UID=sa;PWD=;","","",adModeUnknown);
//连接ACCESS2000
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=userinfo.mdb","","",adModeUnknown);

24、void CDVRDlg::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos)
{
//在窗口改变之前调用的方法:窗口的最小尺寸。
//CDialog::OnWindowPosChanging(lpwndpos); //注销这句避免无法最大化窗口
if (lpwndpos->cx < 400) lpwndpos->cx = 400;
if (lpwndpos->cy < 300) lpwndpos->cy = 300;

}

this->InvalidateRect(CRect(30,y-30,150,y-20),TRUE);//重新绘制矩形,用于更新时间。

void CDVRDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
//点击鼠标响应事件
CRect changeApp_rect(77,119,41,95);

//判断是否在这个changeApp_rect区域,如果在就执行调用其它应用程序操作。
if(changeApp_rect.PtInRect(point))
{
if(AfxMessageBox("确定切换到笔录系统吗?",MB_YESNO)==IDYES)
{
WinExec("D:\\test\\Debug\\DlgSplashScr.exe",SW_SHOW);
OnClose();
}
}
}

25\
VC中常用的20种方法

一、打开CD-ROM
mciSendString("Set cdAudio door open wait",NULL,0,NULL);
二、关闭CD_ROM
mciSendString("Set cdAudio door closed wait",NULL,0,NULL);
三、关闭计算机
OSVERSIONINFO OsVersionInfo; //包含操作系统版本信息的数据结构
OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&OsVersionInfo); //获取操作系统版本信息
if(OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
//Windows98,调用ExitWindowsEx()函数重新启动计算机

DWORD dwReserved;
ExitWindowsEx(EWX_REBOOT,dwReserved); //可以改变第一个参数,实现注销用户、
//关机、关闭电源等操作
// 退出前的一些处理程序
}
四、重启计算机
typedef int (CALLBACK *SHUTDOWNDLG)(int); //显示关机对话框函数的指针
HINSTANCE hInst = LoadLibrary("shell32.dll"); //装入shell32.dll
SHUTDOWNDLG ShutDownDialog; //指向shell32.dll库中显示关机对话框函数的指针
if(hInst != NULL)
{
//获得函数的地址并调用之
ShutDownDialog = (SHUTDOWNDLG)GetProcAddress(hInst,(LPSTR)60);

(*ShutDownDialog)(0);
}
五、枚举所有字体
LOGFONT lf;
lf.lfCharSet = DEFAULT_CHARSET; // Initialize the LOGFONT structure
strcpy(lf.lfFaceName,"");
CClientDC dc (this);
// Enumerate the font families
::EnumFontFamiliesEx((HDC) dc,&lf,


(FONTENUMPROC) EnumFontFamProc,(LPARAM) this,0);
//枚举函数
int CALLBACK EnumFontFamProc(LPENUMLOGFONT lpelf,
LPNEWTEXTMETRIC lpntm,DWORD nFontType,long lparam)

{
// Create a pointer to the dialog window
CDay7Dlg* pWnd = (CDay7Dlg*) lparam;
// add the font name to the list box
pWnd ->m_ctlFontList.AddString(lpelf ->elfLogFont.lfFaceName);
// Return 1 to continue font enumeration
return 1;
}
其中m_ctlFontList是一个列表控件变量
六、一次只运行一个程序实例,如果已运行则退出
if( FindWindow(NULL,"程序标题")) exit(0);
七、得到当前鼠标所在位置
CPoint pt;
GetCursorPos(&pt); //得到位置
八、上下文菜单事件触发事件:OnContextMenu事件

九、显示和隐藏程序菜单
CWnd *pWnd=AfxGetMainWnd();
if(b_m) //隐藏菜单
{
pWnd->SetMenu(NULL);
pWnd->DrawMenuBar();
b_m=false;
}
else
{
CMenu menu;
menu.LoadMenu(IDR_MAINFRAME); ////显示菜单 也可改变菜单项
pWnd->SetMenu(&menu);
pWnd->DrawMenuBar();
b_m=true;
menu.Detach();
}
十、获取可执行文件的图标
HICON hIcon=::ExtractIcon(AfxGetInstanceHandle(),_T("NotePad.exe"),0);
if (hIcon &&hIcon!=(HICON)-1)
{
pDC->DrawIcon(10,10,hIcon);

}
DestroyIcon(hIcon);
十一、窗口自动靠边程序演示
BOOL AdjustPos(CRect* lpRect)
{//自动靠边
int iSX=GetSystemMetrics(SM_CXFULLSCREEN);
int iSY=GetSystemMetrics(SM_CYFULLSCREEN);
RECT rWorkArea;
BOOL bResult = SystemParametersInfo(SPI_GETWORKAREA, sizeof(RECT), &rWorkAre
a, 0);
CRect rcWA;
if(!bResult)
{//如果调用不成功就利用GetSystemMetrics获取屏幕面积
rcWA=CRect(0,0,iSX,iSY);
}
else
rcWA=rWorkArea;
int iX=lpRect->left;
int iY=lpRect->top;

if(iX < rcWA.left + DETASTEP && iX!=rcWA.left)
{//调整左
//pWnd->SetWindowPos(NULL,rcWA.left,iY,0,0,SWP_NOSIZE);
lpRect->OffsetRect(rcWA.left-iX,0);
AdjustPos(lpRect);
return TRUE;
}
if(iY < rcWA.top + DETASTEP && iY!=rcWA.top)
{//调整上
//pWnd->SetWindowPos(NULL ,iX,rcWA.top,0,0,SWP_NOSIZE);
lpRect->OffsetRect(0,rcWA.top-iY);
AdjustPos(lpRect);
return TRUE;
}
if(iX + lpRect->Width() > rcWA.right - DETASTEP && iX !=rcWA.right-lpRect->W

idth())
{//调整右
//pWnd->SetWindowPos(NULL ,rcWA.right-rcW.Width(),iY,0,0,SWP_NOSIZE);
lpRect->OffsetRect(rcWA.right-lpRect->right,0);
AdjustPos(lpRect);
return TRUE;
}
if(iY + lpRect->Height() > rcWA.bottom - DETASTEP && iY !=rcWA.bottom-lpRect
->Height())
{//调整下
//pWnd->SetWindowPos(NULL ,iX,rcWA.bottom-rcW.Height(),0,0,SWP_NOSIZE);
lpRect->OffsetRect(0,rcWA.bottom-lpRect->bottom);
return TRUE;
}
return FALSE;
}
//然后在ONMOVEING事件中使用所下过程调用

CRect r=*pRect;
AdjustPos(&r);
*pRect=(RECT)r;
十二、给系统菜单添加一个菜单项
给系统菜单添加一个菜单项需要进行下述三个步骤:
首先,使用Resource Symbols对话(在View菜单中选择Resource Symbols...可以显
示该对话)定义菜单项ID,该ID应大于0x0F而小于0xF000;
其次,调用CWnd::GetSystemMenu获取系统菜单的指针并调用CWnd:: Appendmenu将菜单
项添加到菜单中。下例给系统菜单添加两个新的
int CMainFrame:: OnCreate (LPCREATESTRUCT lpCreateStruct)
{

//Make sure system menu item is in the right range.

ASSERT(IDM_MYSYSITEM<0xF000);
//Get pointer to system menu.
CMenu* pSysMenu=GetSystemMenu(FALSE);
ASSERT_VALID(pSysMenu);
//Add a separator and our menu item to system menu.
CString StrMenuItem(_T ("New menu item"));
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_MYSYSITEM, StrMenuItem);

}
十三、运行其它程序
//1、运行EMAIL或网址
char szMailAddress[80];
strcpy(szMailAddress,"mailto:[email protected]");
ShellExecute(NULL, "open", szMailAddress, NULL, NULL, SW_SHOWNORMAL);

//2、运行可执行程序
WinExec("notepad.exe",SW_SHOW); //运行计事本
十四、动态增加或删除菜单
1、 增加菜单
//添加
CMenu *mainmenu;
mainmenu=AfxGetMainWnd()->GetMenu(); //得到主菜单
(mainmenu->GetSubMenu (0))->AppendMenu (MF_SEPARATOR);//添加分隔符
(mainmenu->GetSubMenu (0))->AppendMenu(MF_STRING,ID_APP_ABOUT,_T("Always on
&Top")); //添加新的菜单项
DrawMenuBar(); //重画菜单
2、 删除菜单
//删除
CMenu *mainmenu;
mainmenu=AfxGetMainWnd()->GetMenu(); //得到主菜单

CString str ;
for(int i=(mainmenu->GetSubMenu (0))->GetMenuItemCount()-1;i>=0;i--) //取得菜
单的项数。
{
(mainmenu->GetSubMenu (0))->GetMenuString(i,str,MF_BYPOSITION);
//将指定菜单项的标签拷贝到指定的缓冲区。MF_BYPOSITION的解释见上。
if(str=="Always on &Top") //如果是刚才我们增加的菜单项,则删除。
{
(mainmenu->GetSubMenu (0))->DeleteMenu(i,MF_BYPOSITION);
break;
}
十五、改变应用程序的图标
静态更改: 修改图标资源IDR_MAINFRAME。它有两个图标,一个是16*16的,另一个是3

2*32的,注意要一起修改。
动态更改: 向主窗口发送WM_SETICON消息.代码如下:
HICON hIcon=AfxGetApp()->LoadIcon(IDI_ICON);
ASSERT(hIcon);
AfxGetMainWnd()->SendMessage(WM_SETICON,TRUE,(LPARAM)hIcon);
十六、另一种改变窗口标题的方法
使用语句 CWnd* m_pCWnd = AfxGetMainWnd( ),然后,再以如下形式调用SetWindowTe
xt()函数:
SetWindowText( *m_pCWnd,(LPCTSTR)m_WindowText);// m_WindowText可以是一个CSt
ring类的变量。
十七、剪切板上通过增强元文件拷贝图像数据
下面代码拷贝通过元文件拷贝图像数据到任何应用程序,其可以放置在CView派生类的函

数中。
CMetaFileDC * m_pMetaDC = new CMetaFileDC();
m_pMetaDC->CreateEnhanced(GetDC(),NULL,NULL,"whatever");
//draw meta file
//do what ever you want to do: bitmaps, lines, text...
//close meta file dc and prepare for clipboard;
HENHMETAFILE hMF = m_pMetaDC->CloseEnhanced();
//copy to clipboard
OpenClipboard();
EmptyClipboard();
::SetClipboardData(CF_ENHMETAFILE,hMF);


CloseClipboard();

//DeleteMetaFile(hMF);
delete m_pMetaDC;
十八、剪切板上文本数据的传送
把文本放置到剪接板上:
CString source;
//put your text in source
if(OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(source));
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
从剪接板上获取文本:

char * buffer;
if(OpenClipboard())
{
buffer = (char*)GetClipboardData(CF_TEXT);
//do something with buffer here
//before it goes out of scope
}
CloseClipboard();
十九、将捕捉屏幕图像到剪切版
void CShowBmpInDlgDlg::OnCutScreen()
{
ShowWindow(SW_HIDE);
RECT r_bmp={0,0,::GetSystemMetrics(SM_CXSCREEN),
::GetSystemMetrics(SM_CYSCREEN)};


HBITMAP hBitmap;
hBitmap=CopyScreenToBitmap(&r_bmp);

//hWnd为程序窗口句柄
if (OpenClipboard())
{
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBitmap);
CloseClipboard();
}
ShowWindow(SW_SHOW);
}
HBITMAP CShowBmpInDlgDlg::CopyScreenToBitmap(LPRECT lpRect)
{
//lpRect 代表选定区域
{
HDC hScrDC, hMemDC;
// 屏幕和内存设备描述表
HBITMAP hBitmap, hOldBitmap;
// 位图句柄
int nX, nY, nX2, nY2;
// 选定区域座标
int nWidth, nHeight;
// 位图宽度和高度
int xScrn, yScrn;
// 屏幕分辨率

// 确保选定区域不为空矩形
if (IsRectEmpty(lpRect))
return NULL;
//为屏幕创建设备描述表
hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
//为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hScrDC);
// 获得选定区域座标
nX = lpRect->left;
nY = lpRect->top;
nX2 = lpRect->right;
nY2 = lpRect->bottom;
// 获得屏幕分辨率
xScrn = GetDeviceCaps(hScrDC, HORZRES);
yScrn = GetDeviceCaps(hScrDC, VERTRES);
//确保选定区域是可见的
if (nX<0)

nX = 0;
if (nY<0)
nY = 0;
if (nX2>xScrn)
nX2 = xScrn;
if (nY2>yScrn)
nY2 = yScrn;
nWidth = nX2 - nX;
nHeight = nY2 - nY;
// 创建一个与屏幕设备描述表兼容的位图
hBitmap = CreateCompatibleBitmap
(hScrDC, nWidth, nHeight);
// 把新位图选到内存设备描述表中
hOldBitmap =(HBITMAP)SelectObject(hMemDC, hBitmap);
// 把屏幕设备描述表拷贝到内存设备描述表中
BitBlt(hMemDC, 0, 0, nWidth, nHeight,
hScrDC, nX, nY, SRCCOPY);
//得到屏幕位图的句柄
hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);

//清除
DeleteDC(hScrDC);
DeleteDC(hMemDC);
// 返回位图句柄
return hBitmap;
}
}
二十、如何将位图缩放显示在Static控件中
//在Staic控件内显示位图
void CShowBmpInDlgDlg::ShowBmpInStaic()
{
CBitmap hbmp;
HBITMAP hbitmap;
//将pStatic指向要显示的地方
CStatic *pStaic;
pStaic=(CStatic*)GetDlgItem(IDC_IMAGE);
//装载资源 MM.bmp是我的一个文件名,用你的替换
hbitmap=(HBITMAP)::LoadImage (::AfxGetInstanceHandle(),"MM.bmp",
IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION);

hbmp.Attach(hbitmap);
//获取图片格式
BITMAP bm;
hbmp.GetBitmap(&bm);
CDC dcMem;
dcMem.CreateCompatibleDC(GetDC());
CBitmap *poldBitmap=(CBitmap*)dcMem.SelectObject(hbmp);
CRect lRect;
pStaic->GetClientRect(&lRect);
//显示位图
pStaic->GetDC()->StretchBlt(lRect.left ,lRect.top ,lRect.Width(),lRect.Heigh
t(),
&dcMem,0 ,0,bm.bmWidth,bm.bmHeight,SRCCOPY);
dcMem.SelectObject(&poldBitmap);
}

26、修改单文档程序的标题:
OnCreat()中加入 SetWindowText("程序标题");
CMainFrame::PreCreateWindow(CREATESTRUCT& cs)中加入 cs.style =WS_OVERLAPPEDWINDOW;
cs.style &= ~WStyle &= ~WS_THICKFRAME; //不可改变大小

27播放声音
导入 #pragma comment(lib, "Winmm")
#include "mmsystem.h"
PlaySound(MAKEINTRESOURCE(IDR_RINGIN), AfxGetResourceHandle(),
SND_ASYNC | SND_RESOURCE | SND_NODEFAULT);


28.设置窗口最前
m_pMainWnd->SetWindowPos(&m_pMainWnd->wndTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);


29.MsgWnd
void CMainFrame::OnViewMsn()
{
CMsgWnd *pMsgWindow=new CMsgWnd(IDB_SHOWMSG);
CMsgWnd& msgWindow=*pMsgWindow;
msgWindow.CreateMsgWindow();
msgWindow.ShowWindow(SW_SHOW);
msgWindow.UpdateWindow();
}


30.代码收集

VC代码收集
一、改变视图背景色:
在CView的OnDraw函数中添写如下一段程序代码:
void CFileNameView::OnDraw(CDC* pDC)
{
CFileNameDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CRect rectClient;
CBrush brushBkColor;
GetClientRect(rectClient);
brushBkColor.CreateSolidBrush(RGB(255,0,0)); //颜色设置
pDC->DPtoLP(rectClient);
pDC->FillRect(rectClient,&brushBkColor);

}
二、往基于对话框的程序添加菜单:
[1] 先添加菜单(IDR_MENU1)资源,并加上需要的菜单项。
[2] 编辑对话框资源IDD_DLGMENUTOOLBAR_DIALOG的属性,在属性对话框中选择IDR_MENU1即可。

[3] 假如您不希望在对话框属性中直接设置菜单,而通过代码在程序中动态生成可以采用如下方法:
在CFileNameDlg类声名中添加成员变量CMenu m_menu,再在CFileNameDlg::OnInitDialog() 中添加如下代码:
//加载菜单
m_menu.LoadMenu(IDR_MENU1);
//设置当前菜单
SetMenu(&m_menu);
//当你不需要菜单时可以用 SetMenu(NULL);来取消当前菜单
三、往基于Dialog的程序添加工具栏:
[1] 先添加工具栏(IDR_TOOLBAR1)资源,并画好各个按钮。
[2] 在CFileNameDlg类声名中添加成员变量 CToolBar m_wndtoolbar;
[3] 在CFileNameDlg::OnInitDialog() 中添加如下代码
//添加一个平面工具条
if (!m_wndtoolbar.CreateEx( this,TBSTYLE_FLAT , WS_CHILD | WS_VISIBLE |
CBRS_ALIGN_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS, CRect(4,4,0,0)) ||
!m_wndtoolbar.LoadToolBar(IDR_TOOLBAR1) )
{
TRACE0("failed to create toolbar\n");
return FALSE;
}
m_wndtoolbar.ShowWindow(SW_SHOW);
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);
四、改变对话框背景色:
在CDlgMenuToolbarDlg::OnPaint()中修改代码实现Dialog 填充颜色:
CPaintDC dc(this);
CRect rect;
GetClientRect(rect);
dc.FillSolidRect(rect, RGB(60,110,170));
方法二、在InitInstance()(不是OnInitDialog())中加入:
SetDialogBkColor(RGB(255,0,0),RGB(0,255,0));
注意:要放在InitInstance函数的最前面!
五、为dialog的工具栏添加工具提示:
[1] 在CFileNameDlg类定义中手工添加消息映射函数的定义,如下黑体部分
//{{AFX_MSG(CFileNameDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg BOOL OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
[2] 在CFileNameDlg.cpp添加函数的实现代码
//工具栏提示
BOOL CFileNameDlg::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
{
ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);
// UNICODE消息
TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
//TCHAR szFullText[512];
CString strTipText;
UINT nID = pNMHDR->idFrom;

if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
{
// idFrom为工具条的HWND
nID = ::GetDlgCtrlID((HWND)nID);
}

if (nID != 0) //不为分隔符
{
strTipText.LoadString(nID);
strTipText = strTipText.Mid(strTipText.Find(’\n’,0)+1);

#ifndef _UNICODE
if (pNMHDR->code == TTN_NEEDTEXTA)
{
lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText));
}
else
{
_mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
}
#else
if (pNMHDR->code == TTN_NEEDTEXTA)
{
_wcstombsz(pTTTA->szText, strTipText,sizeof(pTTTA->szText));
}
else
{
lstrcpyn(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
}
#endif
*pResult = 0;
// 使工具条提示窗口在最上面
::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,SWP_NOACTIVATE|
SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER);
return TRUE;
}
return TRUE;
}
[3] 在CFileNameDlg.cpp中添加消息映射,请看如下代码中的黑体部分
BEGIN_MESSAGE_MAP(CFileNameDlg, CDialog)
//{{AFX_MSG_MAP(CFileNameDlg)
ON_WM_PAINT()
ON_NOTIFY_EX( TTN_NEEDTEXT, 0, OnToolTipText )
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
[4] 在CFileNameDlg.h中添加声明:
BOOL CFileNameDlg::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult);
六、给没有工具栏的窗口添加工具栏:
在资源管理器中编辑工具栏,并将其属性改为IDR_MAINFRAME,然后在MainFrm.h中声明:
CToolBar m_wndToolBar;
在MainFrm.cpp中添加:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
m_wndToolBar.Create(this);
m_wndToolBar.LoadToolBar(IDR_MAINFRAME);
……;

停靠工具栏:在刚才添加的后面加入下面代码:
m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle()|CBRS_TOOLTIPS|CBRS_SIZE_DYNAMIC);

m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);//控制是否开启任意停靠
完善一下功能:
在菜单中添加一项“工具栏”,ID设为ID_VIEW_TOOLBAR,一切OK,试试吧!
七、创建分隔窗口:
只有框架类可以创建分隔,分隔可以嵌套。
在.h文件中声明 CSplitterWnd m_wndSplitter;并且包含COneView.h(新建视图类)和CWinFrame.h(新建框架类)文

件;
然后在.cpp文件中加入:
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
if(!m_wndSplitter.CreateStatic(this,1,2))
return FALSE;

if(!m_wndSplitter.CreateView(0,0,RUNTIME_CLASS(COneView),CSize(240,420),pContext))

return FALSE;

if(!m_wndSplitter.CreateView(0,1,RUNTIME_CLASS(CWinFrame),CSize(300,500),pContext))

return FALSE;
return TRUE;
}
当用户创建好分割窗口后,有时并不希望通过拖动切分条来调节窗口的大小。这时就必须锁定切分条。锁定切分条的最

简单的方法莫过于不让CSplitterWnd来处理WM_LBUTTONDOWN,WM_MOUSEMOVE,WM_SETCURSOR消息,而是将这些消息交给

CWnd窗口进行处理,从而屏蔽掉这些消息。拿WM_LBUTTONDOWN处理过程来说。修改为如下:

void CXXSplitterWnd::OnLButtonDown(UINT nFlags,CPoint point)
{
CWnd::OnLButtonDown(nFlags,point);
}
其余的处理方法类似。
八、“打开”按钮的设置:
用类向导创建该按钮的click函数,选择默认值OnOpen,加入以下代码:
void CYourDlg::OnOpen()
{
char szFileFilter[]=
"BIN File(*.bin)|*.bin|"
"All File(*.*)|*.*||";//文件类型过滤
CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY,szFileFilter);
/* CFileDialog dlg(FALSE);
dlg.m_ofn .lpstrFilter =_T("文本文件(*.txt)*.txt所有文件(*.*)*.*");
dlg.m_ofn.lpstrDefExt=_T("txt"); */
if(dlg.DoModal()==IDOK)
{
m_path = dlg.GetPathName();//将显示路径的Edit控件命名为m_path,并增加CString变量m_path
UpdateData(FALSE);
}
}
九、窗口居中:
在初始化(OnInit)函数中增加:CenterWindow();即可
十、对话框加状态条:
UINT indicators[]={ID_INITMESSAGE,ID_SEPARATOR,ID_TIMEMESSAGE,ID_PROGRESS};
m_statusbar.CreateEx(this,0,WS_CHILD | WS_VISIBLE | CBRS_BOTTOM);
m_statusbar.SetIndicators(indicators,4);
m_statusbar.ShowWindow (SW_SHOW);
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);
十一、设置初始窗口状态:
BOOL CObjectNameApp::InitInstance()
{
m_pMainWnd->SetWindowText(""); //设置初始窗口标题文本
m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED);//设置初始窗口为最大化
m_pMainWnd->UpdateWindow();

对于MDI函数SetWindowText无效,主窗口的标题只能在资源列表中修改,子窗口标题在**doc.cpp中重载OnNewDocument

(),调用SetTitle("LGdownload中文版");来修改。

设置初始窗口最大化的另一优化方法:
void CMainFrame::ActivateFrame(int nCmdShow)
{
// TODO: Add your specialized code here and/or call the base class
nCmdShow=SW_MAXIMIZE;
CFrameWnd::ActivateFrame(nCmdShow);
}
十二、对话框透明特效:
在OnInitDialog()中加入以下代码:
//加入WS_EX_LAYERED扩展属性
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);
}
注意:fun的参数128不能太小,否则就完全透明了!
十三、设置对话框里的STATIC控件颜色属性:
在该对话框增加WM_CTLCOLOR事件,加入以下代码:
if( nCtlColor==CTLCOLOR_STATIC )
{
pDC->SetTextColor(RGB(255,255,255));
pDC->SetBkColor(RGB(91,145,244));
pDC->SetBkMode(TRANSPARENT); //设置透明
}
设置STATIC控件背景透明:
if( nCtlColor==CTLCOLOR_STATIC )
{
pDC->SetBkMode(TRANSPARENT); //设置透明
return (HBRUSH)::GetStockObject(NULL_BRUSH);
}
十四、使窗口的最大化和最小化按钮消失:
在PreCreateWindow函数中添加以下代码即可:
int xSize = ::GetSystemMetrics( SM_CXSCREEN );
int ySize = ::GetSystemMetrics( SM_CYSCREEN );
cs.cx = xSize * 6 / 10;
cs.cy = ySize * 6 / 10;
cs.x = ( xSize - cs.cx ) / 2;
cs.y = ( ySize - cs.cy ) / 2;

cs.style &= ~WS_THICKFRAME;
cs.style &= ~( WS_MAXIMIZEBOX | WS_MINIMIZEBOX );

cs.dwExStyle |= WS_EX_TOOLWINDOW;
十五、设置控件字体颜色:(例如STATIC控件)
在OnCtlColor函数中添加如下代码:(可能需要选择STATIC的简单属性)
if(nCtlColor==CTLCOLOR_STATIC)
{ pDC->SetTextColor(RGB(255,0,0));
pDC->SetBkColor(RGB(128,128,128));//设置文本背景色
pDC->SetBkMode(TRANSPARENT);//设置背景透明
}
其他控件的宏定义为:
.CTLCOLOR_BTN 按钮控件
.CTLCOLOR_DLG 对话框
.CTLCOLOR_EDIT 编辑框
.CTLCOLOR_LISTBOX 列表控件
.CTLCOLOR_MSGBOX 消息控件
.CTLCOLOR_SCROLLBAR 滚动条控件
.CTLCOLOR_STATIC 静态控件
十六、将字符转换为数字:
int i = atoi("12345"); 或 sscanf("12345","%d",&i);
十七、调用外部应用程序可使用的函数:
CreateProcess、WinExec、ShellExecute。
例:ShellExecute(pWnd->m_wnd, "open", "my.exe", NULL, NULL, SW_NORMAL)
一、父窗体句柄,二、命令"open",三、文件路径,四、参数,五、运行路径,六、显示方式
十八、经典安装程序制作软件:InstallShield for Microsoft Visual C++6.0
release 方式是在build菜单中的Set Active configuration中改
在project菜单里面,选Add to Project的component and control来加入ocx控件
十九、控件的注册:
1.注册
regsvr32 x:\xxx\demo.ocx 不一定非得在 Windows 系统目录
2.卸载
regsvr32 /u x:\xxx\demo.ocx
二十、获取当前时间:
CTime m_time=CTime::GetCurrentTime();
char szText[100];
memset(szText,0,100);
sprintf(szText,"%d_%d_%d",m_time.GetHour(),m_time.GetMinite(),m_time.GetSecond());

// 如何得到当前时间日期
CTime time = CTime::GetCurrentTime();
CString m_strTime = time.Format("%Y-%m-%d %H:%M:%S");
// 方法二
SYSTEMTIME ti;
GetSystemTime(&ti); // 如何得到当前时间日期
ti.wMilliseconds; // 得到毫秒时间
SYSTEMTIME time;
CString str;
GetLocalTime( &time );
str.Format( "%04d:%02d:%02d",time.wYear,time.wMonth.....);
二一、修改单文档程序的标题:
OnCreat()中加入 SetWindowText("weichao");
CMainFrame::PreCreateWindow(CREATESTRUCT& cs)中加入 cs.style =WS_OVERLAPPEDWINDOW;

二二、隐藏程序在任务栏的图标:
对话框程序放OnInitDialog()函数:
SetWindowLong(this->m_hWnd,GWL_EXSTYLE,WS_EX_TOOLWINDOW);//隐藏任务拦按钮
二三、读取编辑框内容:
GetDlgItemText(IDC_EDIT_TXDATA,m_strTXData);
二四、自绘菜单宽度不对,高度是对的,解决办法:
在ClassWizard中的ClassName下,选CMianFrame,在Messages下选WM_CONTEXTMENU并生成相应的函数,如下:
void CMainFrame::OnContextMenu(CWnd* pWnd, CPoint point)
{
CMenu menu;
menu.LoadMenu(IDR_MENU1);//IDR_MENU1是你要弹出菜单的ID号.
CMenu *popup=menu.GetSubMenu(0);
popup->TrackPopupMenu(TPM_LEFTALIGN,point.x,point.y,this);
}
二五、重启计算机:
调用一个API函数ExitWindowsEx就可以了,
两个参数:UFlag,标记,可以选择EWX_REBOOT,EWX_SHUTDOWN,EWX_POWEROFF再或上EWX_FORCE第二个参数就是0了
二六、无title对话框的移动:
void CScreenSnapDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
//实现窗体无标题移动
PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(point.x,point.y));

CDialog::OnLButtonDown(nFlags, point);
}
二七、获取操作系统版本:
OSVERSIONINFO OsVersionInfo;//包含操作系统版本信息的数据结构
OsVersionInfo.dwOSVersionInfoSize= sizeof(OSVERSIONINFO);
GetVersionEx(&OsVersionInfo);//获取操作系统版本信息
二八、设置对话框为最顶层:(在OnInitDialog中添加)
SetWindowPos(&wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
二九、对话框程序不在任务栏显示:(在OnInitDialog中添加)
ModifyStyleEx(WS_EX_APPWINDOW,WS_EX_TOOLWINDOW);
三十、向对话框窗口添加右键菜单:
CMenu menu,*pmenu;
menu.LoadMenu(IDR_MENU1);
pmenu=menu.GetSubMenu(0);

CPoint ptScreen(point);
ClientToScreen(&ptScreen);

pmenu->TrackPopupMenu(TPM_RIGHTBUTTON,ptScreen.x,ptScreen.y,this);
三一、文件查找:(例查找连续的换行符)
FILE *fp,*fp1;
int flag=0;
int ch;
fp=fopen("c:\\test.txt","r");
fp1=fopen("c:\\wrttest.txt","w");

while(!feof(fp))
{
ch=fgetc(fp);
if(feof(fp))
break;
if(ch==’\n’&&flag==1)
continue;
else if(ch==’\n’&&flag==0)
flag=1;
else
flag=0;
fputc(ch,fp1);
}
fclose(fp1);
fclose(fp);
三二、托盘菜单不点击不能消失的解决办法:
在菜单之后使用下述代码:
CPoint pt;
GetCursorPos(&pt);

SetForegroundWindow();
NotifyMenu.TrackPopupMenu(TPM_RIGHTBUTTON,pt.x,pt.y,this);
PostMessage(WM_NULL,0,0);
三三、对话框由小到大显示的动画效果:
在InitDialog中增加:
ShowWindow(SW_HIDE);
CRect dlgRect;
GetClientRect(&dlgRect);
CPoint centerPoint;
centerPoint.x=dlgRect.Width()/2;
centerPoint.y=dlgRect.Height()/2;//得到对话框的中点座标
CRgn testrgn;
this->ShowWindow(SW_HIDE);
int m=GetSystemMetrics(SM_CYSIZEFRAME);

//以下代码实现对话框的动态弹出

for (int i=10;i<dlgRect.Width()/2+m;i+=1)
{

testrgn.CreateRectRgn(centerPoint.x-i,centerPoint.y-i,centerPoint.x+i,centerPoint.y+i);

SetWindowRgn((HRGN) testrgn,TRUE);
ShowWindow(SW_SHOW);
CenterWindow();
testrgn.DeleteObject();
}
三四、按行读出文本文件:
下面的例子演示了一行一行取,直到取完。
CStdioFile myFile;
CString ReadFileString;
if(myFile.Open("C:\\Readme.txt", Cfile::modeRead) == TRUE)
{
while(myFile.ReadString(ReadFileString) != FALSE)
{
//... 处理代码
}
}
三五、使用IDC_HAND时提示未定义,加入以下代码:
#if(WINVER >= 0x0500)
#define IDC_HAND MAKEINTRESOURCE(32649)
#endif /* WINVER >= 0x0500 */
三六、使应用程序启动时不自动创建新文档
在默认情况下,用AppWizard开发的SDI/MDI应用程序在启动时创建一个新的文档。如果要使应用程序在启动时不创建新

文档,只需在应用类CmyApp::InitInstance()函数的ProcessShellCommand调用前加上下面的语句就可以了:

cmdInfo.m_nShellCommand = CComandLineInfo::FileNothing;
三七、播放mp3:
CFileDialog file(true);
if(file.DoModal()==IDOK)
{
CString filename=file.GetFileName();
if(hwnd!=NULL)
{
MCIWndDestroy(hwnd);
}
hwnd=MCIWndCreate(this->m_hWnd,NULL,MCIWNDF_NOPLAYBAR,filename);
::ShowWindow(hwnd,SW_HIDE);
MCIWndSetVolume(hwnd,1000);
MCIWndPlay(hwnd);
}
三八、获取屏幕RGB值:OnTimer中添加
CPoint pos;
GetCursorPos(&pos);//获取鼠标座标
HDC hDC = ::GetDC(NULL);
COLORREF clr = ::GetPixel(hDC, pos.x, pos.y);

CString ClrText;
ClrText.Format("R:%d G:%d B:%d",GetRvalue(clr),GetGvalue(clr),GetBvalue(clr));
三九、打开一个网址:
打开http://www.sina.com.cn这个站点如下:
ShellExecute(NULL, "open", "http://www.sina.com.cn",NULL, NULL, SW_MAXIMIZE );
此命令将以默认浏览器打开http://www.sina.com.cn,并将加开后的窗口最大化。
又例:
ShellExecute(NULL, "open", "IEXPLORE.exe http://www.sina.com.cn",NULL, NULL,
SW_MAXIMIZE );
此命令将直接用IE打开一个sina的站点。不过将开一个新的窗口。
四十、位图按钮:
CButton *pRadio = (CButton*)GetDlgItem(IDC_RADIO);
pRadio->SetBitmap(::LoadBitmap(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDB_BITMAP)));


26..Dll调用
typedef void (WINAPI * TESTDLL)();
HINSTANCE hmod;
hmod = ::LoadLibrary ("mfcdll.dll");
if(hmod==NULL)
{
AfxMessageBox("Fail");
}
TESTDLL lpproc;
lpproc = (TESTDLL)GetProcAddress (hmod,"Show");
if(lpproc!=(TESTDLL)NULL)
(*lpproc)();

FreeLibrary(hmod);


27.透明窗口
BOOL CTestDlg::OnInitDialog()
{
CDialog::OnInitDialog();

// TODO: Add extra initialization here

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;

fun=(MYFUNC)GetProcAddress(hInst, "SetLayeredWindowAttributes");
if(fun)fun(this->GetSafeHwnd(),0,128,2);
FreeLibrary(hInst);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}

28.去掉Dialog标题栏
ModifyStyle( WS_CAPTION, WS_MINIMIZEBOX, SWP_DRAWFRAME );
设置鼠标:
BOOL CPartTransparentDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
// TODO: Add your message handler code here and/or call default
SetCursor(AfxGetApp()->LoadCursor(IDC_CURSOR1));
return TRUE;
}
拖动窗口,在OnLButtonDown时调用
PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(point.x, point.y));


29.启动程序
::ShellExecute(NULL,"open","http://www.tomcom",NULL,NULL,SW_SHOWNORMAL);

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章