Search code examples
delphivclpopupmenudelphi-11-alexandria

How to select the right-clicked TreeView node in PopupMenu.OnPopup event-handler?


In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I have a TreeView (TTreeView descendant), where MultiSelect = False and PopupMenu = PopupMenu1, so when I right-click a node in the TreeView, then PopupMenu1 is invoked.

In the PopupMenu1.OnPopup event-handler, I need the right-clicked node to be programmatically selected. How can I do that?

Example: In the following screenshot, the first node is preselected. When I right-click the last node to invoke the popup menu, then the last node gets VISUALLY selected TOO (although MultiSelect = False!):

enter image description here

However, when I try to detect the selected node in the PopupMenu1.OnPopup event-handler:

procedure TformMain.PopupMenu1Popup(Sender: TObject);
begin
  CodeSite.Send(MyTreeView.Selected.Text', MyTreeView.Selected.Text);
end;

... then CodeSite reports still the FIRST node as selected!

So how can I set the right-clicked node in the PopupMenu1.OnPopup event-handler to be selected?

(Please note that the TreeView's OnMouseDown event-handler gets executed AFTER the PopupMenu1.OnPopup event-handler)

Obviously, the TPopupMenu class lacks an OnBeforePopup event!


Solution

  • The simplest solution I know of is to use the OnContextPopup event:

    procedure TForm1.TreeView1ContextPopup(Sender: TObject; MousePos: TPoint;
      var Handled: Boolean);
    begin
      var TreeNode := TreeView1.GetNodeAt(MousePos.X, MousePos.Y);
      if Assigned(TreeNode) then
        TreeNode.Selected := True;
    end;