C# Windows窗体无法正常关闭

C# Windows窗体无法正常关闭,c#,winforms,refactoring,add-in,C#,Winforms,Refactoring,Add In,我正在为outlook 2010开发外接程序。 基本上,我的功能区上有一个按钮,可以接收选定的电子邮件,并将其保存到文本文件中。如果电子邮件包含某个主题,则会自动将其保存到硬编码的文件路径。否则,将打开一个windows窗体,要求用户输入文件路径 当用户选择路径并单击“确定”时,将进行保存,然后表单关闭。。。但后来它又重新打开了。。。它似乎正在创建一个新的实例或其他东西。。。如果我单击“取消”或“X”,它将关闭,但我不明白为什么它第一次不能正常关闭 下面是我的代码 //This is myRib

我正在为outlook 2010开发外接程序。
基本上,我的功能区上有一个按钮,可以接收选定的电子邮件,并将其保存到文本文件中。如果电子邮件包含某个主题,则会自动将其保存到硬编码的文件路径。否则,将打开一个windows窗体,要求用户输入文件路径

当用户选择路径并单击“确定”时,将进行保存,然后表单关闭。。。但后来它又重新打开了。。。它似乎正在创建一个新的实例或其他东西。。。如果我单击“取消”或“X”,它将关闭,但我不明白为什么它第一次不能正常关闭

下面是我的代码

//This is myRibbon.cs
private void btn_SaveFile_Click(object sender, RibbonControlEventArgs e) 
{
   //other code
   if (subject = "xyz") 
   {
      //other code
      textFile.Save();
   }
   else
   {
      MyPopup popup = new MyPopup();
      popup.ShowDialog();
   }
}

//This is MyPopup.cs
private void btnOK_Click(object sender, EventArgs e) 
{
   var filePath = txtFilePath.Text;
   if (!string.IsNullOrWhiteSpace(filePath)) 
   { 
       SaveEmailToText(filePath); 
      this.Close(); 
   }
   else 
   { //show message box with error }
   this.Close(); 
}

private static void SaveEmailToText(string filePath) 
{
    //other code
    textFile.Save();
}
我已经把它简化了很多,这样更容易阅读。 任何帮助都将不胜感激。

  • 考虑使用
    OpenFileDialog
    代替弹出式表单
  • 仅使用弹出窗口(或文件对话框)获取文件名
  • 将电子邮件保存代码保存在一个位置(否则您将有重复的代码)
  • 在进一步处理之前,验证对话框窗体的
    DialogResult
  • 表单是一次性的-
    使用
    语句将自动处理它们
  • 不要关闭对话框窗体-改为设置它的
    DialogResult
    属性
以下是重构代码:

private void btn_SaveFile_Click(object sender, RibbonControlEventArgs e) 
{
   string filePath = defaultPath;

   if (subject != "xyz") 
   {
      using(MyPopup popup = new MyPopup())
      {
         // user can close popup - handle this case
         if (popup.ShowDialog() != DialogResult.OK)
             return;
         filePath = popup.FilePath;
      }
   }       

   SaveEmailToText(filePath);
}

private void SaveEmailToText(string filePath) 
{
   //other code
   textFile.Save();
}
以及您的弹出窗口,应替换为
OpenFileDialog

private void btnOK_Click(object sender, EventArgs e) 
{
    if (string.IsNullOrWhiteSpace(FilePath))
    { 
        //show message box with error
        DialogResult = DialogResult.Cancel;
        return;
    }

    // you can assign default dialog result to btnOK in designer
    DialogResult = DialogResult.OK;
}

public string FilePath
{
    get { return txtFilePath.Text; }
}

您需要通过检查对话框ModalResult关闭或处理表单。是否缺少显示MyPopup的声明方式。。?它不在表格上,是吗…?谢谢你的帮助,我会试试看,看我的进展如何。