Skip to content
</> Mücahit TopalA developer's notebook

Blog/C#

C# SHOWING A WARNING ON EXIT (DialogResult)

Mücahit Topal 1 min read 25,887 views TREN

When you want to close the applications you have built, the code needed to bring up a warning page such as  “Do you want to exit ?”, or to have some other action carried out, can be used under DialogResult. To do this, we first need to click on our Form screen and select the Form Closing event from the events section. Double-clicking the Form Closing event gives us 

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

the event in which we will write our code, and every piece of code we write inside it will run when you press the exit button or the X button to close the program.

The code we actually need should look like this.

DialogResult x = MessageBox.Show("Are You Sure You Want to Exit the Program?", "Exit Message!", MessageBoxButtons.YesNo);
            if (x == DialogResult.Yes)
            {
//Actions to perform when Yes is clicked
                       Environment.Exit(0); // The application will close when Yes is clicked

            }
            else if (x == DialogResult.No)
            {
// Actions to perform when No is clicked
                e.Cancel = true; // Closing will be cancelled when No is clicked
            }

If you look closely,  I did not use Application.Exit(); here, because in some applications it does not quite give the result you want. I used Environment.Exit(0); so that it forces the application to close.

That's all for now, friends; I'll try to help anyone who has questions.

Good luck with your work.

,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 1

Yunus

Hocam çok teşekkür edrim günlerdir form2 kapatılınca form1 de kapatılsın istiyorum hiç biyerde ele alınır bişey bulamadım sayenizde yaptım emeğnize sağlık :)Tekrar teşekkür ederim ..

Leave a comment

Comments appear after approval.