Access controls on the main form from other form

Patriek
21 augustus 2022:

If you have a separate settings form but you need to update controls on your main form. You can access it's functions by referencing it through OpenForms.

var mainForm = Application.OpenForms.OfType().FirstOrDefault();            
mainForm.toTextBox("Configuration saved.");
mainForm.Refresh(); // Refresh to show changes.

Now in order for the function to work it needs to be thread aware and to do that you need to use a delegate to invoke the function.

delegate void toTextBoxCallback(string text);
public void toTextBox(string text)
{
if (this.textOutput.InvokeRequired) // Check if different thread
{
// Use delegate to cross threads
toTextBoxCallbackd = new toTextBoxCallback(toTextBox);
this.Invoke(d, new object[] { text });
}
else
{
// Write text to textbox
this.textOutput.AppendText(text);
}
}

When you call the function it will check if it needs to invoke the delegate function or it can access it directly. Make sure that after you have set the controls on your main form, you do a refresh to update it.

    I like to see who's visiting my website, do you accept?
    Do you want to accept tracking cookies?