建立繼承自 TEdit 的新元件 L_TEdit1,擁有 MoveShow 方法可將文字內容以跑馬燈方式動態顯示。為避免阻塞主介面,採用 TThread 在背景執行動畫迴圈。
unit L_Edit;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
L_TEdit1 = class(TEdit)
private
protected
public
constructor Create(AOwner: TComponent); override;
procedure MoveShow;
published
property Text;
end;
procedure Register;
implementation
constructor L_TEdit1.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Color := clBlue;
Font.Color := clYellow;
Font.Size := 12;
Font.Name := '@仿宋_GB2312';
TabStop := False;
Update;
end;
procedure L_TEdit1.MoveShow;
var
I, Len: Integer; Ch: Char; S: String;
begin
if Length(Text) = 0 then Text := 'Welcome you to use the software!';
Len := Length(Text);
for I := 1 to Len do
begin
Ch := Text[1];
if Ord(Ch) > 127 then // 雙位元組字元 (中文)
begin
if Length(S) > 1 then
begin
Text := Copy(Text, 2, Len-2) + S; S := '';
end
else
begin
S := Copy(Text, 1, 2);
Text := Copy(Text, 2, Len-1);
end;
end
else // 單位元組字元
Text := Copy(Text, 2, Len-1) + Ch;
Update;
Sleep(100); // 速度控制
end;
end;
procedure Register;
begin
RegisterComponents('Samples', [L_TEdit1]);
end;
end.
Image Editor 建立 L_Edit.dcr,新增 24x24 位圖命名 L_TEDIT1,置於同目錄。Component > Install Component,選 Into new package,指定 L_Edit.pas,產生 L_Edit1.dpk。Samples 頁面出現新元件圖示。unit L_Unit1;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, L_Edit;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
L_TEdit11: L_TEdit1;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1; MyThread1: TMyThread;
implementation
{$R *.DFM}
procedure TMyThread.Execute;
begin
while not Terminated do
Form1.L_TEdit11.MoveShow;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
MyThread1 := TMyThread.Create(False); // 立即啟動
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Welcome You!');
end;
end.
MoveShow 直接修改 Text 並呼叫 Update 強制重繪,執行緒中操作 VCL 控件屬非執行緒安全,僅供示範。正式專案建議用 Synchronize 或佇列訊息方式更新 UI。Sleep(100) 可依需求調整滾動速度。AnsiString / UTF8 字元迭代器。