It is necessary that after pressing the "close" button, the program executes the code. I found a solution to this problem.

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; int i = 0; while(i < 10) { Form1 msf = new Form1(); msf.Show(); } } 

But this code does not work. How to fix this code to make it work?

  • 2
    Did you add an event subscriber? Or what did you do with this code? - Andrei NOP
  • @Andrew how to add a subscriber to the program closing event? - True-hacker

2 answers 2

To make the method work when you close a form, it is not enough just to write it; you need to set it as a subscriber to the FormClosing event of your form.

This can be done in several ways, for example, you can select a form in the designer and go to the Properties window, open events (an icon with a lightning) in it and set the method for the desired event:

one

Another way is to subscribe in the form constructor code, to do this, go to the window with the form code and add a line in the constructor (required after InitializeComponent !):

enter image description here

In principle, the first method generates the same line, it just puts it in the autogenerated Form1.Designer.cs file in the InitializeComponent method

    Select the FormClosing event in the form events. Activate it by double-clicking the LMB. And then put your code in the generated method.