Search code examples
c#openfiledialog

C# - OpenFileDialog opening in the same Form/Tab


When I run .ShowDialog() it will run and open fine, except it will open in the same form/tab instead of a new one. This results in issues when I click the Application Icon in the taskbar for it to simply open the form with the OpenFileDialog hidden behind the Application and other windows causing the application to essentially be frozen.

The only workaround is to slowly close all the other applications (Minimize) and then I can click the OpenFileDialog and continue operations.

string proxyFile = "";
Thread thread = new Thread(() =>
{
    OpenFileDialog _ofd = new OpenFileDialog();
    _ofd.Filter = "txt|*.txt";
    using (OpenFileDialog ofd = _ofd)
        if (ofd.ShowDialog() == DialogResult.OK && ofd.CheckFileExists)
        {
            proxyFile = ofd.FileName;
        }
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join(); // Freeze until dialog is done, then it exits the thread and continues with the filepath.
MessageBox.Show(proxyFile);

I have to run it under a thread as it doesnt get executed in STA (Executed using CEFSharp JSCallback) so I have to use a Thread as a workaround.


Solution

  • In the end my fix was to use a Method Invoke from "ActiveForm" and in the ofd.ShowDialog() method it has a parameter to add the Form/Handle, so I changed it to ofd.ShowDialog(ActiveForm) and it worked perfectly.