简体   繁体   中英

serialPort_DataReceived don't work in exe file

i writed a program with Serial Port as this:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        serialLabel.BackColor = Color.Red;
        storage = serialPort1.ReadExisting();

        if (storage.Contains("CMGL"))
        {
            if (storage.Length > 65)
            {
                processUnreadedMessages(storage);
            }
            else
            {
                Thread.Sleep(500);
            }
        }
        else if (storage.Contains("CMTI"))
        {
            serialPort1.Write("AT+CMGL\r");
            Thread.Sleep(500);
        }
        storage = "";
        serialLabel.BackColor = Color.Lime;
    }

in visual studio when i run program works good! but when i'l create setup for my program or run exe file, data don't receive to serialPort, and i don't get any error. but when i send data with this program it's work!

can you help Me?

the problematic lines are probably those:

serialLabel.BackColor = Color.Red;

and

serialLabel.BackColor = Color.Lime;

there's a slim chance it will still work in developent environment, but:

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.

[msdn]

try instead:

serialLabel.Invoke(new EventHandler(delegate
{
   serialLabel.BackColor = Color.Red;
}));

Also:

  • make sure you don't touch GUI or anything that should be accessed from the thread it was created on without invoking (eg you also shouldn't write data to EventLog without Invoking) in your method processUnreadedMessages()
  • Check if there's no First Chance exceptions when you debug your application
  • check Application EventLog for messages generated by your application.
  • log data you received in serialPort1_DataReceived event to a file before you do anything else (this will check if DataReceived event is raised at all when it should)
  • subscribe to SerialPort. ErrorReceived event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM