Marco
Marco

Reputation: 1025

What is DialogResult function visual C++ 2010?

I am working a simple form, I spend more than a day to find out something

What I want is to click a button in form1 and then pop up a form2. I have the following code

private: System::Void MyAdd_Click(System::Object^  sender, System::EventArgs^  e) {
         Form2^ myForm2 = gcnew Form2();

     }
};

However, the form2 could not pop up. I really don't understand, so I copy more code from an example. Even though I don't think it will be useful, just try. However it works.

private: System::Void MyAdd_Click(System::Object^  sender, System::EventArgs^  e) {
         Form2^ myForm2 = gcnew Form2();
         if (myForm2->ShowDialog()==System::Windows::Forms::DialogResult::OK) {}
     }
};

My question is that I have already created the form in both case, why the IF statement makes difference?

Upvotes: 0

Views: 4297

Answers (1)

Mike Kwan
Mike Kwan

Reputation: 24447

In this case it makes no difference since nothing extra is done. However, a common usage is like so:

void ShowMyDialogBox()
{
   Form2^ testDialog = gcnew Form2;

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if ( testDialog->ShowDialog( this ) == ::DialogResult::OK )
   {

      // Read the contents of testDialog's TextBox.
      this->txtResult->Text = testDialog->TextBox1->Text;
   }
   else
   {
      this->txtResult->Text = "Cancelled";
   }

   delete testDialog;
}

Checking the return value allows you to see how the dialog closed.

If you are asking why you need to call ShowDialog, it is because even though you have created your form, you have not told the system to show it yet. Note that ShowDialog blocks/does not return until the dialog box is closed.

Upvotes: 2

Related Questions