0

我在 Delphi 2010 中遇到问题。我想通过串行端口(COM 端口)从我的 PC 发送一些 Unicode(16 位)字符到打印机。我在 D2010 中使用 TCiaComPort 组件。

例如:

CiaComPort1.Open := True; \\I open the port
Data := #$0002 + UnicodeString(Ж) + #$0003;
CiaComPort1.SendStr(Parancs); //I send the data to the device

如果打印机字符集是 ASCII 则字符到达,但 ciril 字符是 '?' 在打印机屏幕上。但如果打印机字符集是 Unicode,则字符不会到达打印机。

以 2 个字节表示的 Unicode 字符。如何将 Unicode 字符逐字节分解?例如#$0002?以及如何使用 comport 逐字节发送此字符串?哪个功能?

4

2 回答 2

0

是否CiaComPort1.SendStr()接受AnsiStringorUnicodeString作为输入?您是否尝试使用 COM 端口嗅探器来确保它CiaComPort按照您的预期传输实际的 Unicode 字节?

#$0002您正在使用的事实#$0003让我认为实际上并非如此,因为这些字符通常在 COM 端口上作为 8 位值而不是 16 位值传输。如果是这种情况,那么这可以解释为什么Ж字符被转换为?,如果CiaComPort在传输之前执行 Unicode->Ansi 数据转换。在这种情况下,您可能不得不这样做:

var
  B: TBytes;
  I: Integer;

B := WideBytesOf('Ж');
SetLength(Data, Length(B)+2);
Data[1] := #$0002;
for I := Low(B) to High(B) do
  Data[2+I] := WideChar(B[I]);
Data[2+Length(B)] #$0003;
CiaComPort1.SendStr(Data); 

但是,如果CiaComPort实际上是在内部执行数据转换,那么您仍然会遇到上述任何编码字节的转换问题$7F

在这种情况下,请查看是否CiaComPort有任何其他可用的发送方法允许您发送原始字节而不是字符串。如果没有,那么您几乎是 SOL,需要切换到更好的 COM 组件,或者只是使用 OS API 直接访问 COM 端口。

于 2013-05-09T01:54:44.953 回答
0

在 Windows 下(检查您的操作系统如何打开和写入 comm 端口),我使用以下函数将 UnicodeString 写入 COMM 端口:请记住,必须正确设置端口、波特率、位数等. 见设备管理器 => 通讯端口

function WriteToCommPort(const sPort:String; const sOutput:UnicodeString):Boolean;
var
   RetW:DWORD;
   buff: PByte;
   lenBuff:Integer;
   FH:THandle;
begin
   Result:=False;
   lenBuff:=Length(sOutput)*2;
   if lenBuff = 0 then Exit; // Nothing to write, empty string

   FH:= Windows.CreateFile(PChar(sPort), GENERIC_READ or GENERIC_WRITE, 0, Nil, OPEN_EXISTING, 0, 0);
   if (FH <> Windows.INVALID_HANDLE_VALUE) then
   try
      Buff:=PByte(@sOutput[1]);
      Windows.WriteFile(FH, buff^, lenBuff, RetW, Nil);
      Result:= Integer(RetW) = lenBuff;
   finally
      Windows.CloseHandle(FH);
   end;
end;
于 2013-05-09T09:07:36.960 回答