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

WinForms中点击红色关闭按钮触发的事件及日志写入实现咨询

窗口红色关闭按钮触发事件及日志实现

点击WinForms窗口右上角的红色关闭按钮时,会触发FormClosing事件,对应你代码中参数为System.Windows.Forms.FormClosingEventArgs的Window_Closing1方法(另一个Window_Closing方法的参数是CancelEventArgs,属于WPF的Closing事件范畴,若你是WinForms项目,优先用前者)。

要在关闭时写入日志到TXT文件,可按以下方式修改代码:

首先确保代码文件顶部引用必要的命名空间:

using System;
using System.IO;
using System.Windows.Forms;

然后在Window_Closing1方法中添加日志写入逻辑:

private void Window_Closing1(object sender, FormClosingEventArgs e)
{
    // 构造日志内容,包含时间戳和关闭动作说明
    string logText = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] 窗口通过红色关闭按钮关闭\n";
    // 指定日志文件路径,这里用程序运行目录下的window_close_log.txt
    string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "window_close_log.txt");
    // 追加写入日志,UTF-8编码避免乱码
    File.AppendAllText(logFilePath, logText, Encoding.UTF8);
}

注意事项

  • 若日志路径选择系统敏感目录(如C:\根目录),可能会因权限不足导致写入失败,建议优先使用程序自身运行目录或用户文档目录。
  • 如果你的项目是WPF而非WinForms,那么点击红色关闭按钮会触发Closing事件,对应你代码中的Window_Closing方法,日志写入逻辑完全相同,只需把代码放到该方法内即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:50:26