Search for a string in a Multi-line Edit Box
Searching for a string in a multi line edit box might be useful sometimes. I have coded this feature in a dialog based application. Left site edit box is a multi line edit box which supports more functionality then default edit box such as TAB and RETURN operations. To find a string in this text box, type your string in the right side text box and click Find It. Result will be in the form of line number of the text box.
Here is the code segment I have written. I have used CEdit's class's functions to do so. GetLineCount() returns total number of lines in a multi line text box. GetLine() returns text for an entire line.
int i, nLineCount = m_EditCtrl.GetLineCount();
CString strText, strLine;
GetDlgItemText( IDC_FIND, m_strFind );
// Dump every line of text of the edit control.
for (i=0;i < nLineCount;i++)
{
m_EditCtrl.GetLine(i, strText.GetBuffer(m_EditCtrl.LineLength(i)));
strText.ReleaseBuffer();
strLine.Format(TEXT("line %d: '%s'\r\n"), i, strText.GetBuffer(0));
if ( strLine.Find(m_strFind) != -1)
{
CString str;
str.Format("%d", i );
SetDlgItemText( IDC_FOUND, str );
UpdateData(TRUE);
break;
}
}
To provide TAB and return functionality, I have overridden PreTranslageMessage of the dialog class.
if ((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_TAB))
{
int nPos = LOWORD(m_EditCtrl.CharFromPos(m_EditCtrl.GetCaretPos()));
m_EditCtrl.SetSel(nPos, nPos);
m_EditCtrl.ReplaceSel("\t", TRUE);
return TRUE;
}
if ( pMsg->wParam == VK_RETURN )
{
int nPos = LOWORD(m_EditCtrl.CharFromPos(m_EditCtrl.GetCaretPos()));
m_EditCtrl.SetSel(nPos, nPos);
m_EditCtrl.ReplaceSel("\r\n", TRUE);
return TRUE;
}