The RichTextBox control need to save some data received from a serial port. At the same time, also need to process the KeyPress event. The problem is RichTextBox.AppendText method will lost some data from the serial port when processing the key press event at the same time. My code is follow:
private: System::Void sfRichTextBox_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
if(m_bInputChar){
if(sfPort->IsOpen) {
sfPort->Write(e->KeyChar.ToString());
e->Handled = true;
}
}
}
private: System::Void sfPort_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs ^ e) {
String ^lpBuf = sfPort->ReadExisting();
StreamIn(lpBuf);
}
private: System::Void StreamIn(String^ text) {
if(sfRichTextBox->InvokeRequired)
{
StreamInCallback^ lpStreamInCB = gcnew StreamInCallback(this,&SerialTool::SerialForm::StreamIn);
this->BeginInvoke(lpStreamInCB,gcnew array<String^,1> { text });
}
else
{
swReport->Write(text);
sfRichTextBox->AppendText(text);
if(sfRichTextBox->TextLength>sfRichTextBox->MaxLength/4)
{
int delLine = sfRichTextBox->GetLineFromCharIndex(sfRichTextBox->MaxLength/4);
sfRichTextBox->Select(0,sfRichTextBox->GetFirstCharIndexFromLine(delLine)-1);
swLog->Write(sfRichTextBox->SelectedText);
sfRichTextBox->SelectedText = "";
sfRichTextBox->Select(sfRichTextBox->TextLength,0);
sfRichTextBox->ScrollToCaret();
}
sfRichTextBox->HideSelection = false;
}
}

AppendTex problem about RichTextBox
Zilent
Seema Ramchandani MSFT
Based upon the code snippet you've supplied; using InvokeRequired/BeginInvoke means all access to the RichTextBox is done on one thread. So, there isn't a synchronization problem there.
Will the call to sfPort->Write() cause the DataReceived event to be raised on the same thread
The only other thing I can think of is one routine is leaving a selection behind that the other is inadvertently overwriting. Maybe you can trace what the code thinks is adding to the rich text box and compare that with that you see in the rich text box. The difference between the two may make the cause of the problem more apparent to you or someone else in the forums.
JColeman
RSach