Link to home
Start Free TrialLog in
Avatar of Edward van Nijmweegen
Edward van NijmweegenFlag for Netherlands

asked on

Communicatie with serialport on main (windows)form, from usercontrol

Hello,

I have a windows form, where different usercontrole forms can be loaded within a panel.
These (sub) usercontrolform have button that should talk with the serialport control on the main form.
For example a button should turn on a relay that is connect to my serial port. The communication works fine if i use everything on one form, but now i want to do this from the sub usercontrol form.

I tried to do this via addhandler and properties, but i can't get it to work.

Any help would be great.

Thanks in advance.

Edward
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

There are two basic ways to look at it.

(1) UserControls act directly upon the SerialPort
(2) UserControls request that the main form do something on their behalf

For #1 to work, you'd have to pass a reference to the SerialPort (or main form) into the UserControl when you create it.  This obviously can only be done at run-time.  The UserControl would keep that reference as a class level variable so it can use it at will.

For #2, you'd add Custom events to your UserControl that the main form subscribes to.  When the events are received, the main form would act upon the SerialPort for the UserControl.  If there is only one UserControl needing to do this, then you can wire up the custom events by declaring it as WithEvents and using the Handles keyword.  If the UserControls are dynamic in nature, then you'd use AddHandler() to wire up those custom events instead.
Avatar of Edward van Nijmweegen

ASKER

Can you give a small example for option #2?
On the main form i've the serial port control. I just need to write and read some data from/to it. I don't need to act on external changes, like an external switch.

Thanks a lot.

Edward
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial