2008. május 29., csütörtök

Display a popup menu at a certain position in a TTreeView


Problem/Question/Abstract:

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:

procedure TForm1.TreeView1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
  rect: TRect;
begin
  if assigned(TreeView1.Selected) then
  begin
    rect := TreeView1.selected.DisplayRect(true);
    {Because the popup function pops up on the screen, you need to add the form
          coordinates, the treeview coordinates, and then the displayrect coordinates of
          the item.}
    PopupMenu1.Popup(Form1.Top + TreeView1.Top + rect.Top,
      Form1.Left + TreeView1.Left + rect.Left);
  end;
end;


Solve 2:

Here's an example of a popup menu that launches when a user clicks on a node in a TTreeView.

procedure TfrmExplorer.TreeViewMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  P: TPoint;
begin
  if Button <> mbRight then
    exit;
  TreeMenu.AutoPopup := False;
  if TreeView.GetNodeAt(X, Y) <> nil then
  begin
    TreeView.Selected := TreeView.GetNodeAt(X, Y);
    P.X := X;
    P.Y := Y;
    P := TreeView.ClientToScreen(P);
    TreeMenu.Popup(P.X, P.Y);
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése