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-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 contect menu key is called VK_APPS. Note: Do not mistake it with the VK_MENU which is confusingly the ALT key.

Image...

OnContextPopup Event

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 elsewhere.

Image...


Developed using Delphi 10.

The Zip file includes all source files.


Download

StringGridPopUpMenu.zip

License: CC-BY 4.0. Freeware, no warranty. Software Disclaimer.


References

Windows, Virtual-Key Codes



Tags: Delphi, Object Pascal, Programming

Page link: <http://foersom.org/SwDev/Delphi/StringGridPopUpMenu.html>

Edited: 2018-09-21