2

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!

user1580348
  • 5,721
  • 4
  • 43
  • 105

1 Answers1

3

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;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • Strangely, the `OnContextPopup` event-handler is never executed. Only the `OnPopup` event-handler gets executed. – user1580348 Feb 07 '22 at 12:28
  • Then you have something strange in your app. Try this in a new VCL app, and you'll see that it works. (Just one of the 1000 possibilities: While troubleshooting, you set the popup menu's `AutoPopup` to `False` and wrote your own code to invoke it in the list-view's `OnMouseDown` handler.) – Andreas Rejbrand Feb 07 '22 at 12:29
  • I got it working in the `OnMouseDown` event-handler: https://www.screencast.com/t/avv59xeDREq2 – user1580348 Feb 07 '22 at 12:57
  • Obviously, the `TRzShellTree` I use or something in my application somehow is blocking the `OnContextPopup` event-handler. Anyway, I got it working in the `OnMouseDown` event-handler. Thanks for the hint. – user1580348 Feb 07 '22 at 13:02
  • @user1580348: Yes, `OnMouseDown` works just as well (arguably it is even better -- I think the `OnContextMenu` handles the Menu key (or Shift+F10) correctly, but I haven't verified that). – Andreas Rejbrand Feb 07 '22 at 14:02