Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Visual C++ and MFC Fundamentals Chapter 17: Track-Based Controls


If the user wants to change the text of an edit box and if the control allows changes, he or
she must first click in the control, which places a caret in the edit box. The caret is a
blinking I beam that serves as a reminder that lets the user know what edit control would
receive any change made. This means that if the user starts typing, the edit control in
which the caret is positioned would display a change in its value. The edit box that has
the caret is said to have focus. As mentioned already, the user gives focus to an edit box
by clicking it. Remember that if a label that accompanies an edit box has an access key,
the user can also give focus to the edit control by pressing the access key. Also remember
that you can programmatically give focus to an edit control by calling the SetFocus()
method.

At any time, you can find out what text is in an edit control and there are various
techniques you can use. We saw already how to get a handle to a control by calling the
CWnd::GetDlgItem() method. After calling this method, you can use the
CWnd::GetWindowText() method to find out what text an edit box holds. Here is an
example:

void CEditBoxDlg::CreateName()
{
CEdit *edtFirstName, *edtLastName, *edtFullName;
CString FirstName, LastName;
char FullName[40];

edtFirstName = reinterpret_cast<CEdit *>(GetDlgItem(IDC_FIRST_NAME));
edtLastName = reinterpret_cast<CEdit *>(GetDlgItem(IDC_LAST_NAME));
edtFullName = reinterpret_cast<CEdit *>(GetDlgItem(IDC_FULL_NAME));

edtFirstName->GetWindowText(FirstName);
edtLastName->GetWindowText(LastName);

sprintf(FullName, "%s %s", FirstName, LastName);
edtFullName->SetWindowText(FullName);
}
void CEditBoxDlg::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CreateName();

CDialog::OnLButtonDblClk(nFlags, point);
}

Another technique you can use to get the text of an edit control consists of calling the
CWnd::GetDlgItemText() method. It is provided in two syntaxes as follows:

int GetDlgItemText( int nID, LPTSTR lpStr, int nMaxCount ) const;
int GetDlgItemText( int nID, CString& rString ) const;
Free download pdf