winforms - Caller ID using SerialPort C# -
i using serialport caller id when rings landline. i've tested using putty software , works fine.
my c# code throws invalidoperation exception , says that: cross-thread operation not valid: control lblcalleridtitle accessed thread other thread created on. error occurs when try do: lblcalleridtitle.text = readdata;
how can fix this? below 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.io.ports; namespace callerid { public partial class callerid : form { public callerid() { initializecomponent(); port.open(); watchmodem(); setmodem(); } protected override void onpaint(painteventargs e) { base.onpaint(e); watchmodem(); } private serialport port = new serialport("com3"); string callname; string callnumber; string readdata; private void setmodem() { port.writeline("at+vcid=1\n"); port.rtsenable = true; } private void watchmodem() { port.datareceived += new serialdatareceivedeventhandler(port_datareceived); } private void port_datareceived(object sender, serialdatareceivedeventargs e) { readdata = port.readexisting(); //add code split up/decode incoming data lblcalleridtitle.text = readdata; console.writeline(readdata); } private void callerid_load(object sender, eventargs e) { } } } i want label show incoming data. thanks
your user controls (such label) have updated on ui thread, , serial data coming in on thread.
your 2 options either push control update main ui thread invoke(), or have serial thread update variable, , use timer control check variable update label.
the code first (better) option, should this:
private void port_datareceived(object sender, serialdatareceivedeventargs e) { readdata = port.readexisting(); //add code split up/decode incoming data if (lblcalleridtitle.invokerequired) lblcalleridtitle.invoke(() => lblcalleridtitle.text = readdata); else lblcalleridtitle.text = readdata; console.writeline(readdata); } the label updated on main ui thread.
Comments
Post a Comment