Windows.Forms showing a disabled form in a non-modal state

I have some problems displaying a disabled form in a non-modal state. Here is a sample code:

public partial class Form1 : Form
{
    // ....
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            Form2 form = new Form2();
            form.Enabled = false;
            form.Show();    // works, but form has no owner
            // form.Show(this); // gives an System.InvalidOperationException
            // ...
            // ... my program here shows a message box, ask user for something
            // ... while 'form' is shown in the background 
            form.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }
}

Any idea why Show()(without a parameter) works but Show(this)gives an exception? In my script, I formshould know that its owner is shown correctly, so I can do the following:

            form.Enabled = false;
            form.Owner=this;
            form.Show();

but is this really a good solution?

EDIT: Thanks for the quick answers. It seems that we really found a bug in the framework here. Despite your suggestions, I think I will continue my decision, since disabling the form after "Show" gives an ugly visible effect to the user.

+3
source share
3

Show(this), - , .

+1

. , ShowDialog(), , . . Show(). Show().

+4

From the Microsoft help source:

public void Show(IWin32Window owner)
{
    if (owner == this)
    {
        throw new InvalidOperationException(SR.GetString("OwnsSelfOrOwner", new object[] { "Show" }));
    }
    if (base.Visible)
    {
        throw new InvalidOperationException(SR.GetString("ShowDialogOnVisible", new object[] { "Show" }));
    }

    // Here!!!
    if (!base.Enabled)
    {
        throw new InvalidOperationException(SR.GetString("ShowDialogOnDisabled", new object[] { "Show" }));
    }

    if (!this.TopLevel)
    {
        throw new InvalidOperationException(SR.GetString("ShowDialogOnNonTopLevel", new object[] { "Show" }));
    }
    if (!SystemInformation.UserInteractive)
    {
        throw new InvalidOperationException(SR.GetString("CantShowModalOnNonInteractive"));
    }
    if (((owner != null) && ((((int) UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), -20)) & 8) == 0)) && (owner is Control))
    {
        owner = ((Control) owner).TopLevelControlInternal;
    }

By the way, there is a reported error MS Connect .

+3
source

Source: https://habr.com/ru/post/1729096/


All Articles