【问题标题】:Close SaveFileDialog/OpenFileDialog programmatically without using pinvoke不使用 pinvoke 以编程方式关闭 SaveFileDialog/OpenFileDialog
【发布时间】:2021-05-05 08:01:48
【问题描述】:

由于某些要求,我必须在不使用 PINVOKE 的情况下以编程方式关闭 SaveFileDialog

除了使用PINVOKE方式之外,还有什么方法可以关闭SaveFileDialog吗? 我曾尝试关闭 SaveFileDialog 的所有者表单,但 SaveFileDialog 仍然存在。

我尝试过的:

  1. 关闭执行ShowDialog()的表单SaveFileDialog
  2. SaveFileDialog.Dispose()

【问题讨论】:

    标签: c# .net winforms openfiledialog savefiledialog


    【解决方案1】:

    关闭传递给ShowDialog(owner); 方法的owner 窗口应该可以工作。例如:

    private static Form CreateDummyForm(Form owner) {
        Form dummy = new Form();
        IntPtr hwnd = dummy.Handle; // force handle creation
        if (owner != null) {
            dummy.Owner = owner;
            dummy.Location = owner.Location;
            owner.LocationChanged += delegate {
                dummy.Location = owner.Location;
            };
        }
        return dummy;
    }
    
    [STAThread]
    static void Main() {
    
        Form form = new Form();
        form.Size = new Size(400,400);
        Button btn = new Button { Text = "btn" };
        btn.Click += delegate {
            SaveFileDialog fsd = new SaveFileDialog();
            int timeoutMillis = 5000;
            Form dummy = CreateDummyForm(form); // Close disposes the dummy form
            Task.Delay(TimeSpan.FromMilliseconds(timeoutMillis)).ContinueWith((t) => { dummy.Close(); dummy.Dispose(); }, TaskScheduler.FromCurrentSynchronizationContext());
            fsd.ShowDialog(dummy);
            fsd.Dispose();
        };
    
        form.Controls.Add(btn);
        Application.Run(form);
    }
    
        
    

    【讨论】:

    • 致电ShowDialog(owner) 后,我没想过要处理所有者表单。谢谢!它有效!
    • 使用using 块,而不是Dispose
    • @Charlieface 对于上面的这种方法是的,但是对于我的代码,SaveFileDialog 的所有者形式不是临时创建的,所以我仍然必须使用 CloseDispose
    【解决方案2】:

    如果您使用 Visual Studio Designer 添加 SaveFileDialog,您的表单将在表单的生命周期内有一个包含此对话框的字段。

    仅在需要时创建 SaveFileDialog 会更高效、更容易。如果您在 using 语句中执行此操作,则无需处理它,当然也不需要 PInvoke

    private void MenuItem_FileSaveAs_Clicked(object sender, ...)
    {
        using (var dlg = new SaveFileDialog())
        {
            dlg.FileName = this.FileName;
            dlg.InitialDirectory = ...
            dlg.DefaultExt = ...
            ...
    
            // Show the SaveFileDialog, and if Ok save the file
            var dlgResult = dlg.ShowDialog(this);
            if (dlgResult == DialogResult.OK)
            {
                // operator selected a file and pressed OK
                this.FileName = dlg.FileName;
                this.SaveFile(this.FileName);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2013-08-08
      • 2015-03-17
      • 1970-01-01
      • 2014-08-01
      相关资源
      最近更新 更多