Use/call this function in LogForm.log
(btw methods in C# are usually capitalized).
private void SetText(string text)
{
Action set = () => yourTextBox.Text = text;
if (yourTextBox.InvokeRequired)
{
yourTextBox.Invoke(set);
}
else
{
set.Invoke();
}
}
If it cannot be set from the current thread yourTextBox.InvokeRequired
will be true and the function will work it out. Otherwise it just sets it directly.
Inspiration from this answer at possible duplicate.
Since you are saying the problem persists I'll show a bit more code and try to expain it further.
First of all, I edited the SetText
method. I added the private modifier since this function is not indended to be called anywhere outside of LogForm
. I also added the curly brackets since that's my preferred style and it also makes sure that the if-statement behaves as expected.
public void Log(string message) {
SetText(message);
//do stuff
}
Both of these methods (Log
and SetText
) are placed inside the LogForm
class. You can now call logForm.Log("Logger has started...");
from any thread as long as your form (containing the textbox) is already initialized. This usually happens in the constructor by calling InitializeComponent();
on the first line.
Without knowing more about your code this is probably as far as I can help you.