0

I am working on a c# winforms application and I'm using the MetroFramework for the UI. I have a class that handles all sorts of error messages (from the UI thread and background threads) and is supposed to display them on the UI using the MetroFramework.Forms.MetroForm ErrorForm. This ErrorForm is then passed to a Method called ShowAsOverlay that uses the form it gets to display it via ShowDialog and sets it to be owned by my MainForm (which is a MetroForm too).

So far it all works as expected except that ShowAsOverlay behaves differently in the following examples:

This works as excpected (note how I create the instance of ErrorForm in the same line where I pass it to ShowAsOverlay):

public static void NetworkException(string message)
{
    if (MainForm.InvokeRequired)
    {
        MainForm.Invoke((System.Windows.Forms.MethodInvoker)delegate
        {
            _ = ShowAsOverlay(MainForm, new ErrorForm(message, "Network Exception"));
        });
    }
    else
    {
        _ = ShowAsOverlay(MainForm, new ErrorForm(message, "Network Exception"));
    }
}

However the following code does not work (or at least causes the ShowAsOverlay method to behave differently as the ErrorForm is never displayed)

public static void NetworkException(string message)
{
    ErrorForm myErrorForm = new ErrorForm(message, "Network Exception");
    if (MainForm.InvokeRequired)
    {
        MainForm.Invoke((System.Windows.Forms.MethodInvoker)delegate
        {
            _ = ShowAsOverlay(MainForm, myErrorForm);
        });
    }
    else
    {
        _ = ShowAsOverlay(MainForm, myErrorForm);
    }
}

So my question is: Why in the world would it matter if I create the ErrorForm at the same time when passing it as an argument vs when I create it first and then pass it?

FYI: when I was testing it the if condition always returned true (in case it matters) Also: I didn't check if this "bug" (or maybe feature who knows) also would happen when using the "normal" System.Windows.Forms.Form So it may be MetroFramework specific or not. I really don't know whats going on anymore. I can the code of ShowAsOverlay() too if you want but as I said it works fine when using the first syntax so it must be related to my NetworkException method I guess?

Frederik Hoeft
  • 1,177
  • 1
  • 13
  • 37
  • `Why in the world would it matter if I create the ErrorForm at the same time when passing it as an argument vs when I create it first and then pass it?` The two different code samples are creating the form in a different thread. Presumably you should be creating the form in the UI thread (i.e. within the Invoke). – mjwills Sep 19 '19 at 23:04
  • @mjwills Oh wow I'm facepalming so hard right now. Thank you. I was so confused I didn't even think about that :D – Frederik Hoeft Sep 19 '19 at 23:15

0 Answers0