serialPort コンポーネントを含む Windows フォームがあり、DataReceived イベント ハンドラーを使用して受信バッファー内のデータを処理します。String^ を返す ReadExisting メソッドを使用します。これは、受信バッファー内のすべてのデータを欠落させることなく収集できる最も信頼できる方法だからです。そのようです:
void serialPort1_DataReceived(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e)
{
try{
String^ receive = this->serialPort1->ReadExisting();
StreamWriter^ swriter = gcnew StreamWriter("filename.txt", true, Encoding::Unicode);
//Insert some code for encoding conversion here
//Convert String^ receive to another String^ whose character encoding accepts character values from (DEC) 127-255.
//Echo to serialPort the data received, so I can see in the terminal
this->serialPort1->Write(receive);
//Write to file using swriter
this->swriter->Write(receive);
this->swriter->Close();
}catch(TimeoutException^){
in ="Timeout Exception";
}
}
問題は、ReadExisting() メソッドによって返される String^ 値にあります。「wêyÿØÿþÿý6」のような文字を入力すると、127 未満の 10 進値の文字のみが表示されるため、端末から「w?y??????6」を読み取ります。
私が望むのは、ReadExisting() メソッドによって返される String^ 値を Windows-1252 エンコード形式でエンコードして、127 ~ 255 の値を持つ文字を識別できるようにすることです。StreamWriter の Write() メソッドを使用してテキスト ファイルに書き込むことができるように、String^ 変数にする必要があります。
検索してみましたが、これは私がやりたいことに似ていることがわかりました。だからここに私がしたことがあります:
Encoding^ win1252 = Encoding::GetEncoding("Windows-1252");
Encoding^ unicode = Encoding::Unicode;
array <Byte>^ srcTextBytes = win1252->GetBytes(in);
array <Byte>^ destTextBytes = Encoding::Convert(win1252, unicode, srcTextBytes);
array <Char>^ destChars = gcnew array <Char>(unicode->GetCharCount(destTextBytes, 0, destTextBytes->Length));
unicode->GetChars(destTextBytes, 0, destTextBytes->Length, destChars, 0);
String^ converted= gcnew System::String(destChars);
String^ converted
次に、SerialPort と StreamWriterに書き込みます。それでも、無駄に。出力はまだ同じです。127 を超える文字は、引き続き「?」として表されます。これを行う適切な方法は何ですか?私のやり方に何か問題があるのかもしれません。