Reputation: 11
Within my program, I have two forms, formLogin
and formStudent
. The formLogin
has a connection to a server, through an external class called Connection
. I am attempting to pass the connection to formStudent
, show the formStudent
and hide the formLogin
. The Connection
class has two constructors for the forms so that I'm not creating new instances of the forms everywhere and it inherits Form.
The method I am attempting to call from the Connection
class gives me the error shown in the comment:
public void SuccessfulLogin()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => SuccessfulLogin()));
/*
**Invoke or BeginInvoke cannot be called on a control until the window
handler has been created**
*/
}
else
{
formStudent.connection = formLogin.newConnection;
formLogin.Hide();
formStudent.Show();
}
}
I have attempted adding if
statements to see if the handle is created through if (IsHandleCreated)
, but through using break points it doesn't appear that any of the code in the method is being run at all. I have also tried placing this method in both the formLogin
class and the Connection
class, with no changes.
Thank you very much to King King, for pointing me in the right direction. I changed my code to this:
this.CreateHandle();
this.Invoke(new MethodInvoker(SuccessfulLogin));
and the sucessfulLogin
method to this:
public void SuccessfulLogin()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => SuccessfulLogin()));
}
else
{
formStudent = new frmStudent();
formStudent.connection = formLogin.newConnection;
formLogin.Hide();
formStudent.Show();
}
}
Upvotes: 1
Views: 771
Reputation: 63317
Try using CreateControl()
before calling to SuccessfulLogin()
:
this.CreateControl();
this.SuccessfulLogin();
Other solutions:
Load
event handlerShown
event handlerHandleCreated
event handler (Of course, this should be done with some flag to make it work as expected, because the Handle
may be re-created at runtime at some unpredicted point of time and hence may make the SuccessfulLogin
called multitime).Upvotes: 1