Delphi cursor snapshot

Many years ago a certain Malcolm Groves wrote a lovely little class to simplify cursor management in Delphi. I've recently been pulled back to Delphi development and searched for an age to track down that original code. I eventually found it on the wayback machine but thought I'd post my slightly modified code here for your pleasure. It uses the wonders of Delphi interfaces to ensure the cursor will always get returned to its correct state after a long operation.


unit CursorSnapshot;

interface

uses
  Controls;

type
  ISnapshot = interface
  ['{D0C5F65A-70B4-4994-97F9-479EE86D20B9}']
    procedure Restore;
  end;

  TCursorSnapshot = class(TInterfacedObject, ISnapshot)
    private
      FOriginalCursor : TCursor;
    public
      procedure Restore;
      constructor Create;
      destructor Destroy; override;
    end;

implementation

uses Forms;

constructor TCursorSnapshot.Create;
begin
  FOriginalCursor := Screen.cursor;
  Screen.Cursor := crAppStart;
end;

destructor TCursorSnapshot.Destroy;
begin
  Restore;
  inherited;
end;

procedure TCursorSnapshot.Restore;
begin
  Screen.Cursor := FOriginalCursor;
end;

end.

Usage is pretty simple, use it like so

procedure TForm1.Button1Click(Sender: TObject);
var
  CursorSnapshot : ISnapshot;
begin
  CursorSnapshot := TCursorSnapShot.Create;
  // some long winded operation
end;