• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 392
  • Last Modified:

Visible lines in a RichEditCtrl

How do you find out which lines are visible in a richedit contol.
I've seen CRichEditCtrl::GetFirstVisibleLine() but where can I get the rest of the information ?
  • 2
1 Solution
void COpenerDlg::OnButton1()
   // obviously, need a pointer to the control
   CRichEditCtrl* pCtrl = (CRichEditCtrl*) GetDlgItem(IDC_RICHEDIT1);
   ASSERT(pCtrl != NULL);

   // get the dimensions of the control
   CRect rect;

   // find the position of the character closest to the bottom right of the control
   POINTL pt;
   pt.x = rect.right;
   pt.y = rect.bottom - 10;   //FUDGE FACTOR!!
   LRESULT l = pCtrl->SendMessage(EM_CHARFROMPOS, 0, (LPARAM) &pt);

   // decompress the result
   int nLastChar = LOWORD(l);

   // get the top visible line
   int nTopChar = pCtrl->LineIndex(pCtrl->GetFirstVisibleLine());
   ASSERT(nTopChar <= nLastChar);

   // get the text from nTopChar to nLastChar
   CString str;

   TEXTRANGE textRange;
   textRange.chrg.cpMin = nTopChar;
   textRange.chrg.cpMax = nLastChar;
   textRange.lpstrText = str.GetBuffer(nLastChar - nTopChar + 2);
   pCtrl->SendMessage(EM_GETTEXTRANGE, 0, (LPARAM) &textRange);



Note the fudge factor in converting the rectangle. The EM_CHARFROMPOS code gets the "character nearest the point", so you might get an extra line at the end depending on the size of your window, the length of the last visible line, and the height of the font.

The EM_CHARFROMPOS message is your only hope, so you have to make it work...  If you need the function to be super-reliable, you can call EM_POSFROMCHAR on the best-guess index and work backward until you're completely sure the character you're considering to be the last really is visible.

B ekiM

BridgeAuthor Commented:
I am using a CRichEditView. Whenever I try to do a SendMessage( EM_CHARFROMPOS, ...) I get and access violation in the RTF DLL. It makes no difference if I send the message to the view or the underlying control.
Any ideas ??
That's caused by a bug in the system headers.  See Knowledge Base articles Q137805, Q137249, and Q68572 for the official workarounds.

Also, try using a POINT structure instead of a POINTL structure, as I did above.

B ekiM


Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now