简体   繁体   中英

C# accessing serial port from different forms

I have an MdiParent form that opens serial port (COM1). I have a child form, that starts a timer on a click of a button, and the timer fires every couple of seconds. The timer calls a method in a separate class (lets call it commClass) that is suppose to read and write to previously opened COM1 port.

Communication between Mdi and COM1 works fine. So does the timer, triggering events. The problem is the writing/reading from the serial port.

Can someone please tell me a proper OOP way to access my serial port, defined on Mdi form, from my commClass? A few lines of code that explains what to do on Mdi, child and commClass would be greatly appreciated.

Thanks!

If you need to access port from the different forms, the better way would be to create a static helper class that handles the read/write task and use that class from the forms that need it.

If that class need to be activated every couple of seconds then also you should implement the timings in the helper class itself and and define some method like a Start() method that starts the timer, but try not to expose the implementation detail to forms . Instead just provide some methods to abstract the read/write task.

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