処理の実行中を示す回転アニメーションの表示 ~Delphiソースコード集
処理の実行中を示す回転アニメーションの表示 ~Delphiソースコード集 TActivityIndicatorは時間のかかる処理の実行中を示す回転アニメーションを表示するものです。 時間のかかる処理を行う場合に表示させるのが一般的ですが、TActivityIndicatorは メインスレッド で動作します。
TActivityIndicatorは時間のかかる処理の実行中を示す回転アニメーションを表示するものです。 時間のかかる処理を行う場合に表示させるのが一般的ですが、TActivityIndicatorは メインスレッド で動作します。 したがって、時間のかかる処理をメインスレッドで行うと、TActivityIndicatorがアニメーションしません。 アニメーションさせるには、時間のかかる処理を別スレッドで実行させます。
procedure TForm1.Button1Click(Sender: TObject); begin //アクティビティ インジケータのアニメーションを開始 ActivityIndicator1.Animate:=True; TThread.CreateAnonymousThread( procedure begin //何らかの時間のかかる処理をここで行う //アクティビティ インジケータのアニメーションを停止 ActivityIndicator1.Animate:=False; end ).Start; end; 使用例エクセル(*.xlsx)ファイルを選択して、ファイルを開いてブックのシートをMemo1に列挙するアプレケーションを作成します。 待ち時間にアクティビティ インジケータのアニメーションを表示します。
プロジェクト作成とフォームの設計Delphi IDEを起動し、「ファイル」⇒「Windows VCLアプリケーション -Delphi」をクリックします。 フォームにTButtonを1個と、TActivityIndicatorを1個、TMemoを1個、TOpenDialogを1個、ドラッグ&ドロップします。
ソースコードの記述 Button1をダブルクリックして以下ソースコードを記述します。 unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.WinXCtrls; type TForm1 = class(TForm) Button1: TButton; ActivityIndicator1: TActivityIndicator; OpenDialog1: TOpenDialog; Memo1: TMemo; procedure Button1Click(Sender: TObject); private < Private 宣言 >public < Public 宣言 >end; var Form1: TForm1; implementation uses ComObj; procedure TForm1.Button1Click(Sender: TObject); begin OpenDialog1.Filter:='*.xlsx|*.xlsx'; if not OpenDialog1.Execute then exit; Memo1.Clear; Button1.Enabled:=False; //アクティビティインジケーターのアニメーションを開始する ActivityIndicator1.Animate:=True; //メインスレッドとは別のスレッドを作成して実行する TThread.CreateAnonymousThread( procedure var i:Integer; excel, book:OleVariant; sheet_name:string; begin excel:=CreateOleObject('Excel.Application'); book:=excel.Workbooks.open(OpenDialog1.FileName); //excel.Visible:=True; for i := 1 to book.Sheets.Count do begin //シート名の取得 sheet_name:=book.Sheets[i].Name; //メインスレッド内で処理を行う TThread.Synchronize(TThread.CurrentThread, procedure() begin Memo1.Lines.Add(sheet_name); end); end; excel.DisplayAlerts:=False; book.Close; excel.DisplayAlerts:=True; excel.Quit; //メインスレッド内で処理を行う TThread.Synchronize(TThread.CurrentThread, procedure() begin Button1.Enabled:=True; //アクティビティインジケーターのアニメーションを停止する ActivityIndicator1.Animate:=False; end); end ).Start; end; end.