Search code examples
delphiricheditscrollbars

How to use TScrollbar to richedit;


How to use Tscrollbar to Richedit.

My purpose is to separate the scrollbar in a deferent panel.

is it possible?


Solution

  • You can try this:

    procedure TForm1.ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
    var
      WParam: longint;
    
    begin
      case ScrollCode of
        scLineUp: WParam := SB_LINEUP;
        scLineDown: WParam := SB_LINEDOWN;
        scPageUp: WParam := SB_PAGEUP;
        scPageDown: WParam := SB_PAGEDOWN;
        scEndScroll: WParam := SB_ENDSCROLL;
        scPosition: WParam := SB_THUMBPOSITION;
        scTrack: WParam := SB_THUMBTRACK;
        else
          exit;
      end;
      WParam := WParam or word(ScrollPos) shl 16;
    
      RichEdit1.Perform(WM_VSCROLL, WParam, 0);
    end;
    
    procedure TForm1.RichEdit1Change(Sender: TObject);
    var
      ScrollInfo: TScrollInfo;
    
    begin
      FillChar(ScrollInfo, SizeOF(ScrollInfo), 0);
      ScrollInfo.cbSize := SizeOf(ScrollInfo);
      ScrollInfo.fMask := SIF_RANGE or SIF_PAGE or SIF_POS;
      if GetScrollInfo(RichEdit1.Handle, SB_VERT, ScrollInfo) then
      begin
        ScrollBar1.Max := ScrollInfo.nMax;
        ScrollBar1.Min := ScrollInfo.nMin;
        ScrollBar1.PageSize := ScrollInfo.nPage;
        ScrollBar1.Position := ScrollInfo.nPos;
      end;
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      RichEdit1Change(self);
    end;
    

    It synchronizes Scrollbar1: TScrollBar with the scroll info of the RichEdit upon any change in it and simulates WM_VSCROLL messages coming from the scrollbar. However, it requires the RichEdit to have its own vertical scrollbar visible, because the scroll info is not updated, if it is not visible.

    There is AFAIK no other way to get the scroll data, simply because the RichEdit control doesn't create them if not needed (ssNone in ScrollBars property).