首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 自製動態跑馬燈元件 (L_TEdit1) 與執行緒應用

     編輯:Delphi

設計目標

建立繼承自 TEdit 的新元件 L_TEdit1,擁有 MoveShow 方法可將文字內容以跑馬燈方式動態顯示。為避免阻塞主介面,採用 TThread 在背景執行動畫迴圈。

元件原始碼 (L_Edit.pas)

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.

安裝元件步驟

  1. 用 Image Editor 建立 L_Edit.dcr,新增 24x24 位圖命名 L_TEDIT1,置於同目錄。
  2. IDE 選單 Component > Install Component,選 Into new package,指定 L_Edit.pas,產生 L_Edit1.dpk。
  3. 編譯安裝後,工具箱 Samples 頁面出現新元件圖示。

主程式應用 (L_Unit1.pas)

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 字元迭代器。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved