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

Delphi 使用 RC 資源檔字串表實現多語系與錯誤訊息管理

     編輯:Delphi

資源檔建立流程

  1. 用記事本或 Borland Resource Workshop 4.5 建立 .rc 文字檔,定義 STRINGTABLE。
  2. 用 BRCC32.exe 編譯成 .res 二進位資源檔。
  3. 將 .res 改名為 .rc (或直接在專案 {$R xxx.rc} 引入 .res)。
  4. Resource Workshop 會產生對應 .pas 常數單元 (定義 ID 常數)。

範例資源檔 (rcdemo.rc)

#include "urcdemo.pas"
STRINGTABLE
{
  IDS_HELLO, "I am glad to see you."
  IDS_RC, "This programming is created by %s."
}

產生的常數單元 (urcdemo.pas)


unit urcdemo;
interface
const
  IDS_HELLO = 2;
  IDS_RC = 1;
implementation
end.

Delphi 專案引入與使用


unit ufmRCDemo;

interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
     Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1, Button2, Button3, Button4: TButton;
    procedure Button1Click(Sender: TObject);  // API LoadString
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);  // Delphi LoadStr
    procedure Button4Click(Sender: TObject);
  end;

implementation
uses urcdemo;
{$R rcdemo.rc}  // 或 {$R rcdemo.res}
{$R *.dfm}

// 使用 Windows API LoadString
procedure TForm1.Button1Click(Sender: TObject);
var Buf: array[0..255] of Char;
begin
  LoadString(HInstance, IDS_RC, Buf, SizeOf(Buf));
  ShowMessage(Buf);
end;

procedure TForm1.Button2Click(Sender: TObject);
var Buf: array[0..255] of Char;
begin
  LoadString(HInstance, IDS_HELLO, Buf, SizeOf(Buf));
  ShowMessage(Buf);
end;

// 使用 Delphi 封裝 LoadStr
procedure TForm1.Button3Click(Sender: TObject);
begin ShowMessage(LoadStr(IDS_HELLO)); end;

procedure TForm1.Button4Click(Sender: TObject);
begin ShowMessage(LoadStr(IDS_RC)); end;

end.

優點

  • 字串集中管理,方便多語系版本製作 (僅替換 .rc/.res)。
  • 程式碼與字串分離,維護容易。
  • 可存放格式化字串 (%s),搭配 Format 使用。

注意

  • 16 位 (Delphi 1) 與 32 位 (Delphi 2+) 資源格式不同,需用對應版本 BRCC。
  • 字串 ID 建議從 1 開始,避免 0 與系統保留衝突。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved