StringGrid Context Menu
How to make a pop-up context menu that can be activated by either mouse or keyboard.
Context Menu by Mouse Click
For simple use the GridPopupMenu can be assigned to the StringGrid1 PopupMenu event in the Delphi Object Inspector. However only right-button mouse click (context menu mouse click) will be handled correctly and be able to determine the the StringGrid cell where menu is opened.
Context Menu Key
Standard PC keyboards has a key with a menu symbol. This key opens a context menu for current selected item similar to right-click on mouse. For app development the key is important to support so the users can work efficiently with keyboard and access context menu.
In Windows virtual key codes the context menu key is named VK_APPS. Note: Do not mistake it with the ALT key that is confusingly called VK_MENU.
In order to support both mouse right-click and VK_APPS key the StringGrid event OnContextPopup must be used. In the event the MousePos X and Y is read, to give the screen cooordinates of the mouse. If event triggered by VK_APPS was used these coordinates will be X=-1 and Y=-1.
In the case of VK_APPS key press then the text-cursor or here StringGrid current cell (StringGrid1.Col and StringGrid1.Row) will be used to calculate where to open context menu. Use method CellRect to get coordinates of the current cell relative to upper left of StringGrid1 component. The context menu should appear in the lower right corner of the cell so position BottomRight of Rect is used. To move context menu a bit into the cell, coordinates X and Y are subtracted 8 pixels.
In the case of mouse right-click process is easier. Use MouseToCell to convert the mouse coordinates within the StringGrid (i.e. relative to upper left corner of StringGrid) to StringGrid cell. Then point is set as current cell by assigning StringGrid1 Col and Row).
Last steps are common for both VK_APPS and mouse right-click. it is to convert from StringGrid coordinates to screen coordinates using StringGrid ClientToScreen() and to then open the context menu with GridPopupMenu.Popup().
The actual user selection in the context menu is handled by VCL. The context menu has 3 options including a separator line just for demonstration. The result are one of the 3 option events: OptionAClick(), OptionBClick() or OptionCClick(). Alternative user has canceled the selection by Esc key or mouse click outside menu.
Developed using Delphi 10.
The Zip file includes all source files.
License: CC-BY 4.0. Freeware, no warranty. Software Disclaimer.
Tags: Delphi, Object Pascal, Programming