Author: Tomas Rutkauskas
I want to get the exact position (in terms of x, y coordinates) within a treeview.
The reason is that I want a popup menu to appear after a certain keypress.
Answer:
Solve 1:
1 2 procedure TForm1.TreeView1KeyDown(Sender: TObject; var Key: Word; Shift:
3 TShiftState);
4 var5 rect: TRect;
6 begin7 if assigned(TreeView1.Selected) then8 begin9 rect := TreeView1.selected.DisplayRect(true);
10 {Because the popup function pops up on the screen, you need to add the form11 coordinates, the treeview coordinates, and then the displayrect coordinates of 12 the item.}13 PopupMenu1.Popup(Form1.Top + TreeView1.Top + rect.Top,
14 Form1.Left + TreeView1.Left + rect.Left);
15 end;
16 end;
Solve 2:
Here's an example of a popup menu that launches when a user clicks on a node in a
TTreeView.
17 18 procedure TfrmExplorer.TreeViewMouseDown(Sender: TObject; Button: TMouseButton;
19 Shift: TShiftState; X, Y: Integer);
20 var21 P: TPoint;
22 begin23 if Button <> mbRight then24 exit;
25 TreeMenu.AutoPopup := False;
26 if TreeView.GetNodeAt(X, Y) <> nilthen27 begin28 TreeView.Selected := TreeView.GetNodeAt(X, Y);
29 P.X := X;
30 P.Y := Y;
31 P := TreeView.ClientToScreen(P);
32 TreeMenu.Popup(P.X, P.Y);
33 end;
34 end;