Using same serial port data received event on two different forms

半腔热情 提交于 2019-12-02 09:12:33

问题


I have a problem with my SerialDataReceivedEventHandler whitch fails to respond to data in serail port.

I have one main form in whitch i open port and do other stuf whitch need to be done for proper serial port communication (sending and receiving work)! Then i open another form in same project whitch need same serial port for reading and writing! Problem is that my SerialDataReceivedEventHandler in form2 not working jet it is completely identical to the first in mainform. (if i call serial.close() in main form app freezes or cause huge delay)

probably i have to make in my main from this event public, but i still don't konow how to make my custom event or something else that will trigger the event in form 2 that data is arrived on port

I found this link for help but does not work with my app.

http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/7efccf0e-b412-4869-b942-a006773a833f

i'm using VS2008,framework3.5 (smart device project)

can somebody help me with that? , Please!


回答1:


Move your SerialPort consumption into a separate static (or a singleton) class. Create a DataReceived event in that class and fire it every time data is received. Have both forms subscribe to the DataReceived event - this way both forms will receive the data.

Edit 1: Sample in pseudo code

public static class Serial {
    public static delegate void DataReceivedEventHandler(object sender, ReceivedEventArgs e);
    public static event DataReceivedEventHandler DataReceived;
    static SerialPort serialPort = new SerialPort();        

    static Serial() {
        serialPort = new SerialPort();
        serialPort.DataReceived += Incoming;
        serialPort.Open();
    }

    private static void Incoming(object sender, SerialDataReceivedEventHandler args) {
        if (DataReceived != null) {
           ReceivedEventArgs rea = new ReceivedEventArgs {Data = args.Data};
           DataReceived(this, rea);
        }
    }
}

public class ReceivedEventArgs : EventArgs {
   public string Data { get; set;}
}

public class Form1: Form {
    public Form1() {
       Serial.DataReceived += Incoming;
    }

    private void Incoming(object sender, ReceivedEventArgs e) {
        // you receive the data here
        Debug.WriteLine(e.Data);
    }
}

public class Form2: Form {
    public Form2() {
       Serial.DataReceived += Incoming;
    }

    private void Incoming(object sender, ReceivedEventArgs e) {
        // you receive the data here
        Debug.WriteLine(e.Data);
    }
}

Again, this is pseudo code, without compiler nearby. Hope this helps.



来源:https://stackoverflow.com/questions/9358216/using-same-serial-port-data-received-event-on-two-different-forms

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!