如何将Unicode字符串写入控制台屏幕缓冲区? [英] How do I write a Unicode string to the console screen buffer?

查看:98
本文介绍了如何将Unicode字符串写入控制台屏幕缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准输出设备一个句柄(此处为hStdOut),我使用以下两个过程从控制台应用程序中写入任意字符串:

Given a handle (hStdOut here) to the standard output device, I use the following 2 procedures to write an arbitrary string from a console application:

摘录:

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;

我的麻烦:

此语句不能正确显示该字符串:

This statement doesn't render correctely the string as I expected:

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

我的问题:

是否存在 WriteFile 的 WideString重载,还是我应该考虑另一个可访问控制台屏幕缓冲区的Unicode感知功能?

Is there a "WideString" overload of WriteFile or should I consider another Unicode-aware function that access the console screen buffer?

推荐答案

一个问题是,您需要以 bytes 为单位指定长度,而不是以 characters 为单位。因此,请使用 ByteLength 小于 Length 。目前,您传递给 len 的内容是缓冲区字节大小的一半。

One problem is that you need to specify the length in bytes rather than characters. So use ByteLength rather than Length. At the moment what you are passing in len is half the byte size of the buffer.

我也相信您不应对 nNumberOfBytesToWrite lpNumberOfBytesWritten 参数使用相同的变量。

I also believe that you should not use the same variable for the nNumberOfBytesToWrite and lpNumberOfBytesWritten parameters.

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。

The above is fine if your stdout is expecting UTF-16 encoded text. If not, and if it is expecting ANSI text then you should switch to 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;

要发送到标准输出设备的确切信息取决于它期望的文本编码,而我

Exactly what you need to send to the standard output device depends on what text encoding it is expecting and I don't know that.

最后,如果这是您要写入的控制台,那么您只需使用 WriteConsole

Finally, if this is a console that you are writing to then you should simply use WriteConsole.

这篇关于如何将Unicode字符串写入控制台屏幕缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