delphi - 如何将 Unicode 字符串写入控制台屏幕缓冲区?

标签 delphi winapi delphi-xe windows-console

给定一个句柄(这里是hStdOut)到标准输出设备,我使用以下两个过程从控制台应用程序写入任意字符串:

摘录:

procedure Send(const s: string);
var
  len: cardinal;
begin
  len:=Length(s);
  WriteFile(hStdOut,s[1],len,len,nil);
end;

procedure SendLn(const s: string);
begin
  Send(s + #13#10);
end;

我的麻烦:

此语句没有按照我的预期正确呈现字符串:

SendLn('The harder they come...');

我的问题:

WriteFile 是否存在“WideString”重载,或者我应该考虑使用另一个访问控制台屏幕缓冲区的 Unicode 感知函数吗?

最佳答案

一个问题是您需要以字节而不是字符指定长度。所以使用ByteLength而不是长度。目前,您传入的 len 是缓冲区字节大小的一半。

我还认为您不应该对 nNumberOfBytesToWritelpNumberOfBytesWritten 参数使用相同的变量。

procedure Send(const s: string);
var
  NumberOfBytesToWrite, NumberOfBytesWritten: DWORD;
begin
  NumberOfBytesToWrite := ByteLength(s);
  if NumberOfBytesToWrite>0 then
    WriteFile(hStdOut, s[1], NumberOfBytesToWrite, NumberOfBytesWritten, nil);
end;

如果您的 stdout 需要 UTF-16 编码文本,则上述内容没问题。如果不是,并且需要 ANSI 文本,那么您应该切换到 AnsiString。

procedure Send(const s: AnsiString);
var
  NumberOfBytesToWrite, NumberOfBytesWritten: DWORD;
begin
  NumberOfBytesToWrite := ByteLength(s);
  if NumberOfBytesToWrite>0 then
    WriteFile(hStdOut, s[1], NumberOfBytesToWrite, NumberOfBytesWritten, nil);
end;

您需要发送到标准输出设备的确切内容取决于它期望的文本编码,但我不知道。

最后,如果这是您要写入的控制台,那么您应该简单地使用 WriteConsole .

关于delphi - 如何将 Unicode 字符串写入控制台屏幕缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9946039/

相关文章:

delphi - Delphi 的 Mercurial 插件

delphi - libxml2 xmlParseFile无法加载格式正确的XML

delphi - 在Delphi中使用DBExpress创建数据库?

delphi - 如果父应用程序由其他目录中的应用程序启动,则文件I/O无法正常工作

c - 我如何知道外部 DLL 是否进入函数?

c++ - 从 C++ dll 导出类?

delphi - 如何将 Delphi 调试器附加到 64 位 IIS 7.5?

delphi - 如何跟踪 OLE 自动化对象的 _AddRef/_Release 调用

delphi - 如何在 Delphi 中的 dbgrid 上隐藏水平滚动

c - 在 Windows 中临时捕获控制台应用程序的标准输出