Delphi: StringGrid, position and Context Menu

Dan Kelly picture Dan Kelly · Aug 19, 2010 · Viewed 9k times · Source

I'm having a problem with using a TStringGrid and Popup menu

I want to know the Row / Column of the cell that was last active when select an item from my Popup menu. However when I click on the popup menu, the StringGrid.Row is returned as -1.

I've tried using MouseToCell as part of OnClick, but even after setting SG.Row it still returns as -1 in the PopUp menus routines... I suspect that the problem is the Grid losing the focus.

Are there any solutions to this that don't require OnClick setting a global variable?

I'm using an Action List linked to the items on the Popup Menu to make sure that the actions are consistent between the toolbar and the Popup Menu

Answer

Andreas Rejbrand picture Andreas Rejbrand · Aug 19, 2010

I am afraid that I do not fully understand what you mean. When I left-click a cell in a string grid, it gets selected, but not when I right-click it. When I right-click it, the popup menu is shown (if assigned), and on MenuItemClick I can easily read the row and col currently selected. See example video.

I guess that you actually want this: you want right-clicks to change the active cell as well as left-clicks. This is easily done:

procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbRight then
    StringGrid1.Perform(WM_LBUTTONDOWN, 0, MakeLParam(Word(X), Word(Y)));
end;