The problemOften in code Visual FoxPro developers will find themselves having to save the previous state of something in order to be able to restore it once some code has run. The usual culprits are:

SET command (such as SET SAFETY, SET DELETED, etc.)

ON command (ON ERROR, ON ESCAPE, etc.)

Record Pointer position

Selected Work Area

The solutionRather than writing the same lines of code over and over again in our programs, we could create a class that will handle this. The following is a SettingHandler class I’ve written and some examples of use. You’ll note that when I instantiate the class I send it the command that I’m about to execute (such as SET SAFETY OFF) as a string parameter. The class will save the current Safety setting for me and then set it to OFF. When I want the previous Safety setting restored, I release the instance of SettingHandler and the class will restore Safety to whatever it was prior to my setting it off.

Drawbacks and possible improvementsThe only drawback I’ve found to this approach is that intellisense doesn’t work when I am typing in the command as a string parameter. As for improvements, most of the ones I can think of would have to do with table operations. Code could be added to allow you to save the current datasession id and restore to that datasession (there are probably other settings that could be provided for as well – Captions, ForeColor, BackColor, Tag, or whatever). Also, some logic could be added to handle if a developer switched work areas, but hadn’t specified the work area in the GOTO command.

Here’s a runnable example and class definition (Cut-n-paste the code below into a prg file and execute it)