Моя система следующая: в отдельном потоке Мне нужно читать непрерывные данные, поступающие из последовательного порта. Теперь, я могу читать строку довольно хорошо, но только когда я нажимаю на форму (почему?) .. также кнопка Stop Reading не работает, поэтому я уверен, что есть некоторая проблема в мой нить звонит или что-то в этом роде. любая идея? Я не могу найти ошибку .. спасибо много ..Прочитать серийный номер в отдельной строке
#pragma once
namespace part1 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO::Ports;
using namespace System::Threading;
/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
findPorts();
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ComboBox^ comboBox1;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::Windows::Forms::ComboBox^ comboBox2;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::Button^ button3;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::ProgressBar^ progressBar1;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Button^ button5;
private: System::ComponentModel::IContainer^ components;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->comboBox1 = (gcnew System::Windows::Forms::ComboBox());
this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
this->comboBox2 = (gcnew System::Windows::Forms::ComboBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->button3 = (gcnew System::Windows::Forms::Button());
this->button4 = (gcnew System::Windows::Forms::Button());
this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar());
this->label3 = (gcnew System::Windows::Forms::Label());
this->button5 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// comboBox1
//
this->comboBox1->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList;
this->comboBox1->FormattingEnabled = true;
this->comboBox1->Location = System::Drawing::Point(678, 46);
this->comboBox1->Name = L"comboBox1";
this->comboBox1->Size = System::Drawing::Size(121, 21);
this->comboBox1->TabIndex = 0;
//
// serialPort1
//
this->serialPort1->ReadTimeout = 500;
this->serialPort1->WriteTimeout = 500;
//
// comboBox2
//
this->comboBox2->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList;
this->comboBox2->FormattingEnabled = true;
this->comboBox2->Items->AddRange(gcnew cli::array<System::Object^>(2) {L"9600", L"115200"});
this->comboBox2->Location = System::Drawing::Point(678, 86);
this->comboBox2->Name = L"comboBox2";
this->comboBox2->Size = System::Drawing::Size(121, 21);
this->comboBox2->TabIndex = 1;
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(608, 49);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(58, 13);
this->label1->TabIndex = 2;
this->label1->Text = L"COM Ports";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(608, 93);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(58, 13);
this->label2->TabIndex = 3;
this->label2->Text = L"Baud Rate";
//
// button1
//
this->button1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button1->Location = System::Drawing::Point(678, 128);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(90, 55);
this->button1->TabIndex = 4;
this->button1->Text = L"Init Port";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// button2
//
this->button2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button2->Location = System::Drawing::Point(678, 189);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(90, 55);
this->button2->TabIndex = 5;
this->button2->Text = L"Close Port";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
//
// textBox1
//
this->textBox1->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192)),
static_cast<System::Int32>(static_cast<System::Byte>(128)));
this->textBox1->Enabled = false;
this->textBox1->Location = System::Drawing::Point(59, 80);
this->textBox1->Multiline = true;
this->textBox1->Name = L"textBox1";
this->textBox1->ReadOnly = true;
this->textBox1->Size = System::Drawing::Size(170, 39);
this->textBox1->TabIndex = 6;
this->textBox1->Text = L"Received Here";
//
// textBox2
//
this->textBox2->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(192)),
static_cast<System::Int32>(static_cast<System::Byte>(128)));
this->textBox2->Location = System::Drawing::Point(59, 190);
this->textBox2->Name = L"textBox2";
this->textBox2->Size = System::Drawing::Size(170, 20);
this->textBox2->TabIndex = 7;
this->textBox2->Text = L"Enter Here";
//
// button3
//
this->button3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button3->Location = System::Drawing::Point(59, 135);
this->button3->Name = L"button3";
this->button3->Size = System::Drawing::Size(75, 40);
this->button3->TabIndex = 8;
this->button3->Text = L"Send";
this->button3->UseVisualStyleBackColor = true;
this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);
//
// button4
//
this->button4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button4->Location = System::Drawing::Point(162, 135);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(81, 40);
this->button4->TabIndex = 9;
this->button4->Text = L"Read";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);
//
// progressBar1
//
this->progressBar1->Location = System::Drawing::Point(59, 46);
this->progressBar1->Name = L"progressBar1";
this->progressBar1->Size = System::Drawing::Size(100, 28);
this->progressBar1->TabIndex = 10;
//
// label3
//
this->label3->AutoSize = true;
this->label3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label3->Location = System::Drawing::Point(56, 19);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(70, 13);
this->label3->TabIndex = 11;
this->label3->Text = L"Port Status";
//
// button5
//
this->button5->Location = System::Drawing::Point(252, 99);
this->button5->Name = L"button5";
this->button5->Size = System::Drawing::Size(88, 20);
this->button5->TabIndex = 12;
this->button5->Text = L"Stop Reading";
this->button5->UseVisualStyleBackColor = true;
this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::Color::Silver;
this->ClientSize = System::Drawing::Size(932, 485);
this->Controls->Add(this->button5);
this->Controls->Add(this->label3);
this->Controls->Add(this->progressBar1);
this->Controls->Add(this->button4);
this->Controls->Add(this->button3);
this->Controls->Add(this->textBox2);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->comboBox2);
this->Controls->Add(this->comboBox1);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
// find available ports
private: void findPorts(void)
{
// get port names
array<Object^>^ objectArray = SerialPort::GetPortNames();
// add string array to combobox
this->comboBox1->Items->AddRange(objectArray);
}
// init button
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
this->textBox1->Text=String::Empty;
if(this->comboBox1->Text==String::Empty || this->comboBox2->Text==String::Empty)
this->textBox1->Text="Please Select Port Settings";
else {
try{
// make sure port isn't open
if(!this->serialPort1->IsOpen){
this->serialPort1->PortName=this->comboBox1->Text;
//this->textBox1->Text=this->comboBox1->Text;
this->serialPort1->BaudRate=Int32::Parse(this->comboBox2->Text);
//this->textBox1->Text=this->comboBox2->Text;
this->textBox2->Text="Enter Message Here";
//open serial port
this->serialPort1->Open();
this->progressBar1->Value=100;
}
else
this->textBox2->Text="Port isn't openned";
}
catch(UnauthorizedAccessException^){
this->textBox2->Text="UnauthorizedAccess";
}
}
}
// close button
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
//close serialPort
this->serialPort1->Close();
// update progress bar
this->progressBar1->Value=0;
// Enable read button
this->button4->Enabled = true;
// Enable the init button
this->button1->Enabled = true;
}
// send button
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
// add sender name
String^ name = this->serialPort1->PortName;
// grab text and store in send buffer
//String^ message = this->textBox2->Text;
// write to serial
if(this->serialPort1->IsOpen)
//this->_serialPort->WriteLine(String::Format("<{0}>: {1}",name,message));
this->serialPort1->WriteLine("s");
else
this->textBox2->Text="Port Not Opened";
this->textBox2->Text="Abilitate to read";
}
void UpdateButton() {
while(this->textBox2->Text=="Abilitate to read"){
// check if port is ready for reading
if(this->serialPort1->IsOpen){
// Reset the text in the result label.
// this->textBox1->Text = String::Empty;
//this->textBox2->Text="Abilitate to read";
// this will read manually
try{
this->textBox1->Text=this->serialPort1->ReadLine();
}
catch(TimeoutException^){
this->textBox1->Text="Timeout Exception";
}
// Disable the init button
// the asynchronous operation is done.
this->button1->Enabled = false;
}
else
// give error warning
this->textBox1->Text="Port Not Opened";
}
}
void ThreadMethod() {
this->Invoke(gcnew MethodInvoker(this, &Form1::UpdateButton));
}
//read button
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
Thread^ oThread = gcnew Thread(gcnew ThreadStart(this, &Form1::ThreadMethod));
oThread->Start();
/*while(this->textBox2->Text=="Abilitate to read"){
// check if port is ready for reading
if(this->serialPort1->IsOpen){
// Reset the text in the result label.
// this->textBox1->Text = String::Empty;
//this->textBox2->Text="Abilitate to read";
// this will read manually
try{
this->textBox1->Text=this->serialPort1->ReadLine();
}
catch(TimeoutException^){
this->textBox1->Text="Timeout Exception";
}
// Disable the init button
// the asynchronous operation is done.
this->button1->Enabled = false;
}
else
// give error warning
this->textBox1->Text="Port Not Opened";
}*/
}
private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) {
this->textBox2->Text="Stop Reading";
this->button1->Enabled = true;
}
};
}
Я думаю, что проблема должна быть в использовании метода внутри нити, как это:
void ThreadMethod() {
while(this->textBox2->Text=="Abilitate to read"){
// check if port is ready for reading
if(this->serialPort1->IsOpen){
// Reset the text in the result label.
// this->textBox1->Text = String::Empty;
//this->textBox2->Text="Abilitate to read";
// this will read manually
try{
this->textBox1->Text=this->serialPort1->ReadLine();
}
catch(TimeoutException^){
this->textBox1->Text="Timeout Exception";
}
// Disable the init button
// the asynchronous operation is done.
this->button1->Enabled = false;
}
else
// give error warning
this->textBox1->Text="Port Not Opened";
}
}
//read button
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
Thread^ oThread = gcnew Thread(gcnew ThreadStart(this, &Form1::ThreadMethod));
oThread->Start();
}
й отладчик отправить мне письмо исключение: Я не могу Acces в текстовом поле из другой нити которым был создан
может быть, вместо «это» я могу сослаться на Form1 в только что созданную нить ..
StackOverflow не является: исправьте ошибки. Вы должны попытаться выяснить, что вы пытались исправить, что вы думаете об этой проблеме и выделить какой-то интересный исходный код, а не просто копировать и вставлять кучу кода здесь. –
Возможно, это не совершенство, но лучше после редактирования? – user3296856