C++ Tutorial: Change the back color of the form using Color Dialog component
Submitted by Bright777 on Friday, February 21, 2014 - 22:17.
In this tutorial we will learn some useful things about Color Dialog component in C++/CLI and make some practice. We will write a simple program, which will change the back color of the main form of our application. Also we will do some magic with buttons of this dialog :). So, let`s begin.
Preparations
First of all you need to start a new Windows Forms Application project and put on it control called button. Then find the Color Dialog control. It situated in the group of controls called “Dialogs” and drag it on the form. If you want you can rename your button and write something like “Change background color” or something else. Also you don’t need to change the settings of Color Dialog.
Code
Our program will change the back color of the form when we will click on the button. So here the code of the buttonClick function:
In this code we make two main things : we get a pointer to our main form and change its color. To do first task, I used FindForm function, which returns a pointer to the form. Next I declare a variable, which will show the answer of our dialog. Then we need enable ShowHelp function of the color dialog and compare we answer of the dialog. If it is OK, we change back color of the form. And If it is Cancel, we show the message below:
Also we declare the starting color in our dialog in this line “colorDialog1->Color = myForm->BackColor”.
Thanks.
- private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
- Form^ myForm=this->FindForm();
- System::Windows::Forms::DialogResult dial;
- colorDialog1->ShowHelp=true;
- colorDialog1->Color=myForm->BackColor;
- dial=colorDialog1->ShowDialog();
- if ( dial == ::System::Windows::Forms::DialogResult::OK )
- {
- myForm->BackColor= colorDialog1->Color;
- }
- if(dial == ::System::Windows::Forms::DialogResult::Cancel)
- {
- MessageBox::Show("Try another time:)");
- }
- }

Add new comment
- 420 views