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

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