MFC編輯框中按下回車後使游標換行
阿新 • • 發佈:2019-01-10
MFC編輯框中輸入字元,按下回車,發現游標並沒有按照想象的另起一行,需要手動截獲回車按鍵並新增對應的換行處理。
Dialog對話方塊中截獲訊息可以覆蓋父類的PreTranslateMessage方法,故實現方法如下例所示(編輯軟體是VS2010):
BOOL CTestDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
// 判斷是否按下鍵盤Enter鍵
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN)
{
// 獲取當前的焦點是否是Edit編輯框
if (GetFocus() == GetDlgItem(IDC_EDIT_DEBUGAT))
{
/*
* m_edit_debugat和m_str_debugat分別是
* IDC_EDIT_DEBUGAT所對應控制元件相關的類變數:
* CEdit m_edit_debugat;
* CString m_str_debugat;
*/
m_edit_debugat.GetWindowTextA(m_str_debugat);
// 給顯示字串添加回車和換行
m_str_debugat += "\r\n";
m_edit_debugat.SetWindowTextA(m_str_debugat);
int len = m_str_debugat.GetLength();
// 設定游標位置
// 第一個引數是顯示字串選中部分的起始位置
// 第二個引數是顯示字串選中部分的結束位置
// 兩個引數相等,代表不選中任何字元,游標指向對應字元處
m_edit_debugat.SetSel(len, len);
}
return TRUE;
}
return CDialog::PreTranslateMessage(pMsg);
}