The string in the Windows API corresponds to this Delphi pchar (Pansichar); Using the Delphi string in the API is still more flexible.
First say assignment://赋值方法1: 给直接量
begin
SetWindowText(Handle, '新标题');
end;
//赋值方法2: 定义它要的类型
var
p: PChar;
begin
p := '新标题';
SetWindowText(Handle, p);
end;
//赋值方法3: 转换成它要的类型
var
str: string;
begin
str := '新标题';
SetWindowText(Handle, PChar(str));
end;
//赋值方法4: 用字符数组
var
arr: array[0..255] of Char;
begin
arr := '新标题';
SetWindowText(Handle, arr);
end;
Again, the value://取值方法1: 用字符数组(经常被称作"缓冲区")
var
arr: array[0..254] of Char;
begin
GetWindowText(Handle, arr, 255);
ShowMessage(arr); {Form1}
end;
//取值方法2: 使用 GetMem 给 PChar 分配内存
var
p: PChar;
begin
GetMem(p, 255); {分配内存}
GetWindowText(Handle, p, 255);
ShowMessage(p); {Form1}
FreeMem(p); {释放内存}
end;
//取值方法3: 用 GlobalAlloc 分配全局内存(比 GetMem 慢)
var
p: HGLOBAL;
begin
p := GlobalAlloc(0, 255); {参数一给 0 或 GMEM_FIXED 表示分配的是固定内存}
GetWindowText(Handle, PChar(p), 255);
ShowMessage(PChar(p)); {Form1}
GlobalFree(p); {释放内存}
end;
//取值方法4: 直接使用 string; 需要先 SetLength, 然后再去除空白:
var
str: string;
begin
SetLength(str, 255); {先设定 str 的长度}
GetWindowText(Handle, PChar(str), 255);
{但此时 str 的长度是 255 啊!}
str := PChar(str); {这样可以得到实际长度的字符串}
ShowMessage(str); {Form1}
end;
Fixed-length strings are not #0 ended, are not compatible with APIs, and are generally not used in APIs. C