OnKeyPress occurs before TStringGrid updates cell with new character

Coding in Delphi, attaching an OnKeyPress event handler to a TStringGrid:

The OnKeyPress event fires before the grid cell that the user is typing into has actually updated its value with the key that has been pressed. This is obviously a problem, when I want to know what the contents of that cell are at this moment, as in, as the user modifies it.

The "hacked" solution is simple, if you're not considering every detail: just grab the value from the cell and, since the OnKeyPress event comes along with a Key parameter, append that value to the end - now you have the current value of the cell!

False. What if the user has selected all the text in the cell (ie: "foo") and they are now typing 'b'. Since they selected the text, it will be erased and replaced with the letter 'b'. However, the value of the cell will still display as "foo" in OnKeyPress, and the value of Key will be 'b', so the above logic would lead the application to conclude that the cell now contains "foob", which we know is not true.

So. Does anybody know how to get around this problem? Is there a way to make OnKeyPress react after the grid's contents have been updated, or perhaps a way to force an update at the start of the handler? I am desperately avoiding the use of the OnKeyUp event here, so any suggestions aside from that would be greatly appreciated.


If you wish to respond to a change in a cells value why are you not using the OnSetEditText event ?

Keyboard events are for responding to keyboard input, not a controls response to that input. A control will typically provide one or more additional events to allow an application to respond to the controls response to some input - in this case, where a keyboard input results in a cell value being modified, rather than a change in cell selection, for example.

As an aside, it is quite natural that these events should be occuring prior to the grid controls response to those events, so that you may effectively "filter" such events before they reach the control, eg to prevent a particular keyboard input from affecting the value of a cell.

链接地址: http://www.djcxy.com/p/50624.html

上一篇: 我怎样才能选择一个字符串网格的多个单独的单元格?

下一篇: OnKeyPress在TStringGrid使用新字符更新单元格之前发生