Handling the OnChange event handler on a TEdit is great until you programmatically change the text and trigger your OnChange event handler again. It gets really fun if you have two TEdit boxes that update each other in their OnChange event handler. I was reading Automate Restorable Operations with Custom Managed Records by Erik van Bilsen over on Griggy’s Blog and I had a great idea 💡 to automate the disabling and re-enabling of the OnChange event handler!
Custom Managed Records (or CMR as Eric calls them) is a super powerful language feature introduced in 10.4 Sydney. It takes the Record data type and adds Initialization and Finalization methods that are automatically called (as well as other features). Since Records are reference counted Finalization method is automatically called when the last reference goes out of scope. Additionally, it uses try..finally
blocks to make sure the finalization method is called.
So instead of writing code like…
[crayon-672a74aacfbec859589483/]It can be dramatically simplified to the following, while still having the same effect…
[crayon-672a74aacfbf6060472086/]It is important that you assign the instance created, otherwise it goes out of scope immediately, and you loose the benefit.
Originally I implemented this to only support TCustomEdit, but then I got to thinking about TMemo and a number of the other components with OnChange that don’t share a common ancestor. Then I realized I’d probably be better off using RTTI (which should make it agnostic to FMX vs VCL) and maybe a fluent syntax with generics . . . so this isn’t fully implemented yet. . . . Use it at your own risk.
Random tip #1 for handling OnChange events in FMX/FireMonkey forms – if you want to be notified immediately of changes, and not only when the user exits the field, you can handle the OnTyping event, or map the two together.
Random tip #2 I’ve posted to GitHub Gist my Rot47 code and the IgnoreEditChanges unit.
[crayon-672a74aacfbf9653324928/]What cool uses are you finding for Custom Managed Records?