Delphi character and string [5]

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.