You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Form类中重写OnFormClosing方法的技术问题咨询

自定义Form关闭确认类实现

看起来你已经把窗体关闭前的确认逻辑封装到自定义Form类里了,这段代码的思路很清晰,我帮你用Markdown格式整理好,方便后续使用和参考:

public class MyForm : Form { 
    protected override void OnFormClosing(FormClosingEventArgs e) { 
        base.OnFormClosing(e); 
        if (e.CloseReason == CloseReason.WindowsShutDown) return; 
        // Confirm user wants to close 
        switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo)) { 
            case DialogResult.No: e.Cancel = true; break; 
            default: break; 
        } 
    } 
}

另外再给你提几个小细节,让逻辑更严谨:

  • 一定要先调用base.OnFormClosing(e),这能保证Form原生的关闭事件和相关逻辑正常触发,不会因为重写方法丢失原有功能
  • 通过CloseReason.WindowsShutDown判断系统关机场景,直接跳过确认,避免在系统关机时弹出不必要的提示框,提升用户体验
  • 当用户选择“No”时设置e.Cancel = true,就能精准阻止窗体关闭,符合预期的交互逻辑

内容的提问来源于stack exchange,提问作者MikisaMaliDojnik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:18:20