Daniel Jørgensen
Daniel Jørgensen

Reputation: 1202

Run code when window closes

I believe it is possible to run code when the close button is pressed in Windows Forms application in C#. Its a child form of the main window. I want to save some user settings when the user closes the window.

private void fileTypeDialog_FormClosing(Object sender, FormClosingEventArgs e)
    {
        int ArraySize = fileTypesData.Items.Count;
        string[] fileTypesToSaveArray = new string[ArraySize];

        for (int i = 0; i < ArraySize; i++)
        {
            fileTypesToSaveArray[i] = fileTypesData.Items[i].ToString();
        }
        string fileTypesToSave = String.Join(",", fileTypesToSaveArray);
        MessageBox.Show(fileTypesToSave.ToString());
        Properties.Settings.Default.fileTypes = fileTypesToSave;
        Properties.Settings.Default.Save();
    }

I have done this before i think, but i simply cannot remember how i did it. Can you guys assist me?

Upvotes: 0

Views: 4925

Answers (2)

LarsTech
LarsTech

Reputation: 81620

Your event isn't wired up. If you don't create the event with the designer, then you need to add it manually, usually in the constructor:

public Form1() {
  InitializeComponent();
  this.FormClosing += fileTypeDialog_FormClosing;
}

But a form shouldn't have to listen to its own events since it has access to its protected event methods. So simply start typing "override OnForm" and select "OnFormClosing" from intellisense. Your code block would look like this:

protected override void OnFormClosing(FormClosingEventArgs e) {
  // your code here

  base.OnFormClosing(e);
}

When overriding a base method, always include the base call as shown unless you have a specific reason not to.

Upvotes: 4

Davide I.
Davide I.

Reputation: 302

Try to use FormClosed instead of FormClosing, I tried and worked very well for me :) Hope helped you :)

Upvotes: 0

Related Questions