Author: Tomas Rutkauskas
I placed some TImage components on a TScrollBox. Now I would like my users to be
able to scroll these images by clicking on them and moving the cursor with the
mouse button down.
Answer:
Attach handlers to the OnMouseDown, Move, Up events of the image. Modify as below.
The key here is to not use the X and Y mouse positions the handlers get. Each time
the image is scrolled the origin for this position moves and that screws up the
calculation. The code below uses the screen-relative mouse position.
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
7 ExtCtrls, JPEG, StdCtrls;
8
9 type
10 TForm1 = class(TForm)
11 ScrollBox1: TScrollBox;
12 Image1: TImage;
13 Label1: TLabel;
14 procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
15 Shift: TShiftState; X, Y: Integer);
16 procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
17 Shift: TShiftState; X, Y: Integer);
18 procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
19 private
20 { Private declarations }
21 FLastDown: TPoint;
22 public
23 { Public declarations }
24 end;
25
26 var
27 Form1: TForm1;
28
29 implementation
30
31 {$R *.DFM}
32
33 procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
34 Shift: TShiftState; X, Y: Integer);
35 begin
36 GetCursorPos(FLastDown);
37 end;
38
39 procedure TForm1.Image1MouseUp(Sender: TObject; Button: TMouseButton;
40 Shift: TShiftState; X, Y: Integer);
41 begin
42 FLastDown := Point(-1, -1);
43 end;
44
45 procedure TForm1.Image1MouseMove(Sender: TObject; Shift: TShiftState; X, Y:
46 Integer);
47 var
48 pt: TPoint;
49 begin
50 if (ssLeft in Shift) and (FLastDown.X >= 0) then
51 begin
52 GetCursorPos(pt);
53 Scrollbox1.VertScrollBar.Position := Scrollbox1.VertScrollBar.Position +
54 FLastDown.Y - pt.Y;
55 Scrollbox1.HorzScrollBar.POsition := Scrollbox1.HorzScrollBar.Position +
56 FLastDown.X - pt.X;
57 FLastDown := pt;
58 label1.caption := format('%d:%d', [pt.x, pt.y]);
59 end;
60 end;
61
62 end.
|