資源檔建立流程
- 用記事本或 Borland Resource Workshop 4.5 建立
.rc 文字檔,定義 STRINGTABLE。
- 用
BRCC32.exe 編譯成 .res 二進位資源檔。
- 將
.res 改名為 .rc (或直接在專案 {$R xxx.rc} 引入 .res)。
- 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 與系統保留衝突。