【发布时间】:2011-08-25 00:43:18
【问题描述】:
我有一个定制的设备,我通过串口发送/接收数据。我想知道是否有任何函数可以用来获取等待从串口读取的字节数?
我只想要一个 windows api 解决方案,如果有的话。这似乎是一项微不足道的任务,我不想使用外部组件。
【问题讨论】:
标签: delphi serial-port
我有一个定制的设备,我通过串口发送/接收数据。我想知道是否有任何函数可以用来获取等待从串口读取的字节数?
我只想要一个 windows api 解决方案,如果有的话。这似乎是一项微不足道的任务,我不想使用外部组件。
【问题讨论】:
标签: delphi serial-port
ClearCommError 应填写 COMSTAT(TComStat 记录),其中包含一个“cbInQue”成员,指定端口上接收的未读字节数。
【讨论】:
我使用TComPort。虽然您可以使用 WinAPi 调用,但它们很棘手,而 TComPort 会处理这些无聊的事情。它非常轻巧且免费,您可以使用帮助中的 TComport.InputCount 函数:
Returns the number of bytes in input buffer.
function InputCount: Integer;
Description
Call InputCount function to get the number of bytes in input buffer.
【讨论】:
Win API ClearCommError 应该返回接收缓冲区中等待的字符数,其中 cHandle 是当前使用/打开的串行通信端口。
function TRS232Comm.InputCount: cardinal;
var
Errors: Cardinal;
CommStat: TComStat;
begin
if not ClearCommError(cHandle, Errors, @CommStat) then
begin
PurgeComm(cHandle, PURGE_RXCLEAR); //Just empty comm buffer on error and return 0
result := 0;
end else
result := CommStat.cbInQue;
end;
【讨论】:
GetLastError 告知问题所在,而不是返回'0'。