Search code examples
delphidelphi-7delphi-2010

How to get the bottom coordinate of visible items inTRichView?


I am working on one project where I need the pixel of Last visible item in the TRichview.

By using 'LastVisibleItem' Property of TRichView I am able to find the Item Start Cordinate.

but the Problem is I need a pixel value of very last visible word.

Can any one tell me how I can get that?

Thanks in advance.


Solution

  • I'm a bit unsure how your LastVisibleItem property works. Below is a suggested solution to get the top-right coordinate of the last visible character. Hope it works for you.

    //Function GetCharPos source: http://www.delphipages.com/forum/showthread.php?t=33707
    function GetCharPos(AOwner : TControl; Index : LongInt) : TPoint;
    var
      p : TPoint;
    begin
      AOwner.Perform(EM_POSFROMCHAR,WPARAM(@p),Index);
      Result := p;
    end;
    
    //Inspired by: http://www.swissdelphicenter.ch/en/showcode.php?id=1213
    function GetLastVisibleCharIndex(AOwner : TControl):integer;
    var
      r: TRect;
    begin
      //The EM_GETRECT message retrieves the formatting rectangle of an edit control.
      AOwner.Perform(EM_GETRECT, 0, Longint(@r));
      r.Right := r.Right - 1;
      r.Bottom := r.Bottom - 2;
      //The EM_CHARFROMPOS message retrieves information about the character closest to a specified point in the client area of an edit control
      result := AOwner.Perform(EM_CHARFROMPOS, 0, Integer(@r.BottomRight));
    end;
    
    //Get the Top-Right coordinate of the last visible character
    function GetLastVisibleCharPos(AOwner : TControl):TPoint;
    var Index : integer;
    begin
      index := GetLastVisibleCharIndex(AOwner);
      result := GetCharPos(AOwner, index);
    end;
    

    Example usage:

    procedure TForm2.Button3Click(Sender: TObject);
    var
      p : TPoint;
    begin
      p := GetLastVisibleCharPos(RichEdit1);
    
      DrawCrossHair(p); //Help visualize the point
    end;
    
    //Helper proc to draw a cross-hair
    procedure TForm2.DrawCrossHair(p : TPoint);
    var
      aCanvas: Tcanvas;
      X, Y: Integer;
    begin
    
      aCanvas := TCanvas.Create;
      Y := RichEdit1.Height;
      X := RichEdit1.Width;
      try
        aCanvas.Handle := GetDC(RichEdit1.Handle);
        aCanvas.Font := RichEdit1.Font;
    
        aCanvas.Pen.color := clGreen; // Color of line
    
        //Draw vertical line
        aCanvas.MoveTo(p.x, 0);
        aCanvas.LineTo(p.x, Y);
    
        //Draw horizontal line
        aCanvas.MoveTo(0, p.Y);
        aCanvas.LineTo(x, p.y);
      finally
        ReleaseDC(RichEdit1.Handle, aCanvas.Handle);
        aCanvas.Free;
      end;
    end;