Assuming you have a Form1 like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void HandleError(int errorCode, string errorMessage)
{
this.Text = $"{errorCode}: {errorMessage} - " +
$"{DateTime.Now.ToLongTimeString()}";
}
}
And a Program.cs like this:
internal static class Program
{
public static Form1 MainForm { get; private set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new Form1();
Application.Run(MainForm);
}
}
The following piece of code throws and exception every two seconds, and updates the Text of your main form:
System.Threading.Timer timer = new System.Threading.Timer(
(o) =>
{
try
{
//do something
int i = 1;
i = i / (i - 1);
}
catch (Exception)
{
Program.MainForm?.Invoke(new Action(() =>
{
Program.MainForm.HandleError(1, "Devide by zero");
}));
}
}, null, 0, 2000);