当我的表单关闭时执行代码

Por*_*han -1 .net c# winforms

我的程序在运行时对注册表进行了一些更改,如果它们没有正确回滚,可能会给用户带来一些问题。例如,他们可能无法使用互联网连接。

所以我需要确保当他们关闭应用程序时,我将一切恢复正常。为此,我需要知道他们何时按下表单的“关闭”按钮。我怎样才能做到这一点?有我可以处理的事件吗?

sa_*_*213 5

您可以订阅一个名为FormClosingthis fire before 的事件FormClose,并允许您在表单关闭之前验证/更改所需的设置

public Form1()
{
    InitializeComponent();
    FormClosing += Form1_FormClosing;
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   // Reset values
}
Run Code Online (Sandbox Code Playgroud)