Delphi 中字符串资源的定义与使用

字符串的存储在应用程序中是独立的,应用程序只有在使用资源时载入,使用完之后清

除,从而节省内存,同时字符串也可以用于翻译,一些汉化软件都利用了字符串。编辑的字

符串放在一个文本文件中,可以使用Delphi中的:File-〉New-〉Text,编辑字符串文件,字

符串文件的格式如下:

  stringtable

  begin

  1,“book“

  2,“apple“

  3,“desk“

  4,“pen“

  5,“computer“

  end

  编辑完字符串文件后,选择Save as,注意要将文件类型改为资源编译文件(.RC),这还不是资源文件,它还必须经过编译才能成为资源文件(.RES)。编译命令为Dos提示符下的BRCC32,其路径为:D:Program FilesBorlandDelphi4Binrcc32.exe;例如上面的字符串资源编译文件名为:StrRes.rc,在DOS提示符下输入:brcc32 mydirStrRes.rc;则编译后会生成一个名为:StrRes.res的资源文件,使用该文件即可访问字符串资源。具体使用见下例:

unit teststr;

interface

uses

Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;

type

TForm1 = class(TForm)

Button1: TButton;

Label1: TLabel;

procedure Button1Click(Sender: TObject);

procedure FormCreate(Sender: TObject);

 private

count : integer; 

public

 end;

var

Form1: TForm1;

implementation

{ *.DFM}

{ StrRes.RES}

const

wordcount = 5;

procedure TForm1.Button1Click(Sender: TObject);

var

strword : string;

begin

if count > wordcount then

begin

count := 1;

end;

strword := LoadStr(count);

label1.Caption := strword;

count := count + 1;

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

label1.Caption := LoadStr(1);

count := 2;

end;

end.

程序中常量wordcount用来记录字符串资源文件中字符串的数量,变量count用来记录显

示的字符串编号。程序运行后单击Button1按钮,则将循环显示字符串资源文件中的每一个字

符串。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

另一篇文章

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

不同于其它资源,字符串资源不能直接编辑,需要先按格式编制一个文本文件,再用程

序将其编译成资源文件。下面用一个简单的例子来说明。首先用文本编辑器编一个文件lb.rc,

其内容如下:

stringtable

begin

1,"开始"

2,"退出"

end

然后,找到delphi的bin子目录下的brcc32.exe文件进行编译, 命令格式为: brcc32

lb.rc,编译结束后即生成一个资源文件lb.res。要使用该资源文件,需要在单元文件imple

mentation部分的开始处包括资源文件:<$R lb.res>。在本例中,上面的字符串用于给一个

命令按钮更换caption设置, 使用的函数是windows api函数 loadstring,以下是使用实例:

//在formcreat过程中:

var

txtcaption:array [0..255] of char;

begin

if loadstring(hinstance, 1, txtcaption, sizeof(txtcaption)) > 0 then

begin

btnstart.caption:=StrPas(txtcaption);

end;

end;

//在btnstartclick过程中:

var

txtcaption:array [0..255] of char;

begin

if loadstring(hinstance, 2, txtcaption, sizeof(txtcaption)) > 0 then

btnstart.caption:=strpas(txtcaption);

end;

这样就可以在程序运行时改变各种属性,而不需要在程序中出现字符串。如果使用另一

个delphi函数loadstr,会显得更加简单:

var

txtcaption:string;

begin

txtcaption:=loadstr(2);

if txtcaption <> '' then

begin

btnstart.caption:=txtcaption;

end;

end;

或许大家可以从以上的过程中看出, 使用123来标识一个字符串有些简陋,也很容易出

错,那么怎么办呢?我们可以采取像 c++ 中使用字符串的方法,为每个字符串预定义一个id,

如:

const

idc-start=1;

idc-exit=2;

当然要把它放在一个unit里(类似于c++的.h文件) ,在使用的单元里再uses一下就

可以了,这样应用感觉是不是很爽呢?

txtcaption:=loadstr(idc-exit);