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

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_AUTOHSCROLL WS_HSCROLL 格位, 由于 CEditView : : PreCreateWindow cs. 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 如何使程序保持极小状 ?
这么办 : 在恢 程序窗体大小 Windows WM_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: : GetDescendantWindow AfxGetMainWnd 些子窗口的指
//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 : : GetBarStyle CControlBar : : 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 : : OnOK CDialog : : OnCancel EndDialog , 所以需要 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: : GetDescendantWindow AfxGetMainWnd 些子窗口的指
//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: : GetDescendantWindow AfxGetMainWnd 些子窗口的指
//Get pointer to status bar .
CStatusBar * pStatusBar = (CStatusBar *) AfxGetMainWnd ( )
—> GetDescendantWindow(AFX_IDW_STUTUS_BAR)
32 如何使能和禁止工具条的工具提示
如果 置了 CBRS_TOOLTIPS 格位,工具条将 示工具提示,要使能或者禁止工具提示,需要 置或者清除 该风 格位。下例通 过调 CControlBar : : GetBarStyle CControlBar : : 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) )
}
最后,使用 ClassWizard WM_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 ,要保 在控件撤消之前不能撤消字体 象。下例将下 的字体改 8 Arial 字体:
//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 : : GetFortColor COleControl : : 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: : DlgDirListComboBox Windows 将自 地向列表框或 合框填充可用的 驱动 器名或者指定目 中的文件,下例将 Windows 中的文件填充在 合框中:
BOOL CSampleDig : : OnInitDialog ( )
{
CDialog : : OnInitDialog ( )
TCHAR szPath [MAX_PATH] = {"c://windows"}
int nReslt = DlgDirListComboBox (szPath, IDC_COMBO , IDC_CURIDIR, DDL_READWRITE
DDL_READONLY DDL_HIDDEN DDL_SYSTEM DDL_ARCHIVE)
return TRUE
}
42 控件看起来倒
需要 CSpinCtrl : : SetRange 置旋 控件的范 ,旋 控件的缺省上限 0 ,缺省下限 100 意味着增加 按控件的 100 变为 0 。下例将旋 控件的范 围设 0 100
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_BITMAP BS_ICON ,要想具有位 建按 CButton : : SetBitmap CButton : : SetIcon 要指定 BS_BITMAP BS_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 定制控件自己 理字符,可以派生一个 CEdit WM_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)

}
使用 ClassWizard WM_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 )
}
如果要修改字符, 不能 仅仅简单 地用修改 nChar CEdit: : OnChar ,然后 CEdit: : OnChar CWnd: : Default 取原来的 wParam lParam 这样 是不行的。要修改一个字符,需要首先修改 nChar ,然后用修改 nChar CWnd: : 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)
}
最后,使用 ClassWizard WM_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:: SetBkmode OPAQUE 用当前的背景 色填充背景,或者 CDC::SetBkMode TRANSPAARENT 使背景保持不 方法都可以 置背景模式。下例 置背景模式 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 的角度,角度的 位是十分之一度而不是度,例如, ifEscapement 450 表示字体旋 45 度。 确保所有的字体沿坐 的同一方向旋 ,一定要 ifEscapement CLIP_LH_ANGLES 位,否 ,有些字体可能反向旋 。下例使用了 14 Arial 字体 每间 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_bAutomenuEnable FALSE ,如果 数据成 员为 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 ...可以 该对话 )定 单项 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 &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)

}
在, 选择 单项时 户应进 检测 。使用 ClassWizard WM_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), &s tFont, 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 可以 顶层 窗口的列表, IsWindowVisible GetWindowTextLength 以及 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 如何确定 Windows Windows
有两个 SDK 函数可以完成 功能。 GetWindowsDirectory GetSystemDirectory ,下例 明了如何使用 两个函数:
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)
}
74 COLORREF? 用它 ?
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)   如何控制菜 的大小 ?
我用 MFC CMenu 生成了一个 动态 ( 例如 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 的状 态颜 ?
我想将 CListCtrl CTreeCtrl LVIS_SELECTED 态时 .
方法一 : 找函数 CustomDraw, 它是 IE4 提供的公共控制 , 有你自己的代 .
方法二 : 生成一个 draw 控件 , 然后在 DrawItem 理文本 .
(102)   如何只存 文档的某一部分 ?
我只想存 文档的某一部分 , 能否象使用文件一 使用文档 ?( 也就是有定位函数 ). CArchive 类设 CFile 的派生 , 这样 你就能使用 Seek 等成 函数 .
(103)   保存工具条菜 bug ?
使用浮 ,SaveBarState LoadBarState 问题 . 如果菜 是浮 , 重起 用程序 它会出 在左上角 , 而它固定在屏幕其它位置 , 下一次启 就会出 位置 , 是什 原因 ? 试试这 PToolBar->Create(this,...,ID_MYTOOLBAR);
你的工具条需要包括 id, 而不是象默 的工具条那 .
(104)   Tip of the day bug
建了一个 简单 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;
}
第二 , CFrameWnd PreCreateWindow 函数中去掉 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)    
如何将 用程序窗口置于屏幕正中 ?
要将你的 用程序窗口放置在屏幕正中央 , MainFrame OnCreate 函数中加入 :
CenterWindow( GetDesktopWindow() );


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值