Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to periodically read from a device connected via a USB cable and update WinForm properties with the updated information. The device is a GPS made by TinkerForge that has an API associated with it. There are two steps to access the device:

First connect to the device, the code is:
C#
IPConnection ipcon = new IPConnection();
Bricklet gps - new BrickletGPS(UID, icon);  Where UID is a sting with the 
         device ID
ipcon.Connect (HOST, PORT);  Where HOST is "localhost" and PORT is 4223;

Once connected there are a number of methods in gps for retrieving data such as:
C#
gps.GetDateTime (out long date, out long time);

I would like to make gps available globally so once connected I can continue to access the device periodically.

the structure of the code is:
C#
public partial class Form1:form
{
     
   public Form1()
     {
        InitializeComponent();
        Timer code in here to call DoWork periodically to collect GPS Data
        Will use RunWorkerCompleted to update the GUI with the new Data
      }

      private void DoWork (Object sender, DoWorkEventArgs e)
      {
          I can put the connection and access code in here and it works 
          but then the 
          connection is reestablished on each cycle.  I'd like access to 
          the gps object here rather then continually reinitializing it.
       }

{


What I have tried:

When I put the initialization code before public Form1() the
C#
IPConnection ipcon = new IPConection(); works

However the next statement Bricket gps = new BrickletGPS (UID, ipcon) is flagged with the error that a field initializer cannot reference the non static field method or property Form1().ipcon. As a result the initialization fails.

When I put the initialization in the Form1() method then statements like

gps.GetDateTime indicate that gps does not exist in the current context. The same thing happens is I put a first time if statement to execute the connection. The gps object is not recognized outside the if statement field.

I'm new to C# and .net and am not sure if it is possible and if so who to make the gps object global

Thanks for any help
Posted
Updated 27-Nov-16 4:57am
v3

1 solution

If you need to access the single object from multiple forms, one way is to create a static class to hold and initialize the object. Something like

C#
public static class Gps {
   public IPConnection Connection { get; private set; }
   
   public Initialize() {
      Gps.Connection = new new IPConection();
   }
}

Now you can refer the static class everywhere in your program like

C#
Gps.Initialize();
...
Gps.IPConnection...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900