Reputation: 149
I am having trouble with this code being used in multiple window forms:
private void Window_Load(object sender, EventArgs e)
{
new System.Threading.Timer((state) =>
{
BeginInvoke((Action)delegate()
{
if (!CurrentTimeDate.IsHandleCreated) return;
CurrentTimeDate.Text = " " + DateTime.Now.ToString("hh:mm:ss") + " " + DateTime.Now.ToShortDateString();
});
}, null, 0, 1000);
}
When I show the form at first click, it works well, and then I press close button of the window form. I click again the button to show the form again then it shows this error:
InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created
Edit: I thought it is solved but the code still shows error
Upvotes: 1
Views: 1282
Reputation: 1700
I think it's the timer which continue to run, after you're form has been closed.
Try save the instance of the timer, and in the Form_Closing event call timer.Dispose()
Upvotes: 3