понеділок, 29 липня 2019 р.

How to forget to restore a cursor in your Delphi application used an interface

Belowe is a clever way how to forget to restore a cursor in your Delphi application used an interface: unit autoCursor; interface uses Controls;
type
  ICursor
= interface(IInterface)
 
['{F5B4EB9C-6B74-42A3-B3DC-5068CCCBDA7A}']
 
end;
function __SetCursor(const aCursor: TCursor): ICursor;
implementation
uses Forms;
type
  TAutoCursor
= class(TInterfacedObject, ICursor)
  private
    FCursor
: TCursor;
  public
   
constructor Create(const aCursor: TCursor);
   
destructor Destroy; override;
 
end; { TAutoCursor }
constructor TAutoCursor.Create(const aCursor: TCursor);
begin
  inherited Create
;
  FCursor
:= Screen.Cursor;
  Screen
.Cursor := aCursor;
end; destructor TAutoCursor.Destroy;
begin
  Screen
.Cursor := FCursor;
  inherited
;
end;
function __SetCursor(const aCursor: TCursor): ICursor;
begin
  Result
:= TAutoCursor.Create(aCursor);
end;
end. and using the code above: uses
   autoCursor
;
procedure TForm1.Button1Click(Sender: TObject);
var
  Obj
: TSomeObject;
begin
 
__SetCursor(crHourGlass);

  Obj
:= TSomeObject.Create;
  try
   
// do something
  finally
    Obj
.Free;
 
end;
end;