Hi all,, I am writing a program that can communicate through serial port. I have manage the port connection, I try to send a string from my phone, and show the string on the textbox. I have successfully done that.
What I want to achieve is,when i receive the data from my phone, I want to control others windows control, such as, enabling the timer.
my code look like this.
TypeScript
privatevoidForm1_Load(object sender, EventArgs e)
{
_serialport.DataReceived += newSerialDataReceivedEventHandler(_serialport_DataReceived);
_serialport.PortName = "COM4";
_serialport.BaudRate = 9600;
_serialport.DataBits = 8;
_serialport.Parity = Parity.None;
_serialport.StopBits = StopBits.One;
_serialport.Open();
}
private delegate voidSetTextDeleg(string text);
privatevoid_serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = _serialport.ReadExisting();
// Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.// ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.this.BeginInvoke(newSetTextDeleg(si_DataReceived), newobject[] { data });
timer1.Enabled = true;
}
privatevoidsi_DataReceived(string data)
{
textBox1.Text = data.Trim();
timer1.Enabled=true;
}
privatevoidtimer()
{
if (textBox1.Text == "makan")
timer1.Enabled = true;
}
privatevoidtimer1_Tick(object sender, EventArgs e)
{
if (sec > 58)
{
min++;
sec = 0;
}
else
{
sec++;
}
if (min == 2 && sec > 29)
{
lblTime.ForeColor = Color.Red;
}
if (min == 3)
{
min = 3;
sec = 0;
lblTime.Text = string.Format("{0:00} : {1:00}", min, sec);
timer1.Enabled = false;
}
lblTime.Text = string.Format("{0:00} : {1:00}", min, sec);
}
I also have try to enabled the timer in si_DataReceived, but also failed. How is the correct way to do it? Thanks.
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
you cant do that in the way you wrote it since the timer is an object running on the main thread, and the DataReceived is on a second Thread.
in order todo what you want you will need to create a delegate that will be the Timer Activator, and on the DataReceived you will call the Delegate to Invoke the command for you on the main Thread.
Roei BarRank #1,271 · 1.4K reputationPosted Aug 6, 2009, 11:31 PM EDT