获取和设置对话框控件标题或内容的相关方法介绍:
0)先来看一个获取窗口中指定控件或子窗口指针的函数CWnd::GetDlgItem:
CWnd* GetDlgItem(
int nID //控件或子窗口的ID
) const;
void GetDlgItem(
int nID, //控件或子窗口的ID
HWND* phWnd //指向子窗口的指针
) const;
“返回值”是指向控件或子窗口的指针,如果指定nID控件不存在,返回值是NULL;
要注意的是:返回的指针可能是临时的,因此不能存下来以待后面使用。我们通常会将返回的指针转换为nID指向控件的类型。例如:
// uses GetDlgItem to return a pointer to a user interface control
CEdit* pBoxOne;
pBoxOne = (CEdit*)GetDlgItem(IDC_ASCEEDIT);
GotoDlgCtrl(pBoxOne);
1)CWnd::GetWindowText函数实现获取CWnd的标题内容,或者当CWnd对象是一个控件时,函数将获取控件中文本内容而不是标题内容;函数原型如下:
int GetWindowText(
LPTSTR lpszStringBuf, //接收返回的内容的缓冲区
int nMaxCount //复制到缓冲区的最大字符个数
) const;
void GetWindowText(
CString& rString //接收返回的内容的CString对象
) const;
第一个函数的返回值是复制的字符个数,不包括null结束符;当CWnd没有标题或标题为空时返回0。
该成员函数使得WM_GETTEXT消息发送给CWnd对象。
CWnd::SetWindowText函数实现设置CWnd对象的标题内容,而当CWnd对象是一个控件时,函数将设置控件中文本内容,函数原型如下:
void SetWindowText(
LPCTSTR lpszString
);
实例代码如下:
// set the text in IDC_EDITNAME
CWnd* pWnd = GetDlgItem(IDC_EDITNAME);
pWnd->SetWindowText(_T("Gerald Samper"));
// Get the text back. CString is convenient, because MFC
// will automatically allocate enough memory to hold the
// text--no matter how large it is.
CString str;
pWnd->GetWindowText(str);
ASSERT(str == _T("Gerald Samper"));
// The LPTSTR override works, too, but it might be too short.
// If we supply a buffer that's too small, we'll only get those
// characters that fit.
TCHAR sz[10];
int nRet = pWnd->GetWindowText(sz, 10);
// Nine characters, plus terminating null
ASSERT(_tcscmp(sz, _T("Gerald Sa")) == 0);
ASSERT(nRet == 9);
// You can query the length of the text without the length of
// the string using CWnd::GetWindowTextLength()
nRet = pWnd->GetWindowTextLength();
ASSERT(nRet == 13);
2)CWnd::GetDlgItemText函数用来返回对话框中指定ID的控件上的文本,也就是说,GetDlgItemText函数将GetDlgItem和GetWindowText这两个函数的功能组合起来了:
int GetDlgItemText(
int nID, //控件的ID
LPTSTR lpStr, //指向接收控件标题或文本的缓冲区的指针
int nMaxCount //复制到缓冲区的最大字符个数
) const;
int GetDlgItemText(
int nID, //控件ID
CString& rString //接收控件标题或文本内容
) const;
函数返回值是实际复制到缓冲区的字符个数,不包括null结束符;当没有复制任何东西时,返回0。
CWnd::SetDlgItemText函数用来设置对话框中指定控件的标题或文本:
void SetDlgItemText(
int nID, //控件ID
LPCTSTR lpszString //要设置的内容
);
该函数将发送一个WM_SETTEXT消息给指定的控件。
3)CWnd::GetDlgItemInt函数用来获取指定控件的文本,并将其转换为一个整型数值:
UINT GetDlgItemInt(
int nID, //控件ID
BOOL* lpTrans = NULL, //指向一个布尔型变量,该变量接收转换成功与否标志
BOOL bSigned = TRUE //指定被检索的值是否有符号
) const;