There is something I have been a while trying to achieve, and I am really stuck in it. I will start from the beginning: I have a project with two forms, main and login.
The login form is very simple, it only asks for user id and password. When the form is loaded, it connects to the server and when user type those in, and clicks login, it sends a login request to the server. This is a sample of how both forms load. The first form to be called by Program.cs
is login:
public static main Child;
private void login_Load(object sender, EventArgs e)
{
Child = new main(this);
}
And the main form starts this way:
public static login Parent;
public main(login parent)
{
Parent = parent;
sck_connect(); // the connection stuff is in this form, the main form
InitializeComponent();
}
What I needed is login to have an object (child) to access main, and main to have an object (parent) to access login. Google wouldn't tell me a way to do this, so I had to use my imagination. If there is a better way of achieving this, I will be pleased to hear it.
As you can see, the first thing main
does is calling sck_connect()
, this method will start a socket connection with the server and keep it alive. Everything works fine from now.
As soon as the user clicks the login button, the login query is sent to the server. We will wait for its prompt reply:
IAsyncResult art = connection.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, new AsyncCallback(receivedata_w), connection);
As you can see, when some data has been received, the method receivedata_w
is called.
private static void receivedata_w(IAsyncResult ar)
{
// here some wonderful-working code receiving data
// and storing login query result in -> String instruction
if (instruction == "LoginResultTrue") // login succeded. We hide the login
// and show the main form
{
Parent.Visible = false; // hide the login form
// this.visible = true;
}
if (instruction == "LoginResultFalse") // login error. We hide the main
// form and show the login form
{
Parent.Visible = true; // show the login form
// this.visible = false;
}
}
If you are asking yourself: why do you need to set again visible=true
for the login
form if that's already visible? - When the user is already logged in and in the main
form, there could be more login attempts (for example due to a connection lost and reconnected)
So, to summarize, the question is: How to change form properties (or the properties of any control in that form) from a static method probably in a different thread?
I have tried everything, and everything I try throws me a different error. Google doesn't seem to be trying to help me with this either. Thank you for all your help, very appreciated.