Reputation: 1885
I have an application that sets the main form's content code as views (which is a descendant of UserControl
).
Now, in one of my controls, I want to show a message dialog either when it is created or when it is shown (i.e. in the constructor or the Load method).
Weirdly, the MessageBox.Show()
is not shown as I'd expect...
I use following code:
public myControl() {
InitializeComponent();
Load += control_load;
MessageBox.Show("constructor");
}
void control_load(object sender, EventArgs e) {
if (MainForm.Instance.InvokeRequired) {
MainForm.Instance.Invoke((Action)delegate {
MessageBox.Show("Load invoke");
});
return;
}
else {
MessageBox.Show("Load normal");
}
}
}
The symptom is: InvokeRequired
is false
. "constructor" message is not shown and I only have "Load normal" message.
Moreover, if I comment out the "constructor" message box, no message is shown at all...
Can anybody help out, for my general understanding?
Upvotes: 1
Views: 1424
Reputation: 30454
I think that the reason that your constructor message box is not shown in your case is, because you probably construct your control before your main form is shown. Your program is not able to show anything before the main form load event is called.
You should strive to keep your constructors light-weight: let your constructors only do things it can fully control, like creating its own members and setting the state of the members.
The reason for this, is that during construction not everything that is needed for full working of the used Controls are already created and fully functional. Therefore normally the first interaction with the user interface should be done in the load event handler
For an unknown reason you want to communicate with the operator during construction. I guess this is for debug purposes. Consider using the Debug class for this.
If you really want to tell the operator that a Control is constructed, you should wait until at least the main form is constructed.
By the way, you load event handler can only be called by the GUI thread, and thus Invoke will never be required, unless you do strange things like calling the function directly. So your check on InvokeRequired can be removed, or if you don't trust your own code you should Debug.Assert(!InvokeRequired) to find out where you are using windows Forms incorrectly.
Upvotes: 1