Author: Noffen Dopp
Is it possible to read the actual position of a scrollbar from a richedit-component?
Answer:
Solve 1:
YES, you can get the position of the scroll bar, by several ways. Here is some code
that gets the scroll bar position for a RichEdit. I also subclass the RichRdit to
get the WM_VSCROLL message and move the Claret to the top line plus one character
private
1 { Private declarations }
2 PRichEdWndProc, POldWndProc: Pointer;
3
4 procedure RichEdWndProc(var Msg: TMessage);
5
6 procedure TForm1.FormCreate(Sender: TObject);
7 begin
8 {subclass the richedit to get the windows messages}
9 PRichEdWndProc := MakeObjectInstance(RichEdWndProc);
10 POldWndProc := Pointer(SetWindowLong(RichEdit1.Handle, GWL_WNDPROC,
11 Integer(PRichEdWndProc)));
12 end;
13
14 procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
15 begin
16 {un-sublass it so you app can close}
17 if Assigned(PRichEdWndProc) then
18 begin
19 SetWindowLong(RichEdit1.Handle, GWL_WNDPROC, Integer(POldWndProc));
20 FreeObjectInstance(PRichEdWndProc);
21 end;
22 end;
23
24 procedure TForm1.RichEdWndProc(var Msg: TMessage);
25 begin
26 Msg.Result := CallWindowProc(POldWndProc, RichEdit1.Handle, Msg.Msg, Msg.WParam,
27 Msg.LParam);
28
29 if (Msg.Msg = WM_VSCROLL) and (LOWORD(Msg.wParam) = SB_THUMBTRACK) then
30 begin
31 {the SB_THUMBTRACK message is only sent when the user moves the scroll
32 bar position}
33 Label1.Caption := 'thumb Pos is ' + IntToStr(HIWORD(Msg.Wparam));
34 RichEdit1.SelStart := RichEdit1.Perform(EM_LINEINDEX,
35 RichEdit1.Perform(EM_GETFIRSTVISIBLELINE, 0, 0), 0) + 1;
36 end;
37
38 end;
39
40 procedure TForm1.but_REditInfoClick(Sender: TObject);
41 var
42 ScrolPos, VisLineOne: Integer;
43 ScrollInfo1: TScrollInfo;
44 begin
45 {use some windows messages to get scroll position and other info}
46 VisLineOne := RichEdit1.Perform(EM_GETFIRSTVISIBLELINE, 0, 0);
47
48 ScrollInfo1.cbSize := SizeOf(TScrollInfo);
49 ScrollInfo1.fMask := SIF_RANGE;
50 GetScrollInfo(RichEdit1.Handle, SB_VERT, ScrollInfo1);
51 ScrolPos := GetScrollPos(RichEdit1.Handle, SB_VERT);
52 ShowMessage('ScrolPos is ' + IntToStr(ScrolPos) + ' First Vis Line is ' +
53 IntToStr(VisLineOne) + ' Scroll max is ' + IntToStr(ScrollInfo1.nMax));
54 end;
Solve 2:
The most simple way
55
56 function GetHorzScrollBarPosition: Integer;
57 begin
58 // constants: SB_HORZ = 0, SB_VERT = 1,
59 // SB_BOTH = 3, SB_THUMBPOSITION = 4
60 Result := GetScrollPos(RichEdit1.Handle, SB_HORZ);
61 // Result is the number of pixels the RichEdit is scrolled
62 end;
|