Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms GUI hangs when calling OpenFileDialog.ShowDialog()

my project a three tier architecture project talking to a WCF service in the backend. When the backend is able to fetch data from the service, it notifies the business layer using publish-subscribe, which in return notifies the GUI layer.

I have added an OpenFileDialog to my UI design using Visual Studios designer. A button event handler calls the ShowDialog message. However, once I click the button, the whole UI hangs.

Having googled around a bit, I found out that using delegates is the preferred way to handle tasks like this. However, with nor without delegate the problem persists.

Currently my code looks like this:

private void bOpen_Click(object sender, EventArgs e)
{
    Func<Image> del = delegate
    {
        OpenFileDialog d = new OpenFileDialog();
        if (d.ShowDialog() == DialogResult.OK)
        {
            return Image.FromFile(d.FileName);
        }

        return null;
    };

    Invoke(del);
}

I'm coming from the Java world, so I'm not really familiar with the intricacies of C# UI programming.

Anything I'm missing here?

like image 452
Kage Avatar asked Jul 16 '11 14:07

Kage


2 Answers

openFileDialog1->ShowHelp = true;

I put this line in my code then the problem was solved.

like image 180
saiki miya Avatar answered Jan 11 '23 23:01

saiki miya


I seem to have solved the problem adding the [STAThread] Attribute to the main method. I was told to do so once I ran the program in a debugger - which I hadn't done before because I ran the service from Visual Studio and the client regularly from Windows.

[STAThread]
public static void Main(string[] args)
{
    GUI gui = new GUI();
    gui.ShowDialog();
}

Can anybody explain what exactly is going on though

like image 44
Kage Avatar answered Jan 11 '23 23:01

Kage