Hello all:
I was developed a simple descending timer , the problem was while it's execute and after I entered the value in the textbox ,, this message appear:
(((Ontimer(): cross thread operation not valid "textbox1" accessed from the thread other than the thread was crated on )))
on timer is a function I made it for intialize the timer
and this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
using System.Reflection;
namespace NoorHSProject2008
{
public partial class Form1 : Form
{
private System.Timers.Timer timerClock = new System.Timers.Timer();
private int clockTime = 0;
private int alarmTime = 0;
public Form1()
{
InitializeComponent();
InitializeTimer();
}
private void inputToSeconds(string timerInput)
{
try
{
string[] timeArray = new string[3];
int minutes = 0;
int hours = 0;
int seconds = 0;
int occurence = 0;
int length = 0;
occurence = timerInput.LastIndexOf(":");
length = timerInput.Length;
if (occurence == -1 || length != 8)
{
MessageBox.Show("Invalid Time Format.");
}
else
{
timeArray = timerInput.Split(':');
seconds = Convert.ToInt32(timeArray[2]);
minutes = Convert.ToInt32(timeArray[1]);
hours = Convert.ToInt32(timeArray[0]);
this.alarmTime += seconds;
this.alarmTime += minutes * 60;
this.alarmTime += (hours * 60) * 60;
}
}
catch (Exception e)
{
MessageBox.Show("inputToSeconds(): " + e.Message);
}
}
public void InitializeTimer()
{
timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
timerClock.Interval = 1000;
timerClock.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
clockTime = 0;
inputToSeconds(textBox1.Text);
}
public void OnTimer(object sender,ElapsedEventArgs e)
{
try{
clockTime++;
int countdown = alarmTime-clockTime;
if (alarmTime != 0)
textBox1.Text = secondsToTime(countdown);
if(clockTime ==alarmTime )
{
textBox1.Text ="00:00:00";
Form2 b = new Form2();
b.Show();
MessageBox.Show("Time is over");
}
}
catch( Exception ex)
{
MessageBox.Show("OnTimer(): " + ex.Message );
}
}
public string secondsToTime(int seconds)
{
int minutes = 0;
int hours = 0;
while (seconds >= 60)
{
minutes += 1;
seconds -= 60;
}
while (minutes >= 60)
{
hours += 1;
minutes -= 60;
}
string strHours = hours.ToString();
string strMinutes = minutes.ToString();
string strSeconds = seconds.ToString();
if (strHours.Length < 2) strHours = "0" + strHours;
if (strMinutes.Length < 2) strMinutes = "0" + strMinutes;
if (strSeconds.Length < 2) strSeconds = "0" + strSeconds;
return strHours + ":" + strMinutes + ":" + strSeconds;
}
}
So where is the problem???