文本收发:
利用 Read 和 Write 方法可以发送和接收文本数据。
利用 Read 和 Write 方法, 可发送和接收任意类型的数据。
例:文本数据的收发 (此例子已包含在控件压缩包里面)
Unit1.h |
class TForm1 : public TForm
{
__published: // IDE-managed Components
TMemo *MemoSend;
TButton *ButtonSend;
TButton *ButtonSet1;
TYbCommDevice *YbCommDevice1;
TButton *ButtonClear;
TPanel *PanelTextEncoding;
TRadioButton *RadioBtnUTF8;
TRadioButton *RadioBtnANSI;
TMemo *MemoReceive;
void __fastcall ButtonSet1Click(TObject *Sender);
void __fastcall ButtonSendClick(TObject *Sender);
void __fastcall ButtonClearClick(TObject *Sender);
void __fastcall YbCommDevice1CommNotify(TObject *Sender, int NotifyType);
private: // User declarations
RawByteString sRawBuf; // 这个字符串类型不会解析字符编码,不会丢弃不完整的字符(比如半个汉字)
public: // User declarations
__fastcall TForm1(TComponent* Owner);
}; |
Unit1.cpp |
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
try
{
YbCommDevice1->Active = true;
}
catch(Exception &e)
{
ShowMessage("YbCommDevice1: "+e.Message);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSet1Click(TObject *Sender)
{
YbCommDevice1->SettingsDialog(this,true);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSendClick(TObject *Sender)
{
if(RadioBtnANSI->Checked)
{
AnsiString s = MemoSend->Text; // 转成 ANSI/ASCII 传输
YbCommDevice1->Write(s.c_str(),s.Length());
}
else // UTF-8
{
UTF8String s = MemoSend->Text; // 转成 UTF8 传输
YbCommDevice1->Write(s.c_str(),s.Length());
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::YbCommDevice1CommNotify(TObject *Sender, int NotifyType)
{
//收到的字节数不会超过串口缓存的容量, 所以分配一个缓存容量相同的Buf
char Buf[8192+1]; //多一个文本结束符
int n = YbCommDevice1->Read(Buf,8192);
if(n>0) //收到字节数
{
Buf[n] = 0; //添加一个文本结束符 '\0'
sRawBuf+=Buf; // RawByteString 类型,上一次是不完整字符的前半截,能和本次不完整的字符和后半截加在一起,不会因为解析字符编码而丢弃不完整的字符
if(RadioBtnANSI->Checked)
MemoReceive->Text = AnsiString(sRawBuf.c_str()); // RawByteString 里面的字符串内容是 AnsiString
else
MemoReceive->Text = UTF8String(sRawBuf.c_str()); // RawByteString 里面的字符串内容是 UTF8String
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonClearClick(TObject *Sender)
{
sRawBuf = "";
MemoReceive->Lines->Clear();
}
//--------------------------------------------------------------------------- |
|