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.
private void Form1_Load(object sender, EventArgs e)
{
_serialport.DataReceived += new SerialDataReceivedEventHandler(_serialport_DataReceived);
_serialport.PortName = "COM4";
_serialport.BaudRate = 9600;
_serialport.DataBits = 8;
_serialport.Parity = Parity.None;
_serialport.StopBits = StopBits.One;
_serialport.Open();
}
private delegate void SetTextDeleg(string text);
private void _serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string data = _serialport.ReadExisting();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
timer1.Enabled = true;
}
private void si_DataReceived(string data)
{
textBox1.Text = data.Trim();
}
private void timer1_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.