C++的常用知识,常见问题解答

来源:互联网 发布:网络犯罪案件 编辑:程序博客网 时间:2024/05/01 08:30
C++的常用知常见问题解答。
C++的常用知识
  1: 得到系统时间日期(使用GetLocalTime)
  CString sTime,sYear,sMonth,sDay;
  SYSTEMTIME CurTime;
  GetLocalTime(&CurTime);
  sYear.Format(%d,CurTime.wYear);
  sMonth.Format(%d,CurTime.wMonth);
  sDay.Format(%d,CurTime.wDay);
  sTime = sYear+ sMonth + sDay;
  // CurTime.wHour
  // CurTime.wMinute
  // CurTime.wSecond IBM
  AfxMessageBox(sTime);
  2: 分离字串
  CString str = 4d3f0a2278;
  unsigned char a12;
  long x;
  for(int i = 0;i< (str.GetLength()/2);i++)
  {
  sscanf(str.Mid(2*i,2),%x,&x);
  a[i] = x;
  }
  3: 得到当前目 (GetCurrentDirectory)
  char CurPath[MAX_PATH];
  DWORD size=MAX_PATH;
  GetCurrentDirectory(size,CurPath);
  AfxMessageBox(CurPath);
  //
  CString number;
  int len = LineLength(LineIndex(0));
  LPTSTR p=number.GetBuffer(len);
  this->GetLine(0,p,len);
  AfxMessageBox(number);
  得到系 (GetSystemDirectory)
  4: 从字符串中提取数字
  CString strNum;
  CString str(测试125各国87kk);
  strNum = GetStr(str);
  AfxMessageBox(strNum);
  5: 建无模对话
  CDlg_Test *aa = new CDlg_Test;
  aa->Create(IDD_DIALOG1,NULL);
  aa->ShowWindow(SW_SHOW);1
  6: 得到窗口绝对
  CString strNum,strNum1;
  CRect rect;
  GetClientRect(&rect);
  ClientToScreen(&rect);
  strNum.Format(X: %d,rect.top);
  strNum1.Format( Y: %d,rect.center);
  strNum = strNum + strNum1;
  AfxMessageBox(strNum);
  7: 制文件
  SHFILEOPSTRUCT Op;
  char FromBuf[]=E:temp;
  char ToBuf[]=SINTEKSERVER个人文档;;
  Op.hwnd = NULL;
  Op.wFunc = FO_COPY;
  Op.pFrom = FromBuf;
  Op.pTo = ToBuf;
  Op.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION ;
  Op.fAnyOperationsAborted = FALSE;
  Op.hNameMappings = NULL;
  Op.lpszProgressTitle = NULL;
  MessageBox(制完,提示,MB_OK|MB_ICONINFORMATION);
  8: Ctrl+鼠
  case WM_LBUTTONDOWN://消息wParam ==
  if (wParam & MK_CONTROL)
  MessageBox(hwnd,aaa,bbb,MB_OK);
  break;
  或
  case WM_LBUTTONDOWN:
  MessageBox(hwnd,aaa,bbb,MB_OK);
  break;
 
 
常见问题解答。
1如何通码获用程序主窗口的?
主窗口的保存在CWinThread::m_pMainWnd,AfxGetMainWnd实现
AfxGetMainWnd() ->ShowWindow(SW_SHOWMAXMIZED)
//
使程序最大化.
2确定用程序的路径
Use GetModuleFileName 用程序的路径,然后去掉可行文件名。
Example:
TCHAR
exeFullPath[MAX_PATH] // MAX_PATH
API中定了吧,好象是
128
GetModuleFileName(NULL,exeFullPath,MAX_PATH)
3如何在程序中得其他程序的图标?
方法:
(1) SDK
函数 SHGetFileInfo 或使用 ExtractIcon图标资源的 handle,
(2) SDK
函数 SHGetFileInfo 得有文件的很多信息,如大小图标,属性, 型等.
Example(1):
在程序窗口左上角 NotePad图标.
void CSampleView:
OnDraw(CDC * pDC)
{
if( :: SHGetFileInfo(_T("c://pwin95//notepad.exe"),0,
&stFileInfo,sizeof(stFileInfo),SHGFI_ICON))
{
pDC ->DrawIcon(10,10,stFileInfo.hIcon)
}
}
Example(2):
功能,Use ExtractIcon Function
void CSampleView:: OnDraw(CDC *pDC)
{
HICON hIcon=:: ExtractIcon(AfxGetInstanceHandle(),_T
("NotePad.exe"),0)
if (hIcon &&hIcon!=(HICON)-1)
pDC->DrawIcon(10,10,hIcon)
}
    
: notepad.exe的路径正上来GetWindowsDirectory函数得到, 如果是 win95下的画笔,应该访问注册表的方法得其路径,要作成一个比考究的程序,考虑应该全面点.
 4得各信息
Windows: Use "GetWindowsDirectory"
Windows
下的system: Use "GetSystemDirectory"
temp
: Use "GetTempPath"
当前目: Use "GetCurrentDirectory"
注意前两个函数的第一个参数录变量名,后一个为缓冲区后两个相反.
5如何自定消息
1) 手工定消息,可以这么
#define WM_MY_MESSAGE(WM_USER+100),
MS
推荐的至少是 WM_USER+100
2)
写消息理函数,
WPARAM,LPARAM
返回LRESULT.
LRESULT CMainFrame::OnMyMessage(WPARAM wparam,LPARAM lParam)
{
temp
: Use "GetTempPath"
//
加入你的理函数 irectory"
}
6如何改窗口的图标?
向窗口 WM_SECTION消息。
Example:
HICON hIcon=AfxGetApp() ->LoadIcon(IDI_ICON)
ASSERT(hIcon)
AfxGetMainWnd() ->SendMessage(WM_SECTION,TRUE,(LPARAM)hIcon)
7如何改窗口的缺省?
CWnd:: PreCreateWindow 并修改CREATESTRUCT构来指定窗口格和其他建信息.
Example: Delete "Max" Button and Set Original
Window's Position and Size

BOOL CMainFrame:: PreCreateWindow
(CREATESTRUCT &cs)
{
cs.style &=~WS_MAXINIZEMOX
cs.x=cs.y=0
cs.cx=GetSystemMetrics(SM_CXSCREEN/2)
cs.cy=GetSystemMetrics(SM_CYSCREEN/2)
return CMDIFramewnd ::PreCreateWindow(cs)
}
8如何将窗口居中?
Call Function CWnd::
Center Windows
Example(1):
Center Window( ) //Relative to it's parent
// Relative
to Screen
Example(2):
Center Window(CWnd:: GetDesktopWindow( ))
//Relative to
Application's MainWindow
AfxGetMainWnd( ) ->
Center Window( )
9如何窗口和 MDI窗口一启就最大化和最小化?
窗口。
InitStance 函数中 m_nCmdShow的取.
m_nCmdShow=SW_SHOWMAXMIZED //
最大化
m_nCmdShow=SW_SHOWMINMIZED //
最小化
m_nCmdShow=SW_SHOWNORMAL //
正常方式
MDI
窗口:
如果是建新的用程序,可以用MFC AppWizard Advanced 并在MDI子窗口检测最大化或最小化可以重 MDI Window PreCreateWindow函数,WS_MAXMIZE or WS_MINMIZE
如果从 CMDIChildWnd派生, OnInitialUpdate函数中的 CWnd::Show Window来指定 MDI Child Window格。
10如何限制窗口的大小?
也就是 FixedDialog形式。 Windows WM_GETMAXMININFO消息来跟踪, , OnGetMAXMININFO 中写代:
11如何使窗口不可
简单,SW_HIDE 藏窗口,可以 FindWindow,ShowWindow控制.
12如何建一个字回CEditView
CWnd : : PreCreateWindow和修改CREATESTRUCT构,关闭CEditView象的ES_AUTOHSCROLLWS_HSCROLL格位,由于CEditView : : PreCreateWindowcs. style用基函数后要修改cs . style
BOOL CSampleEDitView : : PreCreateWindow (CREATESTRUCT&cs)
{
//First call basse class function .
BOOL bResutl =CEditView : : PreCreateWindow (cs)
// Now specify the new window style .
cs.style &= ~ (ES_AUTOHSCROLL
WS_HSCROLL)
return bResult
}
13如何使程序保持极小状?
这么办: 在恢程序窗体大小WindowsWM_QUERY-OPEN消息,用 ClassWizard置成函数
OnQueryOpen() ,add following code:

Bool CMainFrame:: OnQueryOpen( )
{
Return false
}
14窗口
CWnd : : SetWindowPos并指定SWP_NOSIZE志。目的位置与父窗口有顶层窗口与屏幕有)。CWnd : : MoveWindow要指定窗口的大小。
//Move window to positoin 100 , 100 of its parent window .
SetWindowPos (NULL, 100 , 100 , 0 , 0 , SWP_NOSIZE
SWP_NOAORDER)
15通用控件的示窗口
MFC提供了几个CView派生的封装了通用控件的功能,但仍然使用工作框文档示窗口体系构:CEditView封装了编辑控件,CTreeView保持了列表控件,CListView封装了列表示窗口控件,CRichEditView可以理多种编辑控件。
16重置窗口的大小
CWnd: : SetWindowPos并指定SWP_NOMOVE志,也可CWnd : : MoveWindow 但必指定窗口的位置。
// Get the size of the window .
Crect reWindow
GetWindowRect (reWindow )
//Make the window twice as wide and twice as tall .
SetWindowPos (NULL , 0 , 0 , reWindow . Width ( ) *2,
reWindow . Height () * 2,
SWP_NOMOVE
SWP_NOZORDER )
17如何单击除了窗口标题栏以外的区域使窗口移
当窗口需要确定鼠位置Windows向窗口WM_NCHITTEST信息,可以信息使Windows认为在窗口标题上。对话框和基于对话用程序,可以使用ClassWizard信息并用基函数,如果函数返回HTCLIENT 表明鼠在客房区域,返回HTCAPTION表明鼠Windows标题栏中。
UINT CSampleDialog : : OnNcHitTest (Cpoint point )
{
UINT nHitTest =Cdialog: : OnNcHitTest (point )
return (nHitTest = =HTCLIENT)?
HTCAPTION : nHitTest
}
上述技有两点不利之
其一是在窗口的客区域双击时,窗口将极大;
其二,它不适合包含几个窗的主框窗口。
有一方法,当用按下鼠使主框窗口认为在其窗口标题上,使用ClassWizard窗中WM_LBUTTODOWN信息并向主框窗口送一个WM_NCLBUTTONDOWN信息和一个单击测试HTCAPTION
void CSampleView : : OnLButtonDown (UINT nFlags , Cpoint point
)
{
CView : : OnLButtonDow (nFlags , pont )

//Fool frame window into thinking somene clicked
on
its caption bar .
GetParentFrame ( ) —> PostMessage (
WM_NCLBUTTONDOWN ,
HTCAPTION , MAKELPARAM (poitn .x , point .y) )

}
也适用于对话框和基于用程序,只是不必
CWnd: :GetParentFrame

void CSampleDialog : : OnLbuttonDown (UINT nFlags, Cpoint point )
{
Cdialog : : OnLButtonDow (nFlags, goint )
//Fool dialog into thinking simeone clicked on its
caption bar .
PostMessage (WM_NCLBUTTONDOWN , HTCAPTION , MAKELPARM (point.x
, point. y
) )
}
18如何改变视窗的背景
Windows向窗口送一个WM_ERASEBKGND消息通知窗口擦除背景,可以使用ClassWizard载该消息的缺省理程序来擦除背景(实际是画),并返回TRUE以防止Windows擦除窗口。
//Paint area that needs to be erased.
BOOL CSampleView : : OnEraseBkgnd (CDC* pDC)
{
// Create a pruple brush.
CBrush Brush (RGB (128 , 0 , 128) )

// Select the brush into the device context .
CBrush* pOldBrush = pDC—>SelcetObject (&brush)

// Get the area that needs to be erased .
CRect reClip
pDC—>GetCilpBox (&rcClip)
//Paint the area.
pDC—> PatBlt (rcClip.left , rcClip.top , rcClip.Width ( ) , rcClip.Height( ) , PATCOPY )

//Unselect brush out of device context .
pDC—>SelectObject (pOldBrush )

// Return nonzero to half fruther processing .
return TRUE
}
 
19如何改窗口标题
CWnd : : SetWindowText可以改任何窗口(包括控件)的标题
//Set title for application's main frame window .
AfxGetMainWnd ( ) —> SetWindowText (_T("Application title") )

//Set title for View's MDI child frame window .
GetParentFrame ( ) —> SetWindowText ("_T ("MDI Child Frame new title")
)

//Set title for dialog's push button control.
GetDigitem (IDC_BUTTON) —> SetWindowText (_T ("Button new title ") )
如果需要常修改窗口的标题(注:控件也是窗口),应该使用半文档化的函数AfxSetWindowText函数在AFXPRIV.H明,在WINUTIL.CPP实现,在机帮助中找不到它,它在AFXPRIV.H中半文档化,在以后行的MFC中将文档化。
AfxSetWindowText
实现如下:
voik AFXAPI AfxSetWindowText (HWND hWndCtrl , LPCTSTR IpszNew )
{
itn nNewLen= Istrlen (Ipaznew)
TCHAR szOld [256]
//fast check to see if text really changes (reduces
flash in the
controls )
if (nNewLen >_contof (szOld)
|| : : GetWindowText (hWndCrtl, szOld , _countof (szOld) !=nNewLen
|| Istrcmp (szOld , IpszNew)! = 0
{
//change it
: : SetWindowText(hWndCtrl , IpszNew )
}
}
20如何防止主框窗口在其明中示活的文档名
建主框窗口和MDI子窗口通常具有FWS_ADDTOTITLE格位,如果不希望在明中自添加文档名,禁止该风格位,可以使用ClassWizard重置
CWnd: : PreCreateWindow
关闭FWS_ADDTOTITLE格。
BOOL CMainFrame : : PreCreateWindow (CREATESTRUCT&cs)
{
//Turn off FWS_ADDTOTITLE in main frame .
cs.styel & = ~FWS_ADDTOTITLE
 
return CMDIFrameWnd : : PreCreateWindow (cs )
}
关闭MDI子窗口的FWS _ADDTOTITLE格将建一个具有空标题的窗口,可以CWnd: : SetWindowText标题住自己标题时要遵循接口格指南。
21如何取有窗口正在理的当前消息的信息
CWnd: : GetCurrentMessage可以取一个MSG。例如,可以使用ClassWizard将几个菜单项处理程序映射到一个函数中,然后GetCurrentMessage来确定所中的菜单项
viod CMainFrame : : OnCommmonMenuHandler ( )
{
//Display selected menu item in debug window .
TRACE ("Menu item %u was selected . /n" ,
22如何在代取工具条和状条的指
缺省工作框建状条和工具条将它主框窗口的子窗口,状条有一个AFX_IDW_STATUS_BAR标识符,工具条有一个AFX_IDW_TOOLBAR标识符,下例明了如何通一起CWnd: : GetDescendantWindowAfxGetMainWnd些子窗口的指
//Get pointer to status bar .
CStatusBar * pStatusBar = (CStatusBar *) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_STUTUS_BAR)

//Get pointer to toolbar .
CToolBar * pToolBar = (CToolBar * ) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_TOOLBAR)
23如何使能和禁止工具条的工具提示
如果置了CBRS_TOOLTIPS格位,工具条将示工具提示,要使能或者禁止工具提示,需要置或者清除该风格位。下例通过调CControlBar : : GetBarStyleCControlBar : : SetBarStyle建立一个完成此功能的成函数:
void CMainFrame : : EnableToolTips ( BOOL bDisplayTips )
{
ASSERT_VALID (m_wndToolBar)

DWORD dwStyle = m _wndToolBar.GetBarStyle ( )
if (bDisplayTips) dwStyle
=CBRS_TOOLTIPS
else
dwStyle & = ~CBRS_TOOLTIPS
m_wndToolBar.SetBarStyle (dwStyle )
}
24如何建一个不规则形状的窗口
可以使用新的SDK函数SetWindowRgn函数将画和鼠消息限定在窗口的一个指定的区域,实际上使窗口成指定的不规则形状。使用AppWizard建一个基于用程序并使用编辑器从主对话资源中除所在的缺省控件、标题以及界。
给对话类增加一个CRgn数据成,以后要使用数据成建立窗口区域。
Class CRoundDlg : public CDialog
{

private :
Crgn m_rgn : // window region

}
修改OnInitDialog函数建立一个椭圆区域并SetWindowRgn区域分配窗口:
BOOL CRoundDlg : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )

//Get size of dialog .
CRect rcDialog
GetClientRect (rcDialog )

// Create region and assign to window .
m_rgn . CreateEllipticRgn (0 , 0 , rcDialog.Width( ) , rcDialog.Height ( ) )
SetWindowRgn (GetSafeHwnd ( ) , (HRGN) m_ rgn ,TRUE )

return TRUE
}

建立区域和SetWindowRgn,已建立一个不规则形状的窗口,下面的例子程序是修改OnPaint函数使窗口形状看起来象一个球形体。
voik CRoundDlg : : OnPaint ( )
{
CPaintDC de (this) // device context for painting
.
//draw ellipse with out any border
dc. SelecStockObject (NULL_PEN)
//get the RGB colour components of the sphere color
COLORREF color= RGB( 0 , 0 , 255)
BYTE byRed =GetRValue (color)
BYTE byGreen = GetGValue (color)
BYTE byBlue = GetBValue (color)

// get the size of the view window
Crect rect
GetClientRect (rect)

// get minimun number of units
int nUnits =min (rect.right , rect.bottom )

//calculate he horiaontal and vertical step size
float fltStepHorz = (float) rect.right /nUnits
float fltStepVert = (float) rect.bottom /nUnits


int nEllipse = nUnits/3 // calculate how many to
draw
int nIndex
// current ellipse that is being draw

CBrush brush
// bursh used for ellipse fill color
CBrush *pBrushOld // previous
brush that was selected into dc
//draw ellipse , gradually moving towards upper-right
corner
for (nIndex = 0 nIndes < + nEllipse nIndes++)
{
//creat solid brush
brush . CreatSolidBrush (RGB ( ( (nIndex*byRed ) /nEllipse ).
( ( nIndex * byGreen ) /nEllipse ), ( (nIndex * byBlue)
/nEllipse ) ) )

//select brush into dc
pBrushOld= dc .SelectObject (&brhsh)

//draw ellipse
dc .Ellipse ( (int) fltStepHorz * 2, (int) fltStepVert * nIndex ,
rect. right -( (int) fltStepHorz * nIndex )+ 1,
rect . bottom -( (int) fltStepVert * (nIndex *2) ) +1)

//delete the brush
brush.DelecteObject ( )
}
}

