如何使用事件 FormClosed 或 FormCloing 关闭文本文件?

How to close a text file with the event FormClosed or FormCloing?

我有下一个代码:

Process open_txt = new Process();
   public Form1()
   {
      InitializeComponent();
      open_txt.StartInfo.FileName = @"C:\Users\Desktop\Test.txt";
      open_txt.Start();
   }

使用这段代码,我打开了一个名为 .txt 的文件 Test.txt 并在上面写入。

我希望当我用鼠标关闭表单时(我的意思是,当我单击右上角的小红叉时,换句话说,就像我们所有人都关闭了所有 windows 以及名为 Test.txt.txt 文件也关闭。

我知道我需要使用事件 FormClosedFormClosing,但是它不起作用,我在这个事件中有这个,但没有关闭 .txt 文件。

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
   open_txt.Close();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   open_txt.Close();
}

如何关闭 .txt 文件

在你的Form1_FormClosing()方法中使用Kill()方法:

open_txt.Kill();

您所拥有的只是对 Process 的引用,所以看起来您唯一能做的就是 Kill() 过程。这看起来相当严厉,但可能会做你想做的事。

它也可能有意想不到的副作用。如果 PC 使用 Word 打开文本文件,当您终止该进程时,您也会丢失对其他文档的所有未保存更改?

如果您想更好地控制文件何时关闭,那么您可能需要在您的应用程序中嵌入一个编辑器(或查看器),而不是仅仅交给 OS。