E
E
ElijahVodka2019-06-17 17:16:44
C++ / C#
ElijahVodka, 2019-06-17 17:16:44

How to fix Thread to check numbers c++/cli?

There is a number guessing game. When the form is loaded, the second thread is called - th and sets a random number, which the user must guess later
. After pressing the button, the second thread compares the entered number.
I made the thread start when the form is opened and pause after a random number is set, in order to resume it when it will be necessary to check the number.
Tried resetting the thread or suspending it. In any case, it either does not stop or does not start again.
Actually the question is: how to fix this and do it right?

form code
namespace OS1 { 

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 Threading; 
//using namespace System::IO; 

/// <summary> 
/// Сводка для MyForm 
/// </summary> 
public ref class MyForm : public System::Windows::Forms::Form 
{ 
public: 
MyForm(void) 
{ 
InitializeComponent(); 
} 

//код формы 

}

#pragma endregion

    int num; // это номер который мы загадали
    int rnd; // это номер который загадали нам
    int st = 0;
    
    Thread^ th = gcnew Thread(gcnew ThreadStart(this, &MyForm::check));
    
    private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {
      th->Start();			
    }

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {		
      th->Resume();
    }
    void check() {
      this->ChangeText();
    }	
  };
}

The following code was suggested to me for accessing the form from th:
delegate void SetVoidDelegate();
private: System::Void ChangeText() {
      if (this->textBox1->InvokeRequired) {
        using namespace System;
        SetVoidDelegate^ d = gcnew SetVoidDelegate(this, &MyForm::ChangeText);
        this->Invoke(d);
      }
      else {
        if (textBox2->Text == String::Empty) {
          using namespace std;
          srand((int)time(0));
          rnd = (rand() % 100) + 1;
          textBox2->Text = "" + rnd;
          th->Suspend();
st=1;
        }
        if (st == 1); {
          num = Convert::ToInt32(textBox1->Text);
          if (num == rnd) {
            textBox1->Text = "exelent";						
            label1->Visible = true;
          }
          else if (num < rnd) textBox1->Text = "more!";
          else if (num > rnd) textBox1->Text = "less!";
        }				
      }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom Belousov, 2017-08-05
@flygrounder

It's not very clear without the code, but I think you forgot in media display: block; do

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question