最后,WM_NCHITTEST消息,使当打窗口的任何位置能移窗口。
UINT CRoundDlg : : OnNchitTest (Cpoint point )
{
//Let user move window by clickign anywhere on thewindow .
UINT nHitTest = CDialog : : OnNcHitTest (point)
rerurn (nHitTest = = HTCLIENT)? HTCAPTION: nHitTest

}
25如何用程序的例句柄?
用程序的例句柄保存在CWinApp m_hInstance ,可以这么调AfxGetInstancdHandle得句柄.
Example: HANDLE hInstance=AfxGetInstanceHandle()
26如何用程序?
是个很简单又是程中常要遇到的问题.
向窗口 WM_CLOSE消息, CWnd::OnClose函数.许对提示是否保存修改的数据.
Example: AfxGetMainWindow()->SendMessage(WM_CLOSE)

可以建一个自定的函数 Terminate Window
void Terminate Window(LPCSTR pCaption)
{
CWnd *pWnd=Cwnd::FindWindow(NULL,pCaption)

if (pWnd)

pWnd ->SendMessage(WM_CLOSE)
}

    
: FindWindow函数不是提倡的做法,因它无法标题栏,比如我检测 Notepad是不是已运行而事先不知道Notepad标题栏,这时FindWindow就无能力了,可以通 windows列表的法来实现。在机械出版社"Windows 95 API开发指南"有比较详细的介,里就不再多说乐
27如何建和使用无模式对话
MFC将模式和无模式对话封装在同一个中,但是使用无模式对话需要几个对话需要几个额处步骤。首先,使用编辑器建立对话资源并使用ClassWizard建一个CDialog的派生。模式和无模式对话的中止是不一的:模式对话过调CDialog : : EndDialog 来中止,无模式对话则CWnd: : DestroyWindow来中止的,函数CDialog : : OnOKCDialog : : OnCancelEndDialog ,所以需要DestroyWindow并重置无模式对话的函数。
void CSampleDialog : : OnOK ( )
{
// Retrieve and validate dialog data .
if (! UpdateData (TRUE) )
{
// the UpdateData rountine
will set focus to correct item TRACEO (" UpdateData failed during dialog termination ./n")
return
}

//Call DestroyWindow instead of EndDialog .
DestroyWindow ( )
}

void CSampleDialog : : OnCancel ( )
{
//Call DestroyWindow instead of EndDialog .
DestroyWindow ( )
}

其次,需要正确除表示对话C++象。于模式很容易,需要建函数返回后即可C++象;无模式对话不是同的,建函数用后立即返回,因而用不知道何时删C++象。撤窗口工作框CWnd : : PostNcDestroy,可以重置函数并行清除操作,this
void CSampleDialog : : PostNcDestroy ( )
{
// Declete the C++ object that represents this dialog.
delete this

最后,要建无模式对话。可以CDialog : : DoModal建一个模式放,要建一个无模式对话则CDialog: : Create。下面的例子用程序是如何建无模式对话的:象;无模式对话不是同的,建函数用后立即返回,
void CMainFrame : : OnSampleDialog ( )
{
//Allocate a modeless dialog object .
CSampleDilog * pDialog =new CSampleDialog
ASSERT_VALID (pDialog) Destroy ( )

//Create the modeless dialog . represents this dialog.
BOOL bResult = pDialog —> Creste (IDD_IDALOG)
ASSERT (bResult )
}
28如何防止主框窗口在其明中示活的文档名
建主框窗口和MDI子窗口通常具有FWS_ADDTOTITLE格位,如果不希望在明中自添加文档名,禁止该风格位,可以使用ClassWizard重置
CWnd: : PreCreateWindow
关闭FWS_ADDTOTITLE格。
BOOL CMainFrame : : PreCreateWindow (CREATESTRUCT&cs)
{
//Turn off FWS_ADDTOTITLE in main frame .
cs.styel & = ~FWS_ADDTOTITLE
 
return CMDIFrameWnd : : PreCreateWindow (cs )
}
关闭MDI子窗口的FWS _ADDTOTITLE格将建一个具有空标题的窗口,可以CWnd: : SetWindowText标题住自己标题时要遵循接口格指南。
29如何在代取工具条和状条的指
缺省工作框建状条和工具条将它主框窗口的子窗口,状条有一个AFX_IDW_STATUS_BAR标识符,工具条有一个AFX_IDW_TOOLBAR标识符,下例明了如何通一起CWnd: : GetDescendantWindowAfxGetMainWnd些子窗口的指
//Get pointer to status bar .
CStatusBar * pStatusBar = (CStatusBar *) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_STUTUS_BAR)
//Get pointer to toolbar .
CToolBar * pToolBar = (CToolBar * ) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_TOOLBAR)
30其他的用程序?
三个SDK函数 winexec, shellexecute,createprocess可以使用。
WinExec
简单,两个参数,前一个指定路径,后一个指定示方式.后一个参数一下,比如泥用 SW_SHOWMAXMIZED方式去加一个无最大化按的程序,就是Neterm,calc等等,就不会出正常的窗体,但是已被加到任列表里了。
ShellExecute
WinExex灵活一点,可以指定工作目,下面的Example就是直接打 c:/temp/1.txt,而不用加 txt文件关联用程序,很多安装程序完成后都会打一个窗口,来Readme or Faq,我猜就是这么作的啦.
ShellExecute(NULL,NULL,_T("1.txt"),NULL,_T("c://temp"),SW_SHOWMAXMIZED)
CreateProcess
复杂,一共有十个参数,不大部分都可以用NULL代替,它可以指定程的安全属性,承信息,等等.来看个很简单Example:
STARTUPINFO stinfo
//
窗口的信息
PROCESSINFO procinfo //
程的信息
CreateProcess(NULL,_T("notepad.exe"),NULL,NULL.FALSE,
NORMAL_PRIORITY_

CLASS,NULL,NULL, &stinfo,&procinfo)
31如何在代取工具条和状条的指
缺省工作框建状条和工具条将它主框窗口的子窗口,状条有一个AFX_IDW_STATUS_BAR标识符,工具条有一个AFX_IDW_TOOLBAR标识符,下例明了如何通一起CWnd: : GetDescendantWindowAfxGetMainWnd些子窗口的指
//Get pointer to status bar .
CStatusBar * pStatusBar = (CStatusBar *) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_STUTUS_BAR)
32如何使能和禁止工具条的工具提示
如果置了CBRS_TOOLTIPS格位,工具条将示工具提示,要使能或者禁止工具提示,需要置或者清除该风格位。下例通过调CControlBar : : GetBarStyleCControlBar : : SetBarStyle建立一个完成此功能的成函数:
void CMainFrame : : EnableToolTips ( BOOL bDisplayTips )
{
ASSERT_VALID (m_wndToolBar)
DWORD dwStyle = m _wndToolBar.GetBarStyle ( )
if (bDisplayTips) dwStyle
=CBRS_TOOLTIPS
else
dwStyle & = ~CBRS_TOOLTIPS
m_wndToolBar.SetBarStyle (dwStyle )
}
//Get pointer to toolbar .
CToolBar * pToolBar = (CToolBar * ) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_TOOLBAR)
33如何置工具条标题
工具条是一个窗口,所以可以在CWnd : : SetWindowText标题,例子如下:
int CMainFrame : : OnCreate (LPCREATESTRUCT lpCreateStruct )
{

// Set the caption of the toolbar .
m_wndToolBar.SetWindowText (_T "Standdard")
34如何使窗口始在最前方?
BringWindowToTop(Handle)
SetWindowPos
函数,指定窗口的顶风,WS_EX_TOPMOST展窗口的

Example:
void ToggleTopMost(
CWnd *pWnd)
{
ASSERT_VALID(pWnd)
pWnd ->SetWindowPos(pWnd-> GetStyle( ) &WS_EX_TOPMOST)?
&wndNoTopMOST: &wndTopMost,0,0,0,0,SSP_NOSIZE|WSP_NOMOVE)
}
35如何在对话框中示一个位
功于Win 32的静控件和Microsoft编辑器,在对话框中示位是很容易的,只需将形控件拖到对话中并选择适当属性即可,用也可以图标、位以及增型元文件。
36如何改变对话或窗体窗的背景
CWinApp : : SetDialogBkColor可以改所有用程序的背景色。第一个参数指定了背景色,第二个参数指定了文本色。下例将用程序对话设为蓝色背景和黄色文本。
BOOL CSampleApp : : InitInstance ( )
{

//use blue dialog with yellow text .
SetDialogBkColor (RGB (0, 0, 255 ), RGB ( 255 ,255 , 0 ) )

}
需要重画对话(或对话的子控件)Windows对话发送消息WM_CTLCOLOR,通常用可以Windows选择绘画背景的刷子,也可重置消息指定刷子。下例明了建一个色背景对话步骤
首先,给对话增加一人成员变
CBursh :class CMyFormView : public CFormView
{

private :
CBrush m_ brush // background brush

}

其次,的构造函数中将刷子初始化所需要的背景色。
CMyFormView : : CMyFormView ( )
{
// Initialize background brush .
m_brush .CreateSolidBrush (RGB ( 0, 0, 255) )
}
最后,使用ClassWizardWM_CTLCOLOR消息并返回一个用来对话背景的刷子句柄。注意:由于当重画对话控件也要函数,所以要检测nCtlColor参量。
HBRUSH CMyFormView : : OnCtlColor (CDC* pDC , CWnd*pWnd , UINT nCtlColor
)
{
// Determine if drawing a dialog box . If we are, return +handle to
//our own background brush . Otherwise let windows handle it .
if (nCtlColor = = CTLCOLOR _ DLG )
return (HBRUSH) m_brush.GetSafeHandle ( )
return CFormView : : OnCtlColor (pDC, pWnd , nCtlColor
)
}
37如何取一个对话控件的指
有两方法。其一,CWnd: : GetDlgItem取一个CWnd*针调用成函数。下例GetDlgItem,将返回值传给一个CSpinButtonCtrl*以便CSpinButtonCtrl : : SetPos 函数:
BOOL CSampleDialog : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )

//Get pointer to spin button .
CSpinButtonCtrl * pSpin - ( CSpinButtonCtrl *) GetDlgItem(IDC_SPIN)
ASSERT _ VALID (pSpin)
//Set spin button's default position .
pSpin —> SetPos (10)
return TRUE
}
其二,可以使用ClassWizard将控件和成员变系起来。在ClassWizard简单选择Member Variables标签,然后选择Add Variable …。如果在对话资编辑器中,按下Ctrl并双控件即可Add Member Variable对话
38如何禁止和使能控件
控件也是窗口,所以可以CWnd : : EnableWindow使能和禁止控件。
//Disable button controls .
m_wndOK.EnableWindow (FALSE )
m_wndApply.EnableWindow (FALSE )
39如何改控件的字体
由于控件是也是窗口,用可以CWnd: : SetFont指定新字体。函数用一个Cfont,要保在控件撤消之前不能撤消字体象。下例将下的字体改8Arial字体:
//Declare font object in class declaration (.H file ).
private : Cfont m_font
// Set font in class implementation (.Cpp file ). Note m_wndButton is a
//member variable added by ClassWizard.DDX routines hook the member
//variable to a dialog button contrlo.
BOOL CSampleDialog : : OnInitDialog ( )
{

//Create an 8-point Arial font
m_font . CreateFont (MulDiv (8 , -pDC
—> GetDeviceCaps(LOGPIXELSY) ,72). 0 , 0 , 0 , FW_NORMAL , 0 , 0,0, ANSI_CHARSER, OUT_STROKE_PRECIS ,
CLIP_STROKE _PRECIS , DRAFT _QUALITY
VARIABLE_PITCH
FF_SWISS, _T("Arial") )
//Set font for push button .
m_wndButton . SetFont (&m _font )

}
40如何在OLE控件中使用OLE_COLOR数据
COleControl : : GetFortColorCOleControl : : GetBackColor等函数返回OLE _COLOR数据型的色,而GDI如笔和刷子使用的是COLORREF数据型,COleControl : : TranslateColor可以很容易地将OLE_COLOR型改COLORREF型。下例建了一个当前背景色的刷子:
void CSampleControl : : OnDraw (CDC* pdc
const Crect& rcBounds , const Crect& rcInvalid
)
{
//Create a brush of the cuttent background color.
CBrush brushBack (TranslateColor (GetBackColor () ) )
//Paint the background using the current backgroundcolor .
pdc—> FilllRect (rcBounds , &brushBack)
//other drawign commands

}
41在不使用通用文件打开对话的情况下如何示一个文件列表
CWnd: : DlgDirList或者CWnd: : DlgDirListComboBoxWindows 将自地向列表框或合框填充可用的驱动器名或者指定目中的文件,下例将Windows中的文件填充在合框中:
BOOL CSampleDig : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )
TCHAR szPath [MAX_PATH] = {"c://windows"}
int nReslt = DlgDirListComboBox (szPath, IDC_COMBO , IDC_CURIDIR, DDL_READWRITE
DDL_READONLYDDL_HIDDEN DDL_SYSTEMDDL_ARCHIVE)
return TRUE
}
42控件看起来倒
需要CSpinCtrl : : SetRange 置旋控件的范,旋控件的缺省上限0,缺省下限100意味着增加按控件的100变为0。下例将旋控件的范围设0100
BOOL CAboutDlg : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )
//set the lower and upper limit of the spin button
m_wndSpin . SetRange ( 0 ,100 )
return TRUE
}
Visual C++ 4.0 Print
对话中的Copise控件也有同问题:按下Up钮时的数目减少,而按下Down 钮时的数目增加。
43控件不能自地更新它下面的编辑控件
如果使用旋autu buddy特性,对话标记顺序中buddy窗口先于旋控件。从Layout选择Tab Order单项(或者按下Crtl+D)可以对话标签顺序。
44如何用位图显示下
Windows 95有几新的格,尤其是BS_BITMAPBS_ICON,要想具有位建按CButton : : SetBitmapCButton : : SetIcon要指定BS_BITMAPBS_ICON格。
首先,置按图标属性。然后,当对话初始化时调CButton: : SetIcon。注意:下例用图标代替位,使用位图时要小心,因不知道背景所有的——并非个人都使用浅灰色。
BOOL CSampleDlg : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )
//set the images for the push buttons .
BOOL CSampleDlg : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )
//set the images for the push buttons .
m_wndButton1.SetIcon (AfxGetApp ( ) —> LoadIcon (IDI _ IPTION1))
m_wndButton2.SetIcon (AfxGetApp ( ) —> LoadIcon (IDI _ IPTION2))
m_wndButton3.SetIcon (AfxGetApp ( ) —> LoadIcon (IDI _ IPTION3))
return TRUE
}
45如何一个建三
可以使用新的BS_PUSHBUTTON 格位和检测框以及按建一个三很容易,只需将检测框和按拖拉到对话中并指定属性Push—like即可。不用任何附加程序就可以成
46如何动态创建控件
分配一个控件象的例并用其Create函数。开发者最容易忽略两件事:忘指定WS_VISBLE标签和在中分配控件象。下例动态建一个下控件:
//In class declaration (.H file ).
private : CButton* m _pButton
//In class implementation (.cpp file ) .
m_pButton =new CButton
ASSERT_VALID (m_pButton)
m_pButton —>Create (_T ("Button Title ") , WS_CHILD
WS_VISIBLE BS_PUSHBUTTON. Crect ( 0, 0, 100 , 24) , this , IDC _MYBUTTON )
47如何限制编辑框中的准字符
如果用编辑控件中只允接收数字,可以使用一个准的编辑控件并指定新的ES_NUMBERS,它是Windows 95新增加的志,该标志限制编辑控件只按收数字字符。如果用需要复杂编辑控件,可以使用Microsoft 的屏蔽编辑控件,它是一个很有用的OLE定制控件。
如果希望不使用OLE 定制控件自己理字符,可以派生一个CEditWM_CHAR消息,然后从编辑控件中过滤出特定的字符。首先,使用ClassWizard建立一个 CEdit的派生,其次,在对话类中指定一个成员变量将编辑控件分OnInitdialog CWnd: : SubclassDlgItem .
//In your dialog class declaration (.H file )
private : CMyEdit m_wndEdit // Instance of your new edit control .
//In you dialog class implementation (.CPP file )
BOOL CSampleDialog : : OnInitDialog ( )
{

//Subclass the edit lontrod .
m_wndEdit .SubclassDlgItem (IDC_EDIT,this)

}
使用ClassWizardWM_CHAR消息,nChar参量并决定所行的操作,用可以确定是否修改、送字符。下例明了如何示字母字符,如果字符是字母字符,则调CWnd OnChar,否OnChar.
//Only display alphabetic dharacters .
void CMyEdit : : OnChar (UINT nChar , UINT nRepCnt , UITN nFlags )
{
//Determine if nChar is an alphabetic character.
if (: : IsCharAlpha ( ( TCHAR) nChar ) )
CEdit : : OnChar (nChar, nRepCnt , nFlags )
}
如果要修改字符,不能仅仅简单地用修改nCharCEdit: : OnChar,然后CEdit: : OnCharCWnd: : Default取原来的wParam lParam 这样是不行的。要修改一个字符,需要首先修改nChar,然后用修改nCharCWnd: : DefWindowProc。下例明了如何将字符转变为大写:
//Make all characters uppercase
void CMyEdit : : OnChar (UINT nChar , UINT nRepCnt , UINT nFlags )
{
//Make sure character is uppercase .
if (: : IsCharAlpha ( .( TCHAR) nChar)
nChar=: : CharUpper(nChar )
//Bypass default OnChar processing and directly call
//default window proc.
DefWindProc (WM_CHAR, nChar , MAKELPARAM (nRepCnt, nFlags ))
}
48如何改控件的
有两方法。其一,可以在父中指定控件的色,或者利用MFC4.0新的消息反射在控件中指定色。当控件需要重新着色,工作框用父窗口(通常是对话框)的CWnd: : OnCrtlColor,可以在父窗口中重置函数并指定控件的新的画属性。例如,下述代对话中的所有编辑控件文本色改为红色:
HBRUSH CAboutDig : : OnCtlColor (CDC * pDCM , CWnd * pWnd , UINT nCtlColor)
{
HBRUSH hbr = CDialog : : OnCtlColor (pDC, pWnd , nCtlColor )
//Draw red text for all edit controls .
if (nCtlColor= = CTLCOLOR_EDIT )
pDC —> SetTextColor (RGB (255, 0 , 0 , ) )
return hbr
}
然而,由于个父窗口必须处理通知消息并指定个控件的画属性,所以,这种方法不是完全的面向象的方法。控件消息并指定画属性更合情合理。消息反射允户这样做。通知消息首先父窗口,如果父窗口没有则发控件。建一个定制彩色列表框控件必遵循下述步骤
首先,使用ClassWizard 建一个CListBox 的派生为该类添加下述数据成
class CMyListBox publilc CListBox
{

private
COLORREF m_clrFor // foreground color
COLORREF m_clrBack //background color
Cbrush m_brush //background brush

}
其次,在的构造函数中,初始化数据中。
CMyListBox : : CMyListBox ()
{
//Initialize data members .
m_clrFore =RGB (255 , 255 , 0) //yellow text
m_clrBack=RGB (0 , 0 , 255) // blue background
m_brush . CreateSolidBrush (m _clrBack )
}
最后,使用ClassWizard理反射的WM_CTLCOLOR(=WM_CTLCOLOR)消息并指定新的画属性。
HBRUSH CMyListBox : : CtlColor (CDC* pDC, UINT nCtlColor )
{
pDC—>SetTextColor (m_clrFore)
pDC—>SetBkColor (m_clrBack)
return (HBRUSH) m_brush.GetSafeHandle ()
}
在,控件可以自己决定如何画,与父窗口无
49当向列表框中添加多个项时如何防止闪烁
CWnd::SetRedraw 清除重画志可以禁止CListBox(或者窗口)重画。当向列表框添加几个项时,用可以清除重画志,然后添加,最后恢重画志。确保重画列表框的新SetRedraw (TRUE) 之后CWnd::Invalidate
//Disable redrawing.
pListBox->SetRedraw (FALSE)
//Fill in the list box gere
//Enable drwing and make sure list box is redrawn.
pListBox->SetRedraw (TRUE)
pListBox->Invalidate ()
50如何向编辑控件中添加文本
由于没有CEdit:: AppendText函数,用只好自己做此工作。CEdit:: SetSel编辑控件末尾,然后CEdit:: ReplaceSel添加文本。下例是AppendText 的一种实现方法:
void CMyEdit:: AppendText (LPCSTR pText)
{
int nLen=GetWindowTextLength ()
SetFocus ()
SetSel (nLen, nLen)
ReplaceSel (pText)
}
51如何访问预GDI
可以通过调CDC:: SlectStockObject使用Windows的几个象,如刷子、笔以及字体。下例使用了Windows的笔和刷子GDI象在窗中画一个椭圆
//Draw ellipse using stock black pen and gray brush.
void CSampleView:: OnDraw (CDC* pDC)
{
//Determine size of view.
CRect rcView
GetClientRect (rcView)
//Use stock black pen and stock gray brush to draw ellipse.
pDC->SelectStockObject (BLACK_PEN)
pDC->SelectStockObject (GRAY_BRUSH)
//Draw the ellipse.
pDC->Ellipse (reView)
}
也可以用新的SDK函数GetSysColorBrush取一个系统颜色刷子,下例用背景色在窗中画一个椭圆
void CsampleView:: OnDraw (CDC* pDC)
{
//Determine size of view.
CRect rcView
GetClientRect (rcView)
//Use background color for tooltips brush.
CBrush * pOrgBrush=pDC->SelectObject ( CBrush ::FromHandle( ::GetSysColorBrush (COLOR_INFOBK)))
//Draw the ellipse.
pDC->Ellipse (rcView)

//Restore original brush.
pDC->SelectObject (pOrgBrush)
}
52如何GDI象的属性信息
可以GDIObject:: GetObject个函数将指定设备的消息写入到冲区。下例建了几个有用的助函数。
//Determine if font is bold.
BOOL IsFontBold (const CFont&font)
{
LOGFONT stFont
font.GetObject (sizeof (LOGFONT), &stFont)
return (stFont.lfBold)? TRUE: FALSE
}
//Return the size of a bitmap.
CSize GetBitmapSize (const CBitmap&bitmap)
{
BITMAP stBitmap
bitmap.GetObject (sizeof (BITMAP), &stBitmap)
return CSize (stBitmap.bmWidth, stBitmap.bmHeight)
}
//Create a pen with the same color as a brush.
BOOL CreatePenFromBrush (Cpen&pen, cost Cbrush&brush)
{
LOGBRUSH stBrush
brush.Getobject (sizeof (LOGBRUSH), &stBrush)
return pen. Createpen (PS_SOLID, 0, stBrush.ibColor)
}
53如何实现一个橡皮区矩形
CRectTracker是一个很有用的,可以通过调CRectTracker::TrackRubberBand WM_LBUTTONDOWN消息来建一个橡皮区矩形。
下例表明使用CRectTracker和重置窗中的椭圆的大小是很容易的事情。
首先,在文件档中声明一个CRectTracker数据成
class CSampleView : Public CView
{

public :
CrectTracker m_tracker

}
其次,在文档的构造函数中初始化CRectTracker 象:
CSampleDoc:: CSampleDOC ()
{
//Initialize tracker position, size and style.
m_tracker.m_rect.SetRect (0, 0, 10, 10)
m_tracker.m_nStyle=CRectTracker:: resizeInside | CRectTracker ::dottedLine
}
然后,在OnDraw函数中画椭圆和踪迹矩形:
void CSampleView:: OnDraw (CDC* pDC)
{
CSampleDoc* pDoc=GetDocument ()
ASSERT_VALID (pDoc)
//Select blue brush into device context.
CBrush brush (RGB (0, 0, 255))
CBrush* pOldBrush=pDC->SelectObject (&brush)
//draw ellipse in tracking rectangle.
Crect rcEllipse
pDoc->m_tracker.GetTrueRect (rcEllipse)
pDC->Ellipse (rcEllipse)
//Draw tracking rectangle.
pDoc->m_tracker.Draw (pDC)
//Select blue brush out of device context.
pDC->Selectobject (pOldBrush)
}
最后,使用ClassWizardWM_LBUTTONDOWN消息,并增加下述代段代根据鼠标击键情况可以拖放、移或者重置椭圆的大小。
void CSampleView::OnLButtonDown (UINT nFlags, CPoint point)
{
//Get pointer to document.
CSampleDoc* pDoc=GetDocument ()
ASSERT_VALID (pDoc)
//If clicked on ellipse, drag or resize it.Otherwise create a
//rubber-band rectangle nd create a new ellipse.
BOOL bResult=pDoc->m_tracker.HitTest (point)!= CRectTracker::hitNothing
//Tracker rectangle changed so update views.
if (bResult)
{
pDoc->m_tracker.Track (this,point,TRue)
pDoc->SetModifiedFlag ()
pDoc->UpdateAllViews (NULL)
}
else
pDoc->m-tracker.TrackRubberBand(this,point,TRUE)
CView:: onLButtonDown (nFlags,point)
}
54如何更新翻背景色的文本
CDC:: SetBkmodeOPAQUE用当前的背景色填充背景,或者CDC::SetBkModeTRANSPAARENT使背景保持不方法都可以置背景模式。下例置背景模式TRANSPARENT,可以两次更新串,用花色影更新文本。黑色串在色串之后,但由于置了背景模式仍然可
void CSampleView:: OnDraw (CDC* pDC)
{
//Determint size of view.
CRect rcView
GetClientRect (rcVieew)
//Create sample string to display.
CString str (_T ("Awesome Shadow Text
..."))
//Set the background mode to transparent.
pDC->SetBKMode (TRANSPARENT)
w black shadow text.
rcView.OffsetRect (1, 1)
pDc->SetTextColor (RGB (0, 0, 0))
pDC->DrawText (str, str.GetLength (), rcView, DT_SINGLELINE | DT_CENTER | DT_VCENTER)
//Draw red text.
rcView.OffsetRect (-1,-1)
pDc->SetTextColor (RGB (255, 0, 0))
pDC->DrawText (str, str.GetLength (), rcView, DT_SINGLELINE | DT_CENTER | DT_VCENTER)
}
55如何建一个具有特定点大小的字体
可以指定字体逻辑单位的大小,但有指定字体的点的大小可能会更方便一些。可以如下将字体的点转换为字体的高度:
int nHeigth=mulDiv (nPointSize, -dc.GetDeviceCaps (LOGPIXELSY), 72)
下例建了一个8点的Apial字体:

CClientDC dc (AqfxGetMainWnd ())
m_font. CreateFont (MulDiv (8, -dc.GetDeviceCaps (LOGPIXELSY), 72), 0, 0, 0, FW_NORMAL, 0, 0, 0, ANSI_CHARSET, OUT_STROKE_PRECIS, CLIP_STROKE_PRECIS, DRAFT_QUALITY, VARIABLE_PITCH | FF-SWISS,_T("Arial"))
56如何算一个串的大小
函数CDC:: Det text Extent 根据当前选择的字体算一个串的高度和度。如果使用的不是系字体而是其他字体,GetTextExtent之前将字体选进设备上下文中是很重要的,否则计算高度和将依据系字体,由此得出的果当然是不正确的。下述板程序当改标题时动态调整按的大小,按的大小由按的字体和标题的大小而定。响消息WM_SETTEXT时调OnSetText消息使用ON_MESSAE宏指令定的用自定消息。
LRESULT CMyButton:: OnSettext (WPARAM wParam, LPARAM lParam)
{
//Pass message to window procedure.
LRESULT bResult=CallWindowProc (*GetSuperWndProcAddr(), m_hWnd, GetCurrentMessage() ->message,wParam,lParam)
//Get title of push button.
CString strTitle
GetWindowText (strTitle)
//Select current font into device context.
CDC* pDC=GetDc ()
CFont*pFont=GetFont ()
CFont*pOldFont=pDC->SelectObject (pFont)
//Calculate size of title.
CSize size=pDC->GetTextExent (strTitle,strTitle.GetLength())
//Adjust the button's size based on its title.
//Add a 5-pixel border around the button.
SetWindowPos (NULL, 0, 0, size.cx+10, size.cy+10, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE)
//Clean up.
pDC->SelectFont (pOldFont)
ReleaseDC (pDC)
return bResult
}
57如何示旋文本
只要用使用TrueType或者GDI笔或字体就可以示旋文本(有些硬件设备也支持旋字体)。LOGFONT构中的ifEscapement指定了文本行和x的角度,角度的位是十分之一度而不是度,例如,ifEscapement450表示字体旋45度。确保所有的字体沿坐的同一方向旋,一定要ifEscapementCLIP_LH_ANGLES位,否,有些字体可能反向旋。下例使用了14Arial字体每间15度画一个串。
void CSampleView:: OnDraw (CDC* pDC)
{
//Determine the size of the window.
CRect rcClient
GetClientRect (rcClient)
//Create sample string.
CString str (_T ("Wheeee
...I am rotating!"))
//Draw transparent, red text.
pDC->SetBkMode (TRANSPARENT)
pDC->SetTextColor (RGB (255,0,0))
CFont font
//font object
LOGFONT stFont //font definition
//Set font attributes that will not change.
memset (&stFont, 0, sizeof (LOGFONT))
stFont.ifheight=MulDiv (14, -pDC->GetDeviceCaps(LOGPIXELSY), 72)
stFont.ifWeight=FW_NORMAL
stFont.ifClipPrecision=LCIP_LH_ANGLES
strcpy (stFont.lfFaceName, "Arial")
//Draw text at 15degree intervals.
for (int nAngle=0 nAngle<3600 nAngle+=150)
{
//Specify new angle.
stFont.lfEscapement=nAngle

//Create and select font into dc.
font.CreateFontIndirect(&stfont)
CFont* pOldFont=pDC ->SelectObject(&font)
//Draw the text.
pDC->SelectObject(pOldFont)
font.DelectObjext()
}
}
58如何正确示包含标签字符的串
GDI文本画函数需要展开标签字符,可以通过调CDC:: TabbedTextOut或者CDC:: DrawText并指定DT_EXPANDTABS志来完成。TabbedTextOut函数允指定标签位的数,下例指定20设备单位展一个标签
void CSampleView:: OnDraw (CDC* pDC)
{
CTestDoc* pDoc=GetDocument ()
ASSERT_VALID (pDoC)
CString str
str.Format (_T ("Cathy/tNorman/tOliver"))
int nTabStop=20 //tabs are every 20 pixels
pDC->TabbedtextOut (10, 10, str, 1, &nTabStop, 10)
}
59如何快速地格式化一个CString
CString:: Format函数和printf函数具有相同的参数,下例明了如何使用Format函数:
//Get size of window.
CRect rcWindow
GetWindowRect (rcWindow)
//Format message string.
CString strMessage
strMessage.Format (_T ("Window Size (%d, %d)"),
rcWindow.Width (), rcWindow.Height ())
//Display the message.
MessageBox (strmessage)
60串太长时如何在其末尾示一个省略号
CDC:: DrawText并指定DT_END_ELLIPSIS志,这样就可以用小略号取代串末尾的字符使其适合于指定的界矩形。如果要示路径信息,指定DT_END_ELLIPSIS志并省略号取代串中的字符。
void CSampleView:: OnDraw (CDC* pDC)
{
CTestDoc* pDoc=GetDocument ()
ASSERT_VALID (pDoc)
//Add ellpsis to end of string if it does not fit
pDC->Drawtext (CString ("This is a long string"), CRect (10, 10, 80, 30), DT_LEFT | DT_END_ELLIPSIS)
//Add ellpsis to middle of string if it does not fit
pDC->DrawText (AfxgetApp () ->m_pszhelpfilePath, CRect (10, 40, 200, 60), DT_LEFT | DT_PATH_ELLIPSIS)
}
61即使EnableMenuItem单项后,菜单项还处于禁止状
需要将CFrameWnd:: m_bAutomenuEnableFALSE,如果数据成员为TRUE(缺省),工作框将自地禁止没有ON_UPDATE_COMMAND_UI或者ON_COMMAND的菜单项
//Disable MFC from automatically disabling menu items.
m_bAuoMenuEnable=FALSE
//Now enable the menu item.
CMenu* pMenu=GetMenu ()
ASSERT_VALID (pMenu)
pMenu->EnableMenuItem (ID_MENU_ITEM,MF_BYCOMMAND | MF_ENABLED)
62如何添加一个菜单项
添加一个菜单项需要行下述三个步骤
首先,使用Resource Symbols对话(在View选择Resource Symbols...可以该对话)定单项IDID大于0x0F而小于0xF000
其次,CWnd::GetSystemMenu取系的指CWnd:: Appendmenu将菜单项添加到菜中。下例添加两个新的
int CMainFrame:: OnCreate (LPCREATESTRUCT lpCreateStruct)
{

//Make sure system menu item is in the right range.
ASSERT (IDM_MYSYSITEM &0xFFF0)==IDM_MYSYSITEM)
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)

}
在,选择单项时户应进检测。使用ClassWizardWM_SYSCOMMAND消息并检测nID参数:
void CMainFrame:: OnSysCommand (UINT nID,LPARAM lParam)
{
//Determine if our system menu item was selected.
if ( (nID & 0xFFF0)==IDM_MYSYSITEM)
{
//TODO-process system menu item
}
else
CMDIFrameWnd ::OnSysCommand (nID, lParam)
}
最后,一个设计良好的UI用程序当在系单项加亮在状示一个帮助信息,可以通增加一个包含系ID的串表的入口来实现
63如何确定顶层所占据的菜行数
可以通过简单的减法和除法来实现。首先,用需要算主框窗口的高度和客区;其次,从主框窗口的高度中减去客区、框界以及标题的高度;最后,除以菜单栏的高度。下例成函数是一个算主框菜所占据的行数的代码实现
int CMainFrame:: GetMenuRows ()
{
CRect rcFrame,rcClient
GetWindowRect (rcFrame)
GetClientRect (rcClient)
return (rcFrame.Height () -rcClient.Height () - :: GetSystemMetrics(SM_CYCAPTION) - (:: getSystemMetrics(SM_CYFRAME) *2)) / :: GetSystemMetrics(SM_CYMENU)
}
64在用户环境中如何确定系统显示元素的
SDK函数GetSysColor可以取一个特定示元素的色。下例明了如何在MFC函数CMainFrameWnd:: OnNcPaint函数置窗口标题颜色。
void CMiniFrameWnd:: OnNcPaint ()
{

dc.SetTextColor (:: GetSysColor (m_bActive ? COLOR_CAPTIONTEXT : COLOR_INACTIVECAPTIONTEXT))
65如何查询置系参数
Windows 3.1 SDK中介绍过SDK函数SystemParametersInfo函数可以查询置系参数,如按的重速率置、鼠迟时间图标字体以及桌面覆盖位等等。
//Create a font that is used for icon titles.
LOGFONT stFont
: SystemParametersInfo (SPIF_GETICONTITLELOGFONT, sizeof (LOGFONT), &stFont, SPIF_SENDWININICHANGE)
m_font.CreateFontIndirect (&stFont)
//Change the wallpaper to leaves.bmp.
: SystemParametersInfo (SPI_SETDESKWALLPAPER, 0, _T (" forest.bmp"), SPIF_UPDATEINIFILE)
66如何确定当前屏幕分辨率
SDK函数GetSystemMetrics函数可以索有windows示信息,标题大小、界大小以及滚动条大小等等。
//Initialize CSize object with screen size.
CSize sizeScreen (GetSystemMetrics (SM_CXSCREEN),
GetSystemMetrics (SM_CYSCREEN))
67如何使用一个Windows
CWinApp:: LoadStandardCursor送光标标识符。
BOOL CSampleDialog:: OnSetCursor (CWnd* pWnd,
UINT nHitTest, UINT
message)
{
//Display wait cursor if busy.
if (m_bBusy)
{
SetCursor (AfxGetApp () ->LoadStandardCursor (IDC_WAIT))
return TRUE
}
return CDialog:: OnSetCursor (pWnd. nHitTest,message)
}
68如何索原先的Task Manager用程序使用的任列表
原先的Task Manager用程序顶层窗口的列表。列表,窗口必、包含一个标题以及不能被其他窗口有。CWnd:: GetWindow可以顶层窗口的列表,IsWindowVisibleGetWindowTextLength以及GetOwner可以确定窗口是否应该在列表中。下例将把TaskManager窗口的标题填充到列表中。
void GetTadkList (CListBox&list)
{
CString strCaption
//Caption of window.
list.ResetContent ()
//Clear list box.
//Get first Window in window list.
ASSERT_VALID (AfxGetMainWnd ())
CWnd* pWnd=AfxGetMainWnd () ->GetWindow (GW_HWNDFIRST)
//Walk window list.
while (pWnd)
{
// I window visible, has a caption, and does not have an owner?
if (pWnd ->IsWindowVisible()
&& pWnd ->GetWindowTextLength ()
&&! pWnd ->GetOwner ())
{
//Add caption o window to list box.
pWnd ->GetWindowText (strCaption)
list.AddString (strCaption)
}
//Get next window in window list.
pWnd=pWnd ->GetWindow(GW_HWNDNEXT)
}
}
69如何确定WindowsWindows
有两个SDK函数可以完成功能。GetWindowsDirectoryGetSystemDirectory,下例明了如何使用两个函数:
TCHAR szDir [MAX_PATH]
//Get the full path of the windows directory.
: GetWindowsDirectory (szDir, MAX_PATH)
TRACE ("Windows directory %s/n", szD
ir)
//Get the full path of the windows system directory.
: GetSystemDirectory (szDir, MAX_PATH)
TRACE ("Windows system directory %s/n", szDir)
70在哪儿文件
SDK函数GetTemPath可以确定临时文件的目函数首先为临时路径检测TMP量:如果没有指定TMP检测TMP量,然后返回到当前目。下例明了如何建一个临时文件。

//get unique temporary file.
CString strFile
GetUniqueTempName (strFile)
TRY
{
//Create file and write data.Note that file is closed
//in the destructor of the CFile object.
CFile file (strFile,CFile ::modeCreate | Cfile:: modeWrite)

//write data
}
CATCH (CFileException, e)
{
//error opening file
}
END_CATCH

Void GetuniqueTempName (CString& strTempName)
{
//Get the temporary files directory.
TCHAR szTempPath [MAX_PATH]
DWORD dwResult=:: GetTempPath (MAX_PATH, szTempPath)
ASSERT (dwResult)
//Create a unique temporary file.
TCHAR szTempFile [MAX_PATH]
UINT nResult=GetTempFileName (szTempPath, _T ("~ex"),0,szTempfile)
ASSERT (nResult)
strTempName=szTempFile
}
71我怎才能建立一个等待光?
BeginWaitCursor EndWaitCursor 。要意,二 app 数,如:
    AfxGetApp()->BeginWaitCursor();
    //
要做的事
    AfxGetApp()->EndWaitCursor();
72我在MDI框架中有个 form 窗。它有个取消按,我需要当用按取消按钮时关闭form窗。我应该如何关闭该文档?
OnCloseDocument 数。
73如何访问桌面窗口
函数CWnd:: GetDesktopWindow 返回桌面窗口的指。下例明了MFC函数CFrameWnd::BeginModalStae是如何使用函数入内部窗口列表的。
void CFrameWnd::BeginModalState ()
{

//first count all windows that need to be disabled
UINT nCount=0
HWND hWnd= :: GetWindow (:: GetDesktopWindow(), GW_CHILD)
while (hWnd!=NULL)
{
if (:: IsWindowEnabled (hwnd)
&& CWnd::FromHandlePermanent (hWnd)!=NULL
&& AfxIsDescendant (pParent->m_hWnd, hWnd)
&& :: SendMessage (hWnd, WM_DISABLEMODAL, 0, 0)==0)
{
++nCount
}
hWnd=:: GetWindow (hWnd, GW_HWNDNEXT)
}
74COLORREF? 用它?
COLORREF 32-bit ,它色。你使 RGB COLORREF。例如:
    COLORREF color = RGB(0, 255, 0);
RGB
0-255 ,一色,绿色,色。在面的中, 0,所色。绿 255。所绿色。0,0,0 色,255,255,255 色。
COLORREF 示:
    CColorDialog colorDialog;
    COLORREF color;
    if( colorDialog.DoModal() == IDOK )
    {
        color = colorDialog.GetColor();
    }
使 MFC 框,它件。
75 AppWizard生的STDAFX文件是干什用的?
的。通的。
76我在我的程序中是了CDWordArray。我向它添加了10,000个整数,使得得非常非常慢。这么?
CDWordArray
的,只的最大尺寸。因此,当。不是,。如素,所使慢。解是,你使 SetSize 率。例如,如 500 500 ,而 1 个。来,你 499 度。
77如何改MDI框架窗口的子窗口的大小以使在窗口以一定的大小打?
OnInitialUpdate GetParentFrame 数。GetParentFrame 。然 MoveWindow
78在我的程序的某些部分,我可以 MessageBox 函数来建立一个信息对话框,例如在视类中。但是,在其它部分我却不能,如文档中。?我怎才能在我的用程序中建立一个信息对话框?
MessageBox
CWnd ,所 CWnd ( CView ) 它。但是,MFC AfxMessageBox 数,你它。
79我需要在我的程序中置全局量,以使文档中的所有都能访问。我应该它放到哪儿?
attribute 。然后,在方,你访量:
    CMyApp *app = (CMyApp *)AfxGetApp();
    app->MyGlobalVariable = ...
80我听MFC可以发现内存漏洞,我怎使用特性?
Debug Go ( Project Execute ) 序,MFC 洞。如有,那 MFC Tracer ( VC++ ),并踪。然序。
81我怎才能在我的用程序中循环浏览的文档?
使用CDocTemplate中未公GetFirstDocPosition()GetNextDoc()函数。
82)才能在我的用程序中循环浏览?
使 CDocument GetFirstViewPosition() GetNextView() 数。
83)数PreCreateWindow是干什用的?
PreCreateWindow CreateWindow 性。
84防止MFC在窗口标题栏上把文档名置成用程序名?
PreCreateWindow FWS_PREFIXTITLE 式:

    cs.style &= ~FWS_PREFIXTITLE;
85应该防止MFC在窗口标题栏上添加文档名?
PreCreateWindow FWS_ADDTOTITLE 式:
    cs.style &= ~FWS_ADDTOTITLE ;
86应该如何改变视窗口的大小?
口,所小,而口。使 CView GetParentFrame() ,然 MoveWindow() 小。使口。
87我有一无模式对话框。我怎才能在窗口退出时删CDialog?
“delete this” PostNcDestroy 中。合。
88“delete this”放在PostNcDestroy中而不是OnNcDestroy?
OnNcDestroy 用。如 ( PreCreateWindow ) WM_NCDESTROY 息。PostNcDestroy 除,在 OnNcDestroy 后,甚的。
89 File中的MRU列表是从哪儿来的?列表中的名字放在哪儿了?我怎才能改列表中目的最大
InitInstance LoadStdProfileSettings 中。 ( 4 )MRU INI 的。如 ID_FILE_MRU_FILE1 ID ,它 MRU 。如 LoadStdProfileSettings ( 16 )
90我在菜中添加了新的。但是,当我选该项时,在状态栏上没有出任何提示信息。?
板。打框。在 Prompt ,你 ( ):
    Status bar string/nFlying tag
91我怎才能在用程序的缺省系中加上一些西?
似,你目,使 CMenu 数。下
    CMenu *sysmenu;
    sysmenu = m_pMainWnd->GetSystemMenu(FALSE);
    sysmenu->AppendMenu(MF_STRING, 1000, "xxx");
MFC CMenu
92我建立了一个对话框。但是当我该对话,第一个编辑是不能得焦点,我必须单击它来使它得焦点。我怎才能使第一个编辑框在对话框打开时得焦点?
板。在 Layout Tab Order 。按 tab 序。
93我怎才能使一个窗口具有“always on top”特性?
OnFileNew 后,在 InitInstance
m_pMainWnd->SetWindowPos(&CWnd::wndTopMost,0,0,0,0, SWP_NOMOVE | SWP_NOSIZE);
(94)   我要我的form view添加文档模板。我先建立了对话框模板,然后使用ClassWizard建立了基于CFormView的新,它也是从CDocument承来的。我建立了相源并在InitInstance中添加了新的文档模板。但是,当我试图运行程序,出Assertion信息。?
form 便 CFromView。确使 AppWizard CFormView 序,并 AppWizard Styles Properties。你式:没、不“Child”。把 form view 了。
(95)   我在一对话框中有一列表框,我需要tabbed列表框中的目。但是,当我理含有tab字符(AddString添加的)的列表项时tab示成小黑而没有展。哪儿出?
中,打性。确“Use Tabstops” 式。然后,确 OnInitDialog SetTabStops
(96)  
我建立了一个用程序,并使用了CRecordset。但是,当我运行程序,它试图访问数据,并“Internal Application Error”对话框。我应该?
下,当 SQL 框。例如,参子:
    set.m_strFilter = "(ZipCode = '27111')";
ZipCode ,如 long“Internal Application Error”框,故。如 27111 号,。当“Internal Application Error”,最 SQL 句。
(97)  
我用ClassWizard建立了一个。但是,我把名字取了,我想把它从目中除,应该如何做?
ClassWizard 后,用 H CPP 件。然 ClassWizard,它件,并做。你
(98)     当我打开应用程序中的窗口,我要传递该窗口的矩形尺寸。矩形指定了窗口的外大小,但是当我GetClientRect,所得到的尺寸要比所希望的要小(工具和窗口框的)。有其它方法来算窗口的尺寸?
CWnd::CalcWindowRect
(99)   我在文档置了一个整型量。但是,当我试图该变量写入Serialize函数中的archive文件中,出错误。而文档中的其它量没有问题?
archive >> << 符。“int”中,也 int Windows 3.1 Windows NT/95 吧。“long”持,所 int long 型。参 MFC CArchive
(100)  如何控制菜的大小?
我用MFCCMenu生成了一个动态(例如File,Edit,View...Help), 我想控制个菜的大小(+).
方法一: WM_MEASUREITEM MEASUREITEMSTRUCT.
方法二:查询::GetSystemMetric(SM_CXMENUSIZE).
     /* 你可以通如下代得文本的大小:
        (A)
得被使用的字体 */
       NONCLIENTMETRICS ncm;
     HFONT hFontMenu;
     SIZE size;
     size.cy = size.cy = 0;
     memset(&ncm, 0, sizeof(NONCLIENTMETRICS));
     ncm.cbSize = sizeof(NONCLIENTMETRICS);
     if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0))
     {
          hFontMenu = CreateFontIndirect(&ncm.lfMenuFont);
          /*
          (B)
得菜单项的文本: */
          char szText[_MAX_PATH];
          pMenu->GetMenuString(0, szText, _MAX_PATH, MF_BYPOSITION);
          /*
          
然后,得菜单项文本的高度: */
          HFONT hFontOld;
          HDC hDC;
          hDC = ::GetDC(NULL);
          hFontOld = (HFONT) ::SelectObject(hDC, hFontMenu);
          GetTextExtentPoint32(hDC, szText, lstrlen(szText), &size);
          SelectObject(hDC, hFontOld);
          ::ReleaseDC(NULL, hDC);
     }
     /*
,size.cy高度,size.cx为宽,你可以加上自定的高度和,,发现宽4
合适。*/
(101)  LVIS_SELECTED的状态颜?
我想将CListCtrlCTreeCtrlLVIS_SELECTED态时.
方法一:找函数CustomDraw,它是IE4提供的公共控制,有你自己的代.
方法二:生成一个draw控件,然后在DrawItem理文本.
(102)   如何只存文档的某一部分?
我只想存文档的某一部分,能否象使用文件一使用文档?(也就是有定位函数).CArchive类设CFile的派生,这样你就能使用Seek等成函数.
(103)   保存工具条菜bug?
使用浮,SaveBarStateLoadBarState问题.如果菜是浮,重起用程序它会出在左上角,而它固定在屏幕其它位置,下一次启就会出位置,是什原因?试试这PToolBar->Create(this,...,ID_MYTOOLBAR);
你的工具条需要包括id,而不是象默的工具条那.
(104)   Tip of the daybug
建了一个简单mdi用程序,使用.BSF(自定的文档展名)它的文档我保存一个foo.bsf文档后,可以在源管理器中双击该文件打mdi用程序同foo.bsf文档.但当我mdi用程序加上a tip of the day件之后,源管理器中双foo.bsf,就会我一个警告:ASSERT(::IsWindow(m_hWnd)),然后mdi用程序就死那了.
当从dde动应用程序(例如:文档),"Tip of the Day"是有bug.你可以看看函数"ShowTipAtStartup",它在"InitInstance",可以看到tip of the day一个模式对话,理其它消息它一直行消息循你可心修改ShowTipAtStartup使其从dde动时不出tip of the day.
void CTipOfApp::ShowTipAtStartup(void)
        {
                // CG: This function added by 'Tip of the Day' component.
                CCommandLineInfo cmdInfo;
                ParseCommandLine(cmdInfo);
                if (
                        cmdInfo.m_bShowSplash &&
                        cmdInfo.m_nShellCommand != CCommandLineInf:FileDDE
                        )
                {
                        CTipDlg dlg;
                        if (dlg.m_bStartup)
                                dlg.DoModal();
                }
        }
如果有其它bug,你可以cmdInfo.m_nShellCommand过滤.
(105)  
如何可以我的程序可以示在其它的窗口上面?
户选择"是在最上面"最好是在系里加入一个选项.可以通修改WM_SYSCOMMAND消息来送用选择.的命令标识(id)会作一个参数传给OnSysCommand().要定义标识(id),将如下代加入到CMainFrame.CPP:
    #define WM_ALWAYSONTOP WM_USER + 1
"在最上面"的菜单项加入到系,将如下代加入到函数CMainFrame::OnCreate():
      CMenu* pSysMenu = GetSystemMenu(FALSE);
      pSysMenu->AppendMenu(MF_SEPARATOR);
      pSysMenu->AppendMenu(MF_STRING, WM_ALWAYSONTOP,
                     "&Always On Top");
使用ClassWizard,加入WM_SYSCOMMAND消息的,应该消息过滤,使用系可以个消息.
void CMainFrame::OnSysCommand(UINT nID, LPARAM lParam)
{
    switch ( nID )
    {
    case WM_ALWAYSONTOP:
        if ( GetExStyle() & WS_EX_TOPMOST )
        {
            SetWindowPos(&wndNoTopMost, 0, 0, 0, 0,
                SWP_NOSIZE | SWP_NOMOVE);
            GetSystemMenu(FALSE)->CheckMenuItem(WM_ALWAYSONTOP,
                MF_UNCHECKED);
        }
        else
        {
            SetWindowPos(&wndTopMost, 0, 0, 0, 0,
                SWP_NOSIZE | SWP_NOMOVE);
            GetSystemMenu(FALSE)->CheckMenuItem(WM_ALWAYSONTOP,MF_CHECKED);
        }
        break;
    default:
        CFrameWnd::OnSysCommand(nID, lParam);
    }
}

(106)    
如何控制窗口框架的最大最小尺寸?
要控制一个框架的的最大最小尺寸,你需要做两件事情.CFrameWnd理消息WM_GETMINMAXINFO,MINMAXINFO置了整个窗口的限制,因此住要考工具条,条等等的大小.
//
最大最小尺寸的象素点 - 示例
#define MINX 200
#define MINY 300
#define MAXX 300
#define MAXY 400

void CMyFrameWnd::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI)
{
    CRect rectWindow;
    GetWindowRect(&rectWindow);
    CRect rectClient;
    GetClientRect(&rectClient);
      // get offset of toolbars, scrollbars, etc.
    int nWidthOffset = rectWindow.Width() - rectClient.Width();
    int nHeightOffset = rectWindow.Height() - rectClient.Height();
    lpMMI->ptMinTrackSize.x = MINX + nWidthOffset;
    lpMMI->ptMinTrackSize.y = MINY + nHeightOffset;
    lpMMI->ptMaxTrackSize.x = MAXX + nWidthOffset;
    lpMMI->ptMaxTrackSize.y = MAXY + nHeightOffset;
}
第二,CFrameWndPreCreateWindow函数中去掉WS_MAXIMIZEBOX消息,在最大化你将得不到料的.

BOOL CMyFrameWnd::PreCreateWindow(CREATESTRUCT& cs)
{
    cs.style &= ~WS_MAXIMIZEBOX;
    return CFrameWnd::PreCreateWindow(cs);
}

(107)    
如何改窗口框架的?
MDI框架的客区被另一个窗口的框架所覆盖.了改区的背景色,你需要重画个客窗口.了做到,你要理消息WM_ERASEBKND生一个新,CWnd,姑且称之CMDIClient.它加上一个成员变,
#include "MDIClient.h"
class CMainFrame : public CMDIFrameWnd
{
...
protected:
CMDIClient m_wndMDIClient;
}
CMainFrame中重CMDIFrameWnd::OnCreateClient
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
    if ( CMDIFrameWnd::OnCreateClient(lpcs, pContext) )
    {
        m_wndMDIClient.SubclassWindow(m_hWndMDIClient);
        return TRUE;
    }
    else
        return FALSE;
}
然后就可以加入消息WM_ERASEBKGND理了.

(108)    
如何将用程序窗口置于屏幕正中?
要将你的用程序窗口放置在屏幕正中央,MainFrameOnCreate函数中加入:
CenterWindow( GetDesktopWindow() );


原创粉丝点击