Question

I have a base class that inherits from Form, that registers a event handler on Shown:

class BaseClass : Form {
    public BaseClass() : base() {
        Shown += new EventHandler(BaseClass_Shown);
    }
    void BaseClass_Shown(object sender, EventArgs e) {
        Close();
        MessageBox.Show("This cannot be opened.");
    }
}

Now, when I subclass this Form and open it in the designer, I actually get that messsage and it closes the form in the designer making is impossible for me to visually edit it.

Is there perhaps some boolean I can use to prevent the Close() and MessageBox to happen?

(Little background: the Close is not always called, but depends on some runtime settings and data)

Was it helpful?

Solution

Some events are fired in the designer as well, it is what gives the Winforms designer its wysiwyg ability. Notably Paint, Shown is also fired, etcetera. The DesignMode property is provided to allow you to tell whether your event handler is running at design-time. Fix:

void BaseClass_Shown(object sender, EventArgs e) {
    if (!this.DesignMode) {
        Close();
        MessageBox.Show("This cannot be opened.");
    }
}

Do note the flaw in your approach, this event also fires for a derived form. You might be helping too much.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top