当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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?

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: