1
votes

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!

1
The proper OOP solution is encapsulation. That SerialPort object belongs in the commClass class, not the form. Avoid having the convenience of the designer cramp your style.Hans Passant

1 Answers

3
votes

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.