Search code examples
c#.netwinformsopenfiledialogsavefiledialog

Close SaveFileDialog/OpenFileDialog programmatically without using pinvoke


Due to some requirements, I have to close SaveFileDialog programmatically without using PINVOKE.

Is there any way to close SaveFileDialog other than using the PINVOKE way? I had tried to close the owner form of the SaveFileDialog, but the SaveFileDialog still there.

What I had tried:

  1. Close the form which execute the ShowDialog() of SaveFileDialog.
  2. SaveFileDialog.Dispose()

Solution

  • Closing the owner window passed to the ShowDialog(owner); method should work. For example:

    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);
    }