How to close FileDialog using code???

  • Thread starter Thread starter Mohit
  • Start date Start date
M

Mohit

Hi all,
I am opening a FileDialog on a different thread(as per client
requirements:-( ). Now whenever user closes the main window from
which FileDialog was opened, then I want that the associated
FileDialog should also gets closed.
I am having hard luck in finding anything by which I can close the
FileDialog. Although Thread Abort is one way but I want to avoid it.
How can I close opened FileDialog???

Thanks in advance!!!
 
It wouldn't be so bad to abort the thread. Your form should be cleaning
up anyways.

You could create another form and use that as the owner parameter in
ShowDialog(...)

You just need a reference to that form inside of your main form. You
don't need to show it.

Then, when closing your form, you can close the owner of the File Dialog.

Here's what I got to work:

// FileDialogForm is just a dummy Form
FileDialogForm _fileForm = new FileDialogForm();

private delegate void CloseDelegate();

protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);

_fileForm.Invoke(new CloseDelegate(_fileForm.Close));
}

Thread thread = null;

private void button2_Click(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(ShowFileDialog));
// OpenFileDialog wants an STA
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}

private void ShowFileDialog()
{
// use the dummy form as the owner
DialogResult result = openFileDialog1.ShowDialog(_fileForm);

if (result == DialogResult.OK)
{
// do something here
}
}
 
Thanks a lot!!!
It really worked like a charm:-)

Now I have another problem.
User clicks a button to open (a separate threaded) FileDialog. Now I
want that when user again clicks on the same button then that already
opened FileDialog should be highlighted/activated/come to front.

I tried the OwnedForms property of that dummy form but it doesn't
contain the reference of that FileDialog as it is not a form.

How can I achieve it??

Thanks again Mufaka.
 
Mohit said:
[...]

Now I have another problem.
User clicks a button to open (a separate threaded) FileDialog. Now I
want that when user again clicks on the same button then that already
opened FileDialog should be highlighted/activated/come to front.

[...]


IMHO, any type of dialog box should _require_ the user's attention/action
before the calling application/program may continue. Perhaps there are
circumstances where it is appropriate or useful, but it just seems like poor
UI design.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top