1、初始化Init(),需要new五个编辑框,并保存到数组。
void CCTimeTestDlg::Init()
{
for (int i = 0; i < 5; i++)
{
CEdit *p = new CEdit;
p->Create(WS_CHILD | WS_VISIBLE | ES_LEFT, CRect(100, 50 * (i + 1), 200, 50 * (i + 1) + 20), this, i + 1);
p->SetWindowText("123456");
m_arrEdit.push_back(p);
}
SetCursorPos();
}
2、OnInitDialog()需要返回false。
// TODO: 在此添加额外的初始化代码
Init();
return FALSE; // 除非将焦点设置到控件,否则返回 TRUE
3、设置光标位置到文本最后。
void CCTimeTestDlg::SetCursorPos()
{
CString str;
m_arrEdit[0]->GetWindowText(str);
int nLength = str.GetLength();
m_arrEdit[0]->SetSel(nLength, nLength, FALSE);
m_arrEdit[0]->SetFocus();
}
4、Tab键切换光标所在编辑框。
BOOL CCTimeTestDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam == VK_TAB)
{
int nCount = m_arrEdit.size();
CWnd* pWnd = GetFocus();
int focusID = pWnd->GetDlgCtrlID();
CString str;
if (focusID < nCount)
{
m_arrEdit[focusID]->GetWindowText(str);
int nLength = str.GetLength();
m_arrEdit[focusID]->SetSel(nLength, nLength, FALSE);
m_arrEdit[focusID]->SetFocus();
}
else if (focusID == nCount)
{
focusID = 0;
m_arrEdit[focusID]->GetWindowText(str);
int nLength = str.GetLength();
m_arrEdit[focusID]->SetSel(nLength, nLength, FALSE);
m_arrEdit[focusID]->SetFocus();
}
return TRUE;
}
}
return CDialogEx::PreTranslateMessage(pMsg);
}
5、响应消息WM_DESTROY,析构对象。
void CCTimeTestDlg::DestroyItem()
{
for (int i = 0; i < m_arrEdit.size();i++)
{
CEdit *p = m_arrEdit[i];
if (p)
delete p;
m_arrEdit[i] = NULL;
}
m_arrEdit.clear();
}
void CCTimeTestDlg::OnDestroy()
{
CDialogEx::OnDestroy();
DestroyItem();
}
运行: