Friday, May 8, 2020

More Accurate Sleep Function on Windows

Delphi 10.3.3


You may want to use the sleep function for slowing or pacing a repeating action. But you are going to have problems if you need sleeps less than 20 milliseconds.

The normal minimum time period for the sleep function is 20 milliseconds. That means if you use Sleep(1) trying to set it for 1 millisecond it will actually sleep for 20 milliseconds.

But there is a Windows function that increases the resolution of timers.
 
You have to turn it on with
timeBeginPeriod(minimum millisecond resolution);

timeBeginPeriod(1)
will set the minimum timer resolution to 1 millisecond
 
And turn it off (go back to default) with
timeEndPeriod(minimum millisecond resolution);
Call it with the same value you called begin with.

Contained in Unit  Winapi.MmSystem.

For Windows XP and newer.
This is a global Windows OS function. It will give the higher resolution timing to all running Windows processes. That’s why you would want to turn it off after you don’t need it anymore.

Microsoft says setting a higher resolution can improve the accuracy of time-out intervals in wait functions. However, it can also reduce overall system performance, because the thread scheduler switches tasks more often. High resolutions can also prevent the CPU power management system from entering power-saving modes.


Example Delphi app:

 
unit MainUnit;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TMainForm = class(TForm)
    Memo1: TMemo;
    Memo2: TMemo;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

{$R *.dfm}
uses
  math,Winapi.MmSystem;

procedure TMainForm.Button1Click(Sender: TObject);
var
  I, x: Integer;
  s: string;
  K: Integer;
begin
  memo1.Clear;
  Application.ProcessMessages; // to clear the memo
  for K := 1 to 25 do
  begin
    s := '';
    for I := 1 to 25 do
    begin
      x := randomrange(33, 57);
      s := s + char(x);
      sleep(1);
    end;
    memo1.Lines.Add(s);
  end;
end;

procedure TMainForm.Button2Click(Sender: TObject);
var
  I, x: Integer;
  s: string;
  K: Integer;
begin
  memo2.Clear;
  Application.ProcessMessages; // to clear the memo
  TimeBeginPeriod(1);
  for K := 1 to 25 do
  begin
    s := '';
    for I := 1 to 25 do
    begin
      x := randomrange(33, 57);
      s := s + char(x);
      sleep(1);
    end;
    memo2.Lines.Add(s);
  end;
  TimeEndPeriod(1);
end;

end.
 
*****************************************
DFM file:

object MainForm: TMainForm
  Left = 0
  Top = 0
  BorderStyle = bsSingle
  Caption = 'Fast Sleep'
  ClientHeight = 309
  ClientWidth = 532
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Memo1: TMemo
    Left = 8
    Top = 55
    Width = 249
    Height = 242
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -11
    Font.Name = 'Courier New'
    Font.Style = []
    ParentFont = False
    TabOrder = 0
  end
  object Memo2: TMemo
    Left = 276
    Top = 55
    Width = 245
    Height = 242
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -11
    Font.Name = 'Courier New'
    Font.Style = []
    ParentFont = False
    TabOrder = 1
  end
  object Button1: TButton
    Left = 92
    Top = 16
    Width = 75
    Height = 25
    Caption = 'Normal'
    TabOrder = 2
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 372
    Top = 16
    Width = 75
    Height = 25
    Caption = 'Fast'
    TabOrder = 3
    OnClick = Button2Click
  end
end

Download Source files:

Thursday, April 30, 2020

TAniIndicator - How to make it work

Delphi 10.3.3

Many want to use a busy indicator to show the user there is a non visible process in operation. Usually when Delphi programmers try this the first time they notice the TAniIndicator doesn't rotate when they want it to. The problem is that the background process is in the same main form thread as the AniIndicator, which stops the AniIndicator from visibly moving.

In this example we download a file from the internet in the background while the Delphi TAniIndicator component is busy rotating.

The main issue is that the AniIndicator needs to be running in the main form thread and whatever long process you are doing in the background has to be running in another created thread. It wont work the other way around.

You can download the example code below. This example works the same on Windows, Android, IOS and MacOS.







unit MainUnit;

interface

uses
  System.Types, System.Classes, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
  FMX.Layouts, System.Net.HttpClient, System.Net.HttpClientComponent, System.Net.URLClient,
  FMX.Controls.Presentation, FMX.Objects;

type
  TMainform = class(TForm)
    LoadButton: TButton;
    AniIndicator1: TAniIndicator;
    Layout1: TLayout;
    Layout2: TLayout;
    Layout3: TLayout;
    Image1: TImage;
    NetHTTPClient1: TNetHTTPClient;
    Layout4: TLayout;
    ClearImageButton: TButton;
    procedure LoadButtonClick(Sender: TObject);
    procedure ClearImageButtonClick(Sender: TObject);
  private
    { Private declarations }
    procedure load_from_internet;
  public
    { Public declarations }
  end;

var
  Mainform: TMainform;

implementation

{$R *.fmx}
uses
  System.threading, system.uitypes;

procedure TMainform.ClearImageButtonClick(Sender: TObject);
begin
  Image1.Bitmap.Clear(TAlphaColorRec.White);
end;

procedure TMainform.load_from_internet;
var
  Task: ITask;
  url: string;
begin

// turn on ani indicator
  mainform.AniIndicator1.Enabled := True;
  mainform.AniIndicator1.Visible := True;

  Task := TTask.Create(
    procedure
    var
      ms: tmemorystream;
      resp: IHTTPResponse;
    begin
      // ***** do what you need to do in the thread 

      // while the aniindicator is running **********
      NetHTTPClient1.UserAgent := 'Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64;+rv:75.0)+Gecko/20100101+Firefox/75.0';
      ms := tmemorystream.Create;
     // some image file on internet
      url := 'https://www.i-logic.com/kitten.jpg';
      try
        resp := NetHTTPClient1.Get(url, ms);

        if TTask.CurrentTask.Status <> TTaskStatus.Canceled then
        begin
          TThread.Queue(TThread.CurrentThread,
            procedure
            begin
              // ****** this is where it comes when the

              // thread is finished *************
              // we can work with the visual form components
              ms.Position := 0;
              // put the data into image1
              try
               if resp.StatusCode = 200 then  // file was found
                  image1.Bitmap.LoadFromStream(ms);
              finally
                ms.Free;
               // turn off aniindicator
                mainform.AniIndicator1.Enabled := False;
                mainform.AniIndicator1.Visible := False;
              end;
            end);
        end;
      except
       // ****** error in get url *************
        TThread.Queue(TThread.CurrentThread,
          procedure
          begin
            ms.Free;
            // turn off aniindicator
            mainform.AniIndicator1.Enabled := False;
            mainform.AniIndicator1.Visible := False;
          end);
      end;
    end);

  Task.Start;
end;

procedure TMainform.LoadButtonClick(Sender: TObject);
begin
  load_from_internet;
end;

end.



**********************************************


The mainunit FMX file:


object Mainform: TMainform
  Left = 0
  Top = 0
  Caption = 'AniIndicator'
  ClientHeight = 480
  ClientWidth = 258
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Layout1: TLayout
    Align = Top
    Size.Width = 258.000000000000000000
    Size.Height = 73.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 1
    object LoadButton: TButton
      Align = Center
      Size.Width = 195.000000000000000000
      Size.Height = 35.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
      Text = 'Load From Internet'
      OnClick = LoadButtonClick
    end
  end
  object Layout2: TLayout
    Align = Top
    Position.Y = 73.000000000000000000
    Size.Width = 258.000000000000000000
    Size.Height = 76.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 2
    object AniIndicator1: TAniIndicator
      Align = Center
      Size.Width = 81.000000000000000000
      Size.Height = 68.000000000000000000
      Size.PlatformDefault = False
    end
  end
  object Layout3: TLayout
    Align = Top
    Position.Y = 149.000000000000000000
    Size.Width = 258.000000000000000000
    Size.Height = 156.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 3
    object Image1: TImage
      MultiResBitmap = <
        item
        end>
      Align = Center
      Size.Width = 185.000000000000000000
      Size.Height = 117.000000000000000000
      Size.PlatformDefault = False
    end
  end
  object Layout4: TLayout
    Align = Top
    Position.Y = 305.000000000000000000
    Size.Width = 258.000000000000000000
    Size.Height = 80.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 5
    object ClearImageButton: TButton
      Align = Center
      Size.Width = 124.000000000000000000
      Size.Height = 32.000000000000000000
      Size.PlatformDefault = False
      TabOrder = 0
      Text = 'Clear Image'
      OnClick = ClearImageButtonClick
    end
  end
  object NetHTTPClient1: TNetHTTPClient
    Asynchronous = False
    ConnectionTimeout = 60000
    ResponseTimeout = 60000
    HandleRedirects = True
    AllowCookies = True
    UserAgent = 'Embarcadero URI Client/1.0'
    Left = 92
    Top = 200
  end
end


**************************************
Source Code:
https://i-logic.com/ftp/AniInicatorCode.zip