Author: Jonas Bilinkevicius
I'm using a form with a TPaintBox element that exceeds the size of the form, so the
form has two scrollbars. I want the user to be able to scroll the form using the
keyboard (with cursor keys). How can I perform scrolling programmatically? I tried
using the TForm.ScrollBy method, but the results are a bit strange.
Answer:
Do not use ScrollBy, instead send WM_VSCROLL messages to the form to make it do the
work for you.
1 2 procedure TfrmMain.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
3 begin4 case Key of5 VK_DOWN: {scroll down}6 begin7 Perform(WM_VSCROLL, SB_LINEDOWN, 0);
8 Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
9 end;
10 VK_UP: {scroll up}11 begin12 Perform(WM_VSCROLL, SB_LINEUP, 0);
13 Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
14 end;
15 end;
16 end;
If you use ScrollBy you also have to manually adjust the scrollbar position since it only scrolls the windows client area, completely independent of any scrollbar.