zoukankan      html  css  js  c++  java
  • Windows Mobile6.0 入门学习(一)

    刚接触Windows Mobile是同事写的程序,在手机上开启GPRS定位时获取手机的经纬度坐标,由于获取不到卫星,在执行程序的时候报空异常。由此开始接触Windows Moblile,看了看同事的代码,然后再往上搜索资料,MSDN,CSDN,博客园,连百度文库也看了。呵呵。最后,还是在Windows Mobile6.0自带的Samples\PocketPC\CS里面看到例子和微软DLL文件的内部类。下面是GpsSample.cs例子代码,这个例子是获取GPS经纬度的例子,用到Microsoft.WindowsMobile.Samples.Location这个DLL文件,希望给其他初学者带来一些方便。

    View Code
      1 //
      2 // Copyright (c) Microsoft Corporation.  All rights reserved.
      3 //
      4 //
      5 // Use of this sample source code is subject to the terms of the Microsoft
      6 // license agreement under which you licensed this sample source code. If
      7 // you did not accept the terms of the license agreement, you are not
      8 // authorized to use this sample source code. For the terms of the license,
      9 // please see the license agreement between you and Microsoft or, if applicable,
     10 // see the LICENSE.RTF on your install media or the root of your tools installation.
     11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
     12 //
     13 //
     14 // Copyright (c) Microsoft Corporation.  All rights reserved.
     15 //
     16 //
     17 // Use of this source code is subject to the terms of the Microsoft end-user
     18 // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
     19 // If you did not accept the terms of the EULA, you are not authorized to use
     20 // this source code. For a copy of the EULA, please see the LICENSE.RTF on your
     21 // install media.
     22 using System;
     23 using System.Drawing;
     24 using System.Collections;
     25 using System.Windows.Forms;
     26 using System.Data;
     27 using Microsoft.WindowsMobile.Samples.Location;
     28 
     29 namespace GpsTest
     30 {
     31     /// <summary>
     32     /// Summary description for Form1.
     33     /// </summary>
     34     public class Form1 : System.Windows.Forms.Form
     35     {
     36         private System.Windows.Forms.MenuItem exitMenuItem;
     37         private System.Windows.Forms.MainMenu mainMenu1;
     38         private System.Windows.Forms.Label status;
     39         private MenuItem menuItem2;
     40         private MenuItem startGpsMenuItem;
     41         private MenuItem stopGpsMenuItem;
     42 
     43 
     44         private EventHandler updateDataHandler;
     45         GpsDeviceState device = null;
     46         GpsPosition position = null;
     47 
     48         Gps gps = new Gps();
     49 
     50         public Form1()
     51         {
     52             //
     53             // Required for Windows Form Designer support
     54             //
     55             InitializeComponent();
     56 
     57             //
     58             // TODO: Add any constructor code after InitializeComponent call
     59             //
     60         }
     61         /// <summary>
     62         /// Clean up any resources being used.
     63         /// </summary>
     64         protected override void Dispose( bool disposing )
     65         {
     66             base.Dispose( disposing );
     67         }
     68         #region Windows Form Designer generated code
     69         /// <summary>
     70         /// Required method for Designer support - do not modify
     71         /// the contents of this method with the code editor.
     72         /// </summary>
     73         private void InitializeComponent()
     74         {
     75             this.mainMenu1 = new System.Windows.Forms.MainMenu();
     76             this.exitMenuItem = new System.Windows.Forms.MenuItem();
     77             this.menuItem2 = new System.Windows.Forms.MenuItem();
     78             this.startGpsMenuItem = new System.Windows.Forms.MenuItem();
     79             this.stopGpsMenuItem = new System.Windows.Forms.MenuItem();
     80             this.status = new System.Windows.Forms.Label();
     81             // 
     82             // mainMenu1
     83             // 
     84             this.mainMenu1.MenuItems.Add(this.exitMenuItem);
     85             this.mainMenu1.MenuItems.Add(this.menuItem2);
     86             // 
     87             // exitMenuItem
     88             // 
     89             this.exitMenuItem.Text = "Exit";
     90             this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
     91             // 
     92             // menuItem2
     93             // 
     94             this.menuItem2.MenuItems.Add(this.startGpsMenuItem);
     95             this.menuItem2.MenuItems.Add(this.stopGpsMenuItem);
     96             this.menuItem2.Text = "GPS";
     97             // 
     98             // startGpsMenuItem
     99             // 
    100             this.startGpsMenuItem.Text = "Start GPS";
    101             this.startGpsMenuItem.Click += new System.EventHandler(this.startGpsMenuItem_Click);
    102             // 
    103             // stopGpsMenuItem
    104             // 
    105             this.stopGpsMenuItem.Enabled = false;
    106             this.stopGpsMenuItem.Text = "Stop GPS";
    107             this.stopGpsMenuItem.Click += new System.EventHandler(this.stopGpsMenuItem_Click);
    108             // 
    109             // status
    110             // 
    111             this.status.Location = new System.Drawing.Point(00);
    112             this.status.Size = new System.Drawing.Size(237173);
    113             this.status.Text = "label1";
    114             // 
    115             // Form1
    116             // 
    117             this.ClientSize = new System.Drawing.Size(240268);
    118             this.Controls.Add(this.status);
    119             this.Menu = this.mainMenu1;
    120             this.Text = "Form1";
    121             this.Load += new System.EventHandler(this.Form1_Load);
    122             this.Closed += new System.EventHandler(this.Form1_Closed);
    123 
    124         }
    125         #endregion
    126 
    127         /// <summary>
    128         /// The main entry point for the application.
    129         /// </summary>
    130 
    131         static void Main() 
    132         {
    133             Application.Run(new Form1());
    134         }
    135 
    136         private void exitMenuItem_Click(object sender, EventArgs e)
    137         {
    138             if (gps.Opened)
    139             {
    140                 gps.Close();
    141             }
    142 
    143             Close();
    144         }
    145 
    146         private void Form1_Load(object sender, System.EventArgs e)
    147         {
    148             updateDataHandler = new EventHandler(UpdateData);
    149          
    150             status.Text = "";
    151             
    152             status.Width = Screen.PrimaryScreen.WorkingArea.Width;
    153             status.Height = Screen.PrimaryScreen.WorkingArea.Height;
    154 
    155             gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged);
    156             gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged);
    157         }
    158 
    159         protected void gps_LocationChanged(object sender, LocationChangedEventArgs args)
    160         {
    161             position = args.Position;
    162 
    163             // call the UpdateData method via the updateDataHandler so that we
    164             // update the UI on the UI thread
    165             Invoke(updateDataHandler);
    166 
    167         }
    168 
    169         void gps_DeviceStateChanged(object sender, DeviceStateChangedEventArgs args)
    170         {
    171             device = args.DeviceState;
    172 
    173             // call the UpdateData method via the updateDataHandler so that we
    174             // update the UI on the UI thread
    175             Invoke(updateDataHandler);
    176         }
    177 
    178         void UpdateData(object sender, System.EventArgs args)
    179         {
    180             if (gps.Opened)
    181             {
    182                 string str = "";
    183                 if (device != null)
    184                 {
    185                     str = device.FriendlyName + " " + device.ServiceState + "" + device.DeviceState + "\n";
    186                 }
    187 
    188                 if (position != null)
    189                 {
    190 
    191                     if (position.LatitudeValid)
    192                     {
    193                         str += "Latitude (DD):\n   " + position.Latitude + "\n";
    194                         str += "Latitude (D,M,S):\n   " + position.LatitudeInDegreesMinutesSeconds + "\n";
    195                     }
    196 
    197                     if (position.LongitudeValid)
    198                     {
    199                         str += "Longitude (DD):\n   " + position.Longitude + "\n";
    200                         str += "Longitude (D,M,S):\n   " + position.LongitudeInDegreesMinutesSeconds + "\n";
    201                     }
    202 
    203                     if (position.SatellitesInSolutionValid &&
    204                         position.SatellitesInViewValid &&
    205                         position.SatelliteCountValid)
    206                     {
    207                         str += "Satellite Count:\n   " + position.GetSatellitesInSolution().Length + "/" +
    208                             position.GetSatellitesInView().Length + " (" +
    209                             position.SatelliteCount + ")\n";
    210                     }
    211 
    212                     if (position.TimeValid)
    213                     {
    214                         str += "Time:\n   " + position.Time.ToString() + "\n";
    215                     }
    216                 }
    217 
    218                 status.Text = str;
    219 
    220             }
    221         }
    222 
    223         private void Form1_Closed(object sender, System.EventArgs e)
    224         {
    225             if (gps.Opened)
    226             {
    227                 gps.Close();
    228             }
    229         }
    230 
    231         private void stopGpsMenuItem_Click(object sender, EventArgs e)
    232         {
    233             if (gps.Opened)
    234             {
    235                 gps.Close();
    236             }
    237 
    238             startGpsMenuItem.Enabled = true;
    239             stopGpsMenuItem.Enabled = false;
    240         }
    241 
    242         private void startGpsMenuItem_Click(object sender, EventArgs e)
    243         {
    244             if (!gps.Opened)
    245             {
    246                 gps.Open();
    247             }
    248 
    249             startGpsMenuItem.Enabled = false;
    250             stopGpsMenuItem.Enabled = true;
    251         }
    252     }
    253 }

    建议用Double类型保存经纬度。

    例子比较简单,相信大家都很随意的都能看懂。下面是DLL文件里面包含的类文件,感兴趣的朋友可以看下。

    DegreesMinutesSeconds.cs  主要负责经纬度坐标的分秒变化

    View Code
      1 //
      2 // Copyright (c) Microsoft Corporation.  All rights reserved.
      3 //
      4 //
      5 // Use of this sample source code is subject to the terms of the Microsoft
      6 // license agreement under which you licensed this sample source code. If
      7 // you did not accept the terms of the license agreement, you are not
      8 // authorized to use this sample source code. For the terms of the license,
      9 // please see the license agreement between you and Microsoft or, if applicable,
     10 // see the LICENSE.RTF on your install media or the root of your tools installation.
     11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
     12 //
     13 #region Using directives
     14 
     15 using System;
     16 
     17 #endregion
     18 
     19 namespace Microsoft.WindowsMobile.Samples.Location
     20 {
     21     /// <summary>
     22     /// class that represents a gps coordinate in degrees, minutes, and seconds.  
     23     /// </summary>
     24     public class DegreesMinutesSeconds
     25     {
     26 
     27         bool isPositive;
     28         /// <summary>
     29         /// Returns true if the degrees, minutes and seconds refer to a positive value,
     30         /// false otherwise.
     31         /// </summary>
     32         public bool IsPositive
     33         {
     34             get { return isPositive; }
     35         }
     36 
     37         uint degrees;
     38         /// <summary>
     39         /// The degrees unit of the coordinate
     40         /// </summary>
     41         public uint Degrees
     42         {
     43             get { return degrees; }
     44         }
     45 
     46         uint minutes;
     47         /// <summary>
     48         /// The minutes unit of the coordinate
     49         /// </summary>
     50         public uint Minutes
     51         {
     52             get { return minutes; }
     53         }
     54 
     55         double seconds;
     56         /// <summary>
     57         /// The seconds unit of the coordinate
     58         /// </summary>
     59         public double Seconds
     60         {
     61             get { return seconds; }
     62         }
     63 
     64         /// <summary>
     65         /// Constructs a new instance of DegreesMinutesSeconds converting 
     66         /// from decimal degrees
     67         /// </summary>
     68         /// <param name="decimalDegrees">Initial value as decimal degrees</param>
     69         public DegreesMinutesSeconds(double decimalDegrees)
     70         {
     71             isPositive = (decimalDegrees > 0);
     72             
     73             degrees = (uint) Math.Abs(decimalDegrees);
     74             
     75             double doubleMinutes = (Math.Abs(decimalDegrees) - Math.Abs((double)degrees)) * 60.0;
     76             minutes = (uint) doubleMinutes;
     77 
     78             seconds = (doubleMinutes - (double)minutes) * 60.0;
     79         }
     80 
     81         /// <summary>
     82         /// Constructs a new instance of DegreesMinutesSeconds
     83         /// </summary>
     84         /// <param name="isPositive">True if the coordinates are positive coordinate, false if they
     85         /// are negative coordinates.</param>
     86         /// <param name="degrees">Degrees unit of the coordinate</param>
     87         /// <param name="minutes">Minutes unit of the coordinate</param>
     88         /// <param name="seconds">Seconds unit of the coordinate. This should be a positive value.</param>
     89         public DegreesMinutesSeconds(bool isPositive, uint degrees, uint minutes, double seconds)
     90         {
     91             this.isPositive = isPositive;
     92             this.degrees = degrees;
     93             this.minutes = minutes;
     94             this.seconds = seconds;
     95         }
     96 
     97         /// <summary>
     98         /// Converts the decimal, minutes, seconds coordinate to 
     99         /// decimal degrees
    100         /// </summary>
    101         /// <returns></returns>
    102         public double ToDecimalDegrees()
    103         {
    104             double val = (double)degrees + ((double)minutes / 60.0+ ((double)seconds / 3600.0);
    105             val = isPositive ? val : val * -1;
    106             return val;
    107         }
    108 
    109         /// <summary>
    110         /// Converts the instance to a string in format: D M' S"
    111         /// </summary>
    112         /// <returns>string representation of degrees, minutes, seconds</returns>
    113         public override string ToString()
    114         {
    115             return degrees + "" + minutes + "" + seconds + "\"";
    116         }
    117     }
    118 }

     DeviceStateChangedEventArgs.cs  //GPS设备的状态变化触发事件

    View Code
     1 //
     2 // Copyright (c) Microsoft Corporation.  All rights reserved.
     3 //
     4 //
     5 // Use of this sample source code is subject to the terms of the Microsoft
     6 // license agreement under which you licensed this sample source code. If
     7 // you did not accept the terms of the license agreement, you are not
     8 // authorized to use this sample source code. For the terms of the license,
     9 // please see the license agreement between you and Microsoft or, if applicable,
    10 // see the LICENSE.RTF on your install media or the root of your tools installation.
    11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
    12 //
    13 #region Using directives
    14 
    15 using System;
    16 
    17 #endregion
    18 
    19 namespace Microsoft.WindowsMobile.Samples.Location
    20 {
    21     /// <summary>
    22     /// Event args used for DeviceStateChanged event.
    23     /// </summary>
    24     public class DeviceStateChangedEventArgs: EventArgs
    25     {
    26         public DeviceStateChangedEventArgs(GpsDeviceState deviceState)
    27         {
    28             this.deviceState = deviceState;
    29         }
    30 
    31         /// <summary>
    32         /// Gets the new device state when the GPS reports a new device state.
    33         /// </summary>
    34         public GpsDeviceState DeviceState
    35         {
    36             get 
    37             {
    38                 return deviceState;
    39             }
    40         }
    41 
    42         private GpsDeviceState deviceState;
    43     }
    44 }

    GPS.cs //GPS设备的开关及经纬度处理

    View Code
     1 //
     2 // Copyright (c) Microsoft Corporation.  All rights reserved.
     3 //
     4 //
     5 // Use of this sample source code is subject to the terms of the Microsoft
     6 // license agreement under which you licensed this sample source code. If
     7 // you did not accept the terms of the license agreement, you are not
     8 // authorized to use this sample source code. For the terms of the license,
     9 // please see the license agreement between you and Microsoft or, if applicable,
    10 // see the LICENSE.RTF on your install media or the root of your tools installation.
    11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
    12 //
    13 using System;
    14 using System.Runtime.InteropServices;
    15 using System.Collections;
    16 using System.Text;
    17 
    18 
    19 namespace Microsoft.WindowsMobile.Samples.Location
    20 {
    21     public delegate void LocationChangedEventHandler(object sender, LocationChangedEventArgs args);
    22     public delegate void DeviceStateChangedEventHandler(object sender, DeviceStateChangedEventArgs args);
    23 
    24     /// <summary>
    25     /// Summary description for GPS.
    26     /// </summary>
    27     public class Gps
    28     {
    29         // handle to the gps device
    30         IntPtr gpsHandle = IntPtr.Zero;
    31 
    32         // handle to the native event that is signalled when the GPS
    33         // devices gets a new location
    34         IntPtr newLocationHandle = IntPtr.Zero;
    35 
    36         // handle to the native event that is signalled when the GPS
    37         // device state changes
    38         IntPtr deviceStateChangedHandle = IntPtr.Zero;
    39 
    40         // handle to the native event that we use to stop our event
    41         // thread
    42         IntPtr stopHandle = IntPtr.Zero;
    43 
    44         // holds our event thread instance
    45         System.Threading.Thread gpsEventThread = null;
    View Code
      1   event LocationChangedEventHandler locationChanged;
      2 
      3         /// <summary>
      4         /// Event that is raised when the GPS locaction data changes
      5         /// </summary>
      6         public event LocationChangedEventHandler LocationChanged
      7         {
      8             add
      9             {
     10                 locationChanged += value;
     11 
     12                 // create our event thread only if the user decides to listen
     13                 CreateGpsEventThread();
     14             }
     15             remove
     16             {
     17                 locationChanged -= value;
     18             }
     19         }
     20 
     21 
     22         event DeviceStateChangedEventHandler deviceStateChanged;
     23 
     24         /// <summary>
     25         /// Event that is raised when the GPS device state changes
     26         /// </summary>
     27         public event DeviceStateChangedEventHandler DeviceStateChanged
     28         {
     29             add
     30             {
     31                 deviceStateChanged += value;
     32 
     33                 // create our event thread only if the user decides to listen
     34                 CreateGpsEventThread();
     35             }
     36             remove
     37             {
     38                 deviceStateChanged -= value;
     39             }
     40         }
     41 
     42         /// <summary>
     43         /// True: The GPS device has been opened. False: It has not been opened
     44         /// </summary>
     45         public bool Opened
     46         {
     47             get { return gpsHandle != IntPtr.Zero; }
     48         }
     49 
     50         public Gps()
     51         {
     52         }
     53 
     54         ~Gps()
     55         {
     56             // make sure that the GPS was closed.
     57             Close();
     58         }
     59 
     60         /// <summary>
     61         /// Opens the GPS device and prepares to receive data from it.
     62         /// </summary>
     63         public void Open()
     64         {
     65             if (!Opened)
     66             {
     67                 // create handles for GPS events
     68                 newLocationHandle = CreateEvent(IntPtr.Zero, 00null);
     69                 deviceStateChangedHandle = CreateEvent(IntPtr.Zero, 00null);
     70                 stopHandle = CreateEvent(IntPtr.Zero, 00null);
     71 
     72                 gpsHandle = GPSOpenDevice(newLocationHandle, deviceStateChangedHandle, null0);
     73 
     74                 // if events were hooked up before the device was opened, we'll need
     75                 // to create the gps event thread.
     76                 if (locationChanged != null || deviceStateChanged != null)
     77                 {
     78                     CreateGpsEventThread();
     79                 }
     80             }
     81         }
     82 
     83         /// <summary>
     84         /// Closes the gps device.
     85         /// </summary>
     86         public void Close()
     87         {
     88             if (gpsHandle != IntPtr.Zero)
     89             {
     90                 GPSCloseDevice(gpsHandle);
     91                 gpsHandle = IntPtr.Zero;
     92             }
     93 
     94             // Set our native stop event so we can exit our event thread.
     95             if (stopHandle != IntPtr.Zero)
     96             {
     97                 EventModify(stopHandle, eventSet);
     98             }
     99 
    100             // block until our event thread is finished before
    101             // we close our native event handles
    102             lock (this)
    103             {
    104                 if (newLocationHandle != IntPtr.Zero)
    105                 {
    106                     CloseHandle(newLocationHandle);
    107                     newLocationHandle = IntPtr.Zero;
    108                 }
    109 
    110                 if (deviceStateChangedHandle != IntPtr.Zero)
    111                 {
    112                     CloseHandle(deviceStateChangedHandle);
    113                     deviceStateChangedHandle = IntPtr.Zero;
    114                 }
    115 
    116                 if (stopHandle != IntPtr.Zero)
    117                 {
    118                     CloseHandle(stopHandle);
    119                     stopHandle = IntPtr.Zero;
    120                 }
    121             }
    122         }
    123 
    124         /// <summary>
    125         /// Get the position reported by the GPS receiver
    126         /// </summary>
    127         /// <returns>GpsPosition class with all the position details</returns>
    128         public GpsPosition GetPosition()
    129         {
    130             return GetPosition(TimeSpan.Zero);
    131         }
    132 
    133 
    134         /// <summary>
    135         /// Get the position reported by the GPS receiver that is no older than
    136         /// the maxAge passed in
    137         /// </summary>
    138         /// <param name="maxAge">Max age of the gps position data that you want back. 
    139         /// If there is no data within the required age, null is returned.  
    140         /// if maxAge == TimeSpan.Zero, then the age of the data is ignored</param>
    141         /// <returns>GpsPosition class with all the position details</returns>
    142         public GpsPosition GetPosition(TimeSpan maxAge)
    143         {
    144             GpsPosition gpsPosition = null;
    145             if (Opened)
    146             {
    147                 // allocate the necessary memory on the native side.  We have a class (GpsPosition) that 
    148                 // has the same memory layout as its native counterpart
    149                 IntPtr ptr = Utils.LocalAlloc(Marshal.SizeOf(typeof(GpsPosition)));
    150 
    151                 // fill in the required fields 
    152                 gpsPosition = new GpsPosition();
    153                 gpsPosition.dwVersion = 1;
    154                 gpsPosition.dwSize = Marshal.SizeOf(typeof(GpsPosition));
    155 
    156                 // Marshal our data to the native pointer we allocated.
    157                 Marshal.StructureToPtr(gpsPosition, ptr, false);
    158 
    159                 // call native method passing in our native buffer
    160                 int result = GPSGetPosition(gpsHandle, ptr, 5000000);
    161                 if (result == 0)
    162                 {
    163                     // native call succeeded, marshal native data to our managed data
    164                     gpsPosition = (GpsPosition)Marshal.PtrToStructure(ptr, typeof(GpsPosition));
    165 
    166                     if (maxAge != TimeSpan.Zero)
    167                     {
    168                         // check to see if the data is recent enough.
    169                         if (!gpsPosition.TimeValid || DateTime.Now - maxAge > gpsPosition.Time)
    170                         {
    171                             gpsPosition = null;
    172                         }
    173                     }
    174                 }
    175 
    176                 // free our native memory
    177                 Utils.LocalFree(ptr);
    178             }
    179 
    180             return gpsPosition;            
    181         }
    View Code
      1   /// <summary>
      2         /// Queries the device state.
      3         /// </summary>
      4         /// <returns>Device state information</returns>
      5         public GpsDeviceState GetDeviceState()
      6         {
      7             GpsDeviceState device = null;
      8 
      9             // allocate a buffer on the native side.  Since the
     10             IntPtr pGpsDevice = Utils.LocalAlloc(GpsDeviceState.GpsDeviceStructureSize);
     11             
     12             // GPS_DEVICE structure has arrays of characters, it's easier to just
     13             // write directly into memory rather than create a managed structure with
     14             // the same layout.
     15             Marshal.WriteInt32(pGpsDevice, 1);    // write out GPS version of 1
     16             Marshal.WriteInt32(pGpsDevice, 4, GpsDeviceState.GpsDeviceStructureSize);    // write out dwSize of structure
     17 
     18             int result = GPSGetDeviceState(pGpsDevice);
     19 
     20             if (result == 0)
     21             {
     22                 // instantiate the GpsDeviceState class passing in the native pointer
     23                 device = new GpsDeviceState(pGpsDevice);
     24             }
     25 
     26             // free our native memory
     27             Utils.LocalFree(pGpsDevice);
     28 
     29             return device;
     30         }
     31 
     32         /// <summary>
     33         /// Creates our event thread that will receive native events
     34         /// </summary>
     35         private void CreateGpsEventThread()
     36         {
     37             // we only want to create the thread if we don't have one created already 
     38             // and we have opened the gps device
     39             if (gpsEventThread == null && gpsHandle != IntPtr.Zero)
     40             {
     41                 // Create and start thread to listen for GPS events
     42                 gpsEventThread = new System.Threading.Thread(new System.Threading.ThreadStart(WaitForGpsEvents));
     43                 gpsEventThread.Start();
     44             }
     45         }
     46 
     47         /// <summary>
     48         /// Method used to listen for native events from the GPS. 
     49         /// </summary>
     50         private void WaitForGpsEvents()
     51         {
     52             lock (this)
     53             {
     54                 bool listening = true;
     55                 // allocate 3 handles worth of memory to pass to WaitForMultipleObjects
     56                 IntPtr handles = Utils.LocalAlloc(12);
     57 
     58                 // write the three handles we are listening for.
     59                 Marshal.WriteInt32(handles, 0, stopHandle.ToInt32());
     60                 Marshal.WriteInt32(handles, 4, deviceStateChangedHandle.ToInt32());
     61                 Marshal.WriteInt32(handles, 8, newLocationHandle.ToInt32());
     62 
     63                 while (listening)
     64                 {
     65                     int obj = WaitForMultipleObjects(3, handles, 0-1);
     66                     if (obj != waitFailed)
     67                     {
     68                         switch (obj)
     69                         {
     70                             case 0:
     71                                 // we've been signalled to stop
     72                                 listening = false;
     73                                 break;
     74                             case 1:
     75                                 // device state has changed
     76                                 if (deviceStateChanged != null)
     77                                 {
     78                                     deviceStateChanged(thisnew DeviceStateChangedEventArgs(GetDeviceState()));
     79                                 }
     80                                 break;
     81                             case 2:
     82                                 // location has changed
     83                                 if (locationChanged != null)
     84                                 {
     85                                     locationChanged(thisnew LocationChangedEventArgs(GetPosition()));
     86                                 }
     87                                 break;
     88                         }
     89                     }
     90                 }
     91 
     92                 // free the memory we allocated for the native handles
     93                 Utils.LocalFree(handles);
     94 
     95                 // clear our gpsEventThread so that we can recreate this thread again
     96                 // if the events are hooked up again.
     97                 gpsEventThread = null;
     98             }
     99         }
    100 
    101         #region PInvokes to gpsapi.dll
    102         [DllImport("gpsapi.dll")]
    103         static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, int dwFlags);
    104 
    105         [DllImport("gpsapi.dll")]
    106         static extern int GPSCloseDevice(IntPtr hGPSDevice);
    107 
    108         [DllImport("gpsapi.dll")]
    109         static extern int GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, int dwMaximumAge, int dwFlags);
    110 
    111         [DllImport("gpsapi.dll")]
    112         static extern int GPSGetDeviceState(IntPtr pGPSDevice);
    113         #endregion
    114 
    115         #region PInvokes to coredll.dll
    116         [DllImport("coredll.dll")]
    117         static extern IntPtr CreateEvent(IntPtr lpEventAttributes, int bManualReset, int bInitialState, StringBuilder lpName);
    118 
    119         [DllImport("coredll.dll")]
    120         static extern int CloseHandle(IntPtr hObject);
    121 
    122         const int waitFailed = -1;
    123         [DllImport("coredll.dll")]
    124         static extern int WaitForMultipleObjects(int nCount, IntPtr lpHandles, int fWaitAll, int dwMilliseconds);
    125 
    126         const int eventSet = 3;
    127         [DllImport("coredll.dll")]
    128         static extern int EventModify(IntPtr hHandle, int dwFunc);
    129 
    130         #endregion
      }
    }

    GpsDeviceState.cs   GPS设备的状态管理

    View Code
      1 //
      2 // Copyright (c) Microsoft Corporation.  All rights reserved.
      3 //
      4 //
      5 // Use of this sample source code is subject to the terms of the Microsoft
      6 // license agreement under which you licensed this sample source code. If
      7 // you did not accept the terms of the license agreement, you are not
      8 // authorized to use this sample source code. For the terms of the license,
      9 // please see the license agreement between you and Microsoft or, if applicable,
     10 // see the LICENSE.RTF on your install media or the root of your tools installation.
     11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
     12 //
     13 #region Using directives
     14 
     15 using System;
     16 using System.Runtime.InteropServices;
     17 
     18 #endregion
     19 
     20 public enum GpsServiceState : int
     21 {
     22     Off = 0,
     23     On = 1,
     24     StartingUp = 2
     25     ShuttingDown = 3,
     26     Unloading = 4,
     27     Uninitialized = 5,
     28     Unknown = -1
     29 }
     30 
     31 namespace Microsoft.WindowsMobile.Samples.Location
     32 {
     33 
     34     [StructLayout(LayoutKind.Sequential)]
     35     internal struct FileTime
     36     {
     37         int dwLowDateTime;
     38         int dwHighDateTime;
     39     }
     40 
     41     /// <summary>
     42     /// GpsDeviceState holds the state of the gps device and the friendly name if the 
     43     /// gps supports them.
     44     /// </summary>
     45     [StructLayout(LayoutKind.Sequential)]
     46     public class GpsDeviceState
     47     {
     48         public static int GpsMaxFriendlyName = 64;
     49         public static int GpsDeviceStructureSize = 216;
     50 
     51         int serviceState = 0;
     52         /// <summary>
     53         /// State of the GPS Intermediate Driver service
     54         /// </summary>
     55         public GpsServiceState ServiceState
     56         {
     57             get {return (GpsServiceState)serviceState;}
     58         }
     59 
     60         int deviceState = 0;
     61         /// <summary>
     62         /// Status of the actual GPS device driver.
     63         /// </summary>
     64         public GpsServiceState DeviceState
     65         {
     66             get {return (GpsServiceState)deviceState;}
     67         }
     68 
     69         string friendlyName = "";
     70         /// <summary>
     71         /// Friendly name of the real GPS device we are currently using.
     72         /// </summary>
     73         public string FriendlyName
     74         {
     75             get {return friendlyName;}
     76         }
     77 
     78         /// <summary>
     79         /// Constructor of GpsDeviceState.  It copies values from the native pointer 
     80         /// passed in. 
     81         /// </summary>
     82         /// <param name="pGpsDevice">Native pointer to memory that contains
     83         /// the GPS_DEVICE data</param>
     84         public GpsDeviceState(IntPtr pGpsDevice)
     85         {
     86             // make sure our pointer is valid
     87             if (pGpsDevice == IntPtr.Zero)
     88             {
     89                 throw new ArgumentException();
     90             }
     91 
     92             // read in the service state which starts at offset 8
     93             serviceState = Marshal.ReadInt32(pGpsDevice, 8);
     94             // read in the device state which starts at offset 12
     95             deviceState = Marshal.ReadInt32(pGpsDevice, 12);
     96 
     97             // the friendly name starts at offset 88
     98             IntPtr pFriendlyName = (IntPtr)(pGpsDevice.ToInt32() + 88);
     99             // marshal the native string into our gpsFriendlyName
    100             friendlyName = Marshal.PtrToStringUni(pFriendlyName);
    101         }
    102     }
    103 }

    GpsPosition.cs //处理经纬度坐标的类

    View Code
    #region Using directives

    using System;
    using System.Runtime.InteropServices;
    using System.Collections;

    #endregion

    namespace Microsoft.WindowsMobile.Samples.Location
    {
        
    #region Internal Native Structures
        [StructLayout(LayoutKind.Sequential)]
        
    internal struct SystemTime
        {
            
    internal short year;
            
    internal short month;
            
    internal short dayOfWeek;
            
    internal short day;
            
    internal short hour;
            
    internal short minute;
            
    internal short second;
            
    internal short millisecond;
        }

        [StructLayout(LayoutKind.Sequential)]
        
    internal struct SatelliteArray
        {
            
    int a, b, c, d, e, f, g, h, i, j, k, l;

            
    public int Count
            {
                
    get { return 12; }
            }

            
    public int this[int value]
            {
                
    get
                {
                    
    if (value == 0return a;
                    
    else if (value == 1return b;
                    
    else if (value == 2return c;
                    
    else if (value == 3return d;
                    
    else if (value == 4return e;
                    
    else if (value == 5return f;
                    
    else if (value == 6return g;
                    
    else if (value == 7return h;
                    
    else if (value == 8return i;
                    
    else if (value == 9return j;
                    
    else if (value == 10return k;
                    
    else if (value == 11return l;
                    
    else throw new ArgumentOutOfRangeException("value must be 0 - 11");
                }
            }
        }
        
    #endregion
        
        
    enum FixQuality : int
        {
            Unknown 
    = 0,
            Gps,
            DGps
        }
        
    enum FixType : int
        {
            Unknown 
    = 0,
            XyD,
            XyzD
        }

        
    enum FixSelection : int
        {
            Unknown 
    = 0,
            Auto,
            Manual
        }

        
    public class Satellite
        {
            
    public Satellite() { }
            
    public Satellite(int id, int elevation, int azimuth, int signalStrength)
            {
                
    this.id = id;
                
    this.elevation = elevation;
                
    this.azimuth = azimuth;
                
    this.signalStrength = signalStrength;
            }

            
    int id;
            
    /// <summary>
            
    /// Id of the satellite
            
    /// </summary>
            public int Id
            {
                
    get
                {
                    
    return id;
                }
                
    set
                {
                    id 
    = value;
                }
            }


            
    int elevation;
            
    /// <summary>
            
    /// Elevation of the satellite
            
    /// </summary>
            public int Elevation
            {
                
    get
                {
                    
    return elevation;
                }
                
    set
                {
                    elevation 
    = value;
                }
            }


            
    int azimuth;
            
    /// <summary>
            
    /// Azimuth of the satellite
            
    /// </summary>
            public int Azimuth
            {
                
    get
                {
                    
    return azimuth;
                }
                
    set
                {
                    azimuth 
    = value;
                }
            }


            
    int signalStrength;
            
    /// <summary>
            
    /// SignalStrenth of the satellite
            
    /// </summary>
            public int SignalStrength
            {
                
    get
                {
                    
    return signalStrength;
                }
                
    set
                {
                    signalStrength 
    = value;
                }
            }

        }

        [StructLayout(LayoutKind.Sequential)]
        
    public class GpsPosition
        {
            
    internal GpsPosition() { }
            
    internal static int GPS_VALID_UTC_TIME = 0x00000001;
            
    internal static int GPS_VALID_LATITUDE = 0x00000002;
            
    internal static int GPS_VALID_LONGITUDE = 0x00000004;
            
    internal static int GPS_VALID_SPEED = 0x00000008;
            
    internal static int GPS_VALID_HEADING = 0x00000010;
            
    internal static int GPS_VALID_MAGNETIC_VARIATION = 0x00000020;
            
    internal static int GPS_VALID_ALTITUDE_WRT_SEA_LEVEL = 0x00000040;
            
    internal static int GPS_VALID_ALTITUDE_WRT_ELLIPSOID = 0x00000080;
            
    internal static int GPS_VALID_POSITION_DILUTION_OF_PRECISION = 0x00000100;
            
    internal static int GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION = 0x00000200;
            
    internal static int GPS_VALID_VERTICAL_DILUTION_OF_PRECISION = 0x00000400;
            
    internal static int GPS_VALID_SATELLITE_COUNT = 0x00000800;
            
    internal static int GPS_VALID_SATELLITES_USED_PRNS = 0x00001000;
            
    internal static int GPS_VALID_SATELLITES_IN_VIEW = 0x00002000;
            
    internal static int GPS_VALID_SATELLITES_IN_VIEW_PRNS = 0x00004000;
            
    internal static int GPS_VALID_SATELLITES_IN_VIEW_ELEVATION = 0x00008000;
            
    internal static int GPS_VALID_SATELLITES_IN_VIEW_AZIMUTH = 0x00010000;
            
    internal static int GPS_VALID_SATELLITES_IN_VIEW_SIGNAL_TO_NOISE_RATIO = 0x00020000;


            
    internal int dwVersion = 1;             // Current version of GPSID client is using.
            internal int dwSize = 0;                // sizeof(_GPS_POSITION)

            
    // Not all fields in the structure below are guaranteed to be valid.  
            
    // Which fields are valid depend on GPS device being used, how stale the API allows
            
    // the data to be, and current signal.
            
    // Valid fields are specified in dwValidFields, based on GPS_VALID_XXX flags.
            internal int dwValidFields = 0;

            
    // Additional information about this location structure (GPS_DATA_FLAGS_XXX)
            internal int dwFlags = 0;

            
    //** Time related
            internal SystemTime stUTCTime = new SystemTime();     //  UTC according to GPS clock.

            
    //** Position + heading related
            internal double dblLatitude = 0.0;            // Degrees latitude.  North is positive
            internal double dblLongitude = 0.0;           // Degrees longitude.  East is positive
            internal float flSpeed = 0.0f;                // Speed in knots
            internal float flHeading = 0.0f;              // Degrees heading (course made good).  True North=0
            internal double dblMagneticVariation = 0.0;   // Magnetic variation.  East is positive
            internal float flAltitudeWRTSeaLevel = 0.0f;  // Altitute with regards to sea level, in meters
            internal float flAltitudeWRTEllipsoid = 0.0f// Altitude with regards to ellipsoid, in meters

            
    //** Quality of this fix
            
    // Where did we get fix from?
            internal FixQuality fixQuality = FixQuality.Unknown;        
            
    // Is this 2d or 3d fix?
            internal FixType fixType = FixType.Unknown;      
            
    // Auto or manual selection between 2d or 3d mode
            internal FixSelection selectionType = FixSelection.Unknown;     
            
    // Position Dilution Of Precision
            internal float flPositionDilutionOfPrecision = 0.0f;
            
    // Horizontal Dilution Of Precision
            internal float flHorizontalDilutionOfPrecision = 0.0f
            
    // Vertical Dilution Of Precision
            internal float flVerticalDilutionOfPrecision = 0.0f;   

            
    //** Satellite information
            
    // Number of satellites used in solution
            internal int dwSatelliteCount = 0;               
            
    // PRN numbers of satellites used in the solution
            internal SatelliteArray rgdwSatellitesUsedPRNs = new SatelliteArray();
            
    // Number of satellites in view.  From 0-GPS_MAX_SATELLITES
            internal int dwSatellitesInView = 0;                                             
            
    // PRN numbers of satellites in view
            internal SatelliteArray rgdwSatellitesInViewPRNs = new SatelliteArray();                
            
    // Elevation of each satellite in view
            internal SatelliteArray rgdwSatellitesInViewElevation = new SatelliteArray();           
            
    // Azimuth of each satellite in view
            internal SatelliteArray rgdwSatellitesInViewAzimuth = new SatelliteArray();             
            
    // Signal to noise ratio of each satellite in view
            internal SatelliteArray rgdwSatellitesInViewSignalToNoiseRatio = new SatelliteArray();  
    View Code
     /// <summary>
            
    /// UTC according to GPS clock.
            
    /// </summary>
            public DateTime Time
            {
                
    get
                {
                    DateTime time 
    = new DateTime(stUTCTime.year, stUTCTime.month, stUTCTime.day, stUTCTime.hour, stUTCTime.minute, stUTCTime.second, stUTCTime.millisecond);
                    
    return time;
                }

            }
            
    /// <summary>
            
    /// True if the Time property is valid, false if invalid
            
    /// </summary>
            public bool TimeValid
            {
                
    get { return (dwValidFields & GPS_VALID_UTC_TIME) != 0; }
            }


            
    /// <summary>
            
    /// Satellites used in the solution
            
    /// </summary>
            
    /// <returns>Array of Satellites</returns>
            public Satellite[] GetSatellitesInSolution()
            {
                Satellite[] inViewSatellites 
    = GetSatellitesInView();
                ArrayList list 
    = new ArrayList();
                
    for (int index = 0; index < dwSatelliteCount; index++)
                {
                    Satellite found 
    = null;
                    
    for (int viewIndex = 0; viewIndex < inViewSatellites.Length && found == null; viewIndex++)
                    {
                        
    if (rgdwSatellitesUsedPRNs[index] == inViewSatellites[viewIndex].Id)
                        {
                            found 
    = inViewSatellites[viewIndex];
                            list.Add(found);
                        }
                    }
                }

                
    return (Satellite[])list.ToArray(typeof(Satellite));
            }
            
    /// <summary>
            
    /// True if the SatellitesInSolution property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInSolutionValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_USED_PRNS) != 0; }
            }



            
    /// <summary>
            
    /// Satellites in view
            
    /// </summary>
            
    /// <returns>Array of Satellites</returns>
            public Satellite[] GetSatellitesInView()
            {
                Satellite[] satellites 
    = null;
                
    if (dwSatellitesInView != 0)
                {
                    satellites 
    = new Satellite[dwSatellitesInView];
                    
    for (int index = 0; index < satellites.Length; index++)
                    {
                        satellites[index] 
    = new Satellite();
                        satellites[index].Azimuth 
    = rgdwSatellitesInViewAzimuth[index];
                        satellites[index].Elevation 
    = rgdwSatellitesInViewElevation[index];
                        satellites[index].Id 
    = rgdwSatellitesInViewPRNs[index];
                        satellites[index].SignalStrength 
    = rgdwSatellitesInViewSignalToNoiseRatio[index];
                    }
                }

                
    return satellites;
            }
            
    /// <summary>
            
    /// True if the SatellitesInView property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInViewValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; }
            }


            
    /// <summary>
            
    /// Number of satellites used in solution
            
    /// </summary>
            public int SatelliteCount
            {
                
    get { return dwSatelliteCount; }
            }
            
    /// <summary>
            
    /// True if the SatelliteCount property is valid, false if invalid
            
    /// </summary>
            public bool SatelliteCountValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITE_COUNT) != 0; }
            }

            
    /// <summary>
            
    /// Number of satellites in view.  
            
    /// </summary>
            public int SatellitesInViewCount
            {
                
    get { return dwSatellitesInView; }
            }
            
    /// <summary>
            
    /// True if the SatellitesInViewCount property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInViewCountValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; }
            }

            
    /// <summary>
            
    /// Speed in knots
            
    /// </summary>
            public float Speed
            {
                
    get { return flSpeed; }
            }
            
    /// <summary>
            
    /// True if the Speed property is valid, false if invalid
            
    /// </summary>
            public bool SpeedValid
            {
                
    get { return (dwValidFields & GPS_VALID_SPEED) != 0; }
            }

            
    /// <summary>
            
    /// Altitude with regards to ellipsoid, in meters
            
    /// </summary>
            public float EllipsoidAltitude
            {
                
    get { return flAltitudeWRTEllipsoid; }
            }
            
    /// <summary>
            
    /// True if the EllipsoidAltitude property is valid, false if invalid
            
    /// </summary>
            public bool EllipsoidAltitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_ELLIPSOID) != 0; }
            }

            
    /// <summary>
            
    /// Altitute with regards to sea level, in meters
            
    /// </summary>
            public float SeaLevelAltitude
            {
                
    get { return flAltitudeWRTSeaLevel; }
            }
            
    /// <summary>
            
    /// True if the SeaLevelAltitude property is valid, false if invalid
            
    /// </summary>
            public bool SeaLevelAltitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_SEA_LEVEL) != 0; }
            }

            
    /// <summary>
            
    /// Latitude in decimal degrees.  North is positive
            
    /// </summary>
            public double Latitude
            {
                
    get { return dblLatitude; }
            }
            
    /// <summary>
            
    /// Latitude in degrees, minutes, seconds.  North is positive
            
    /// </summary>
            public DegreesMinutesSeconds LatitudeInDegreesMinutesSeconds
            {
                
    get { return new DegreesMinutesSeconds(dblLatitude); }
            }

            
    /// <summary>
            
    /// True if the Latitude property is valid, false if invalid
            
    /// </summary>
            public bool LatitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_LATITUDE) != 0; }
            }

            
    /// <summary>
            
    /// Longitude in decimal degrees.  East is positive
            
    /// </summary>
            public double Longitude
            {
                
    get { return dblLongitude; }
            }

            
    /// <summary>
            
    /// Longitude in degrees, minutes, seconds.  East is positive
            
    /// </summary>
            public DegreesMinutesSeconds LongitudeInDegreesMinutesSeconds
            {
                
    get { return new DegreesMinutesSeconds(dblLongitude); }
            }
            
    /// <summary>
            
    /// True if the Longitude property is valid, false if invalid
            
    /// </summary>
            public bool LongitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_LONGITUDE) != 0; }
            }

            
    /// <summary>
            
    /// Degrees heading (course made good).  True North=0
            
    /// </summary>
            public float Heading
            {
                
    get { return flHeading; }
            }
            
    /// <summary>
            
    /// True if the Heading property is valid, false if invalid
            
    /// </summary>
            public bool HeadingValid
            {
                
    get { return (dwValidFields & GPS_VALID_HEADING) != 0; }
            }

            
    /// <summary>
            
    /// Position Dilution Of Precision
            
    /// </summary>
            public float PositionDilutionOfPrecision
            {
                
    get { return flPositionDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the PositionDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool PositionDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_POSITION_DILUTION_OF_PRECISION) != 0; }
            }

            
    /// <summary>
            
    /// Horizontal Dilution Of Precision
            
    /// </summary>
            public float HorizontalDilutionOfPrecision
            {
                
    get { return flHorizontalDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the HorizontalDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool HorizontalDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION) != 0; }
            }

            
    /// <summary>
            
    /// Vertical Dilution Of Precision
            
    /// </summary>
            public float VerticalDilutionOfPrecision
            {
                
    get { return flVerticalDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the VerticalDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool VerticalDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_VERTICAL_DILUTION_OF_PRECISION) != 0; }
            }
        }

    }
    View Code
        /// <summary>
            
    /// UTC according to GPS clock.
            
    /// </summary>
            public DateTime Time
            {
                
    get
                {
                    DateTime time 
    = new DateTime(stUTCTime.year, stUTCTime.month, stUTCTime.day, stUTCTime.hour, stUTCTime.minute, stUTCTime.second, stUTCTime.millisecond);
                    
    return time;
                }

            }
            
    /// <summary>
            
    /// True if the Time property is valid, false if invalid
            
    /// </summary>
            public bool TimeValid
            {
                
    get { return (dwValidFields & GPS_VALID_UTC_TIME) != 0; }
            }


            
    /// <summary>
            
    /// Satellites used in the solution
            
    /// </summary>
            
    /// <returns>Array of Satellites</returns>
            public Satellite[] GetSatellitesInSolution()
            {
                Satellite[] inViewSatellites 
    = GetSatellitesInView();
                ArrayList list 
    = new ArrayList();
                
    for (int index = 0; index < dwSatelliteCount; index++)
                {
                    Satellite found 
    = null;
                    
    for (int viewIndex = 0; viewIndex < inViewSatellites.Length && found == null; viewIndex++)
                    {
                        
    if (rgdwSatellitesUsedPRNs[index] == inViewSatellites[viewIndex].Id)
                        {
                            found 
    = inViewSatellites[viewIndex];
                            list.Add(found);
                        }
                    }
                }

                
    return (Satellite[])list.ToArray(typeof(Satellite));
            }
            
    /// <summary>
            
    /// True if the SatellitesInSolution property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInSolutionValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_USED_PRNS) != 0; }
            }



            
    /// <summary>
            
    /// Satellites in view
            
    /// </summary>
            
    /// <returns>Array of Satellites</returns>
            public Satellite[] GetSatellitesInView()
            {
                Satellite[] satellites 
    = null;
                
    if (dwSatellitesInView != 0)
                {
                    satellites 
    = new Satellite[dwSatellitesInView];
                    
    for (int index = 0; index < satellites.Length; index++)
                    {
                        satellites[index] 
    = new Satellite();
                        satellites[index].Azimuth 
    = rgdwSatellitesInViewAzimuth[index];
                        satellites[index].Elevation 
    = rgdwSatellitesInViewElevation[index];
                        satellites[index].Id 
    = rgdwSatellitesInViewPRNs[index];
                        satellites[index].SignalStrength 
    = rgdwSatellitesInViewSignalToNoiseRatio[index];
                    }
                }

                
    return satellites;
            }
            
    /// <summary>
            
    /// True if the SatellitesInView property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInViewValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; }
            }


            
    /// <summary>
            
    /// Number of satellites used in solution
            
    /// </summary>
            public int SatelliteCount
            {
                
    get { return dwSatelliteCount; }
            }
            
    /// <summary>
            
    /// True if the SatelliteCount property is valid, false if invalid
            
    /// </summary>
            public bool SatelliteCountValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITE_COUNT) != 0; }
            }

            
    /// <summary>
            
    /// Number of satellites in view.  
            
    /// </summary>
            public int SatellitesInViewCount
            {
                
    get { return dwSatellitesInView; }
            }
            
    /// <summary>
            
    /// True if the SatellitesInViewCount property is valid, false if invalid
            
    /// </summary>
            public bool SatellitesInViewCountValid
            {
                
    get { return (dwValidFields & GPS_VALID_SATELLITES_IN_VIEW) != 0; }
            }

            
    /// <summary>
            
    /// Speed in knots
            
    /// </summary>
            public float Speed
            {
                
    get { return flSpeed; }
            }
            
    /// <summary>
            
    /// True if the Speed property is valid, false if invalid
            
    /// </summary>
            public bool SpeedValid
            {
                
    get { return (dwValidFields & GPS_VALID_SPEED) != 0; }
            }

            
    /// <summary>
            
    /// Altitude with regards to ellipsoid, in meters
            
    /// </summary>
            public float EllipsoidAltitude
            {
                
    get { return flAltitudeWRTEllipsoid; }
            }
            
    /// <summary>
            
    /// True if the EllipsoidAltitude property is valid, false if invalid
            
    /// </summary>
            public bool EllipsoidAltitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_ELLIPSOID) != 0; }
            }

            
    /// <summary>
            
    /// Altitute with regards to sea level, in meters
            
    /// </summary>
            public float SeaLevelAltitude
            {
                
    get { return flAltitudeWRTSeaLevel; }
            }
            
    /// <summary>
            
    /// True if the SeaLevelAltitude property is valid, false if invalid
            
    /// </summary>
            public bool SeaLevelAltitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_ALTITUDE_WRT_SEA_LEVEL) != 0; }
            }

            
    /// <summary>
            
    /// Latitude in decimal degrees.  North is positive
            
    /// </summary>
            public double Latitude
            {
                
    get { return dblLatitude; }
            }
            
    /// <summary>
            
    /// Latitude in degrees, minutes, seconds.  North is positive
            
    /// </summary>
            public DegreesMinutesSeconds LatitudeInDegreesMinutesSeconds
            {
                
    get { return new DegreesMinutesSeconds(dblLatitude); }
            }

            
    /// <summary>
            
    /// True if the Latitude property is valid, false if invalid
            
    /// </summary>
            public bool LatitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_LATITUDE) != 0; }
            }

            
    /// <summary>
            
    /// Longitude in decimal degrees.  East is positive
            
    /// </summary>
            public double Longitude
            {
                
    get { return dblLongitude; }
            }

            
    /// <summary>
            
    /// Longitude in degrees, minutes, seconds.  East is positive
            
    /// </summary>
            public DegreesMinutesSeconds LongitudeInDegreesMinutesSeconds
            {
                
    get { return new DegreesMinutesSeconds(dblLongitude); }
            }
            
    /// <summary>
            
    /// True if the Longitude property is valid, false if invalid
            
    /// </summary>
            public bool LongitudeValid
            {
                
    get { return (dwValidFields & GPS_VALID_LONGITUDE) != 0; }
            }

            
    /// <summary>
            
    /// Degrees heading (course made good).  True North=0
            
    /// </summary>
            public float Heading
            {
                
    get { return flHeading; }
            }
            
    /// <summary>
            
    /// True if the Heading property is valid, false if invalid
            
    /// </summary>
            public bool HeadingValid
            {
                
    get { return (dwValidFields & GPS_VALID_HEADING) != 0; }
            }

            
    /// <summary>
            
    /// Position Dilution Of Precision
            
    /// </summary>
            public float PositionDilutionOfPrecision
            {
                
    get { return flPositionDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the PositionDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool PositionDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_POSITION_DILUTION_OF_PRECISION) != 0; }
            }

            
    /// <summary>
            
    /// Horizontal Dilution Of Precision
            
    /// </summary>
            public float HorizontalDilutionOfPrecision
            {
                
    get { return flHorizontalDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the HorizontalDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool HorizontalDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION) != 0; }
            }

            
    /// <summary>
            
    /// Vertical Dilution Of Precision
            
    /// </summary>
            public float VerticalDilutionOfPrecision
            {
                
    get { return flVerticalDilutionOfPrecision; }
            }
            
    /// <summary>
            
    /// True if the VerticalDilutionOfPrecision property is valid, false if invalid
            
    /// </summary>
            public bool VerticalDilutionOfPrecisionValid
            {
                
    get { return (dwValidFields & GPS_VALID_VERTICAL_DILUTION_OF_PRECISION) != 0; }
            }
        }

    }

    LocationChangedEventArgs.cs  //GPS定位位置改变触发事件处理类

    View Code
     1 //
     2 // Copyright (c) Microsoft Corporation.  All rights reserved.
     3 //
     4 //
     5 // Use of this sample source code is subject to the terms of the Microsoft
     6 // license agreement under which you licensed this sample source code. If
     7 // you did not accept the terms of the license agreement, you are not
     8 // authorized to use this sample source code. For the terms of the license,
     9 // please see the license agreement between you and Microsoft or, if applicable,
    10 // see the LICENSE.RTF on your install media or the root of your tools installation.
    11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
    12 //
    13 #region Using directives
    14 
    15 using System;
    16 
    17 #endregion
    18 
    19 namespace Microsoft.WindowsMobile.Samples.Location
    20 {
    21     /// <summary>
    22     /// Event args used for LocationChanged events.
    23     /// </summary>
    24     public class LocationChangedEventArgs: EventArgs
    25     {
    26         public LocationChangedEventArgs(GpsPosition position)
    27         {
    28             this.position = position;
    29         }
    30 
    31         /// <summary>
    32         /// Gets the new position when the GPS reports a new position.
    33         /// </summary>
    34         public GpsPosition Position
    35         {
    36             get 
    37             {
    38                 return position;
    39             }
    40         }
    41 
    42         private GpsPosition position;
    43 
    44     }
    45 }

    Utils.cs  

    View Code
     1 //
     2 // Copyright (c) Microsoft Corporation.  All rights reserved.
     3 //
     4 //
     5 // Use of this sample source code is subject to the terms of the Microsoft
     6 // license agreement under which you licensed this sample source code. If
     7 // you did not accept the terms of the license agreement, you are not
     8 // authorized to use this sample source code. For the terms of the license,
     9 // please see the license agreement between you and Microsoft or, if applicable,
    10 // see the LICENSE.RTF on your install media or the root of your tools installation.
    11 // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
    12 //
    13 #region Using directives
    14 
    15 using System;
    16 
    17 #endregion
    18 
    19 namespace Microsoft.WindowsMobile.Samples.Location.Utils
    20 {
    21     /// <summary>
    22     /// Summary description for Utils.
    23     /// </summary>
    24     public class Utils
    25     {
    26         public Utils()
    27         {
    28         }
    29 
    30         public static IntPtr LocalAlloc(int byteCount)
    31         {
    32             IntPtr ptr = Win32.LocalAlloc(Win32.LMEM_ZEROINIT, byteCount);
    33             if (ptr == IntPtr.Zero)
    34             {
    35                 throw new OutOfMemoryException();
    36             }
    37 
    38             return ptr;
    39         }
    40 
    41         public static void LocalFree(IntPtr hMem)
    42         {
    43             IntPtr ptr = Win32.LocalFree(hMem);
    44             if (ptr != IntPtr.Zero)
    45             {
    46                 throw new ArgumentException();
    47             }
    48         }
    49     }
    50 
    51     public class Win32
    52     {
    53         public const int LMEM_ZEROINIT = 0x40;
    54         [System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "#33", SetLastError = true)]
    55         public static extern IntPtr LocalAlloc(int flags, int byteCount);
    56 
    57         [System.Runtime.InteropServices.DllImport("coredll.dll", EntryPoint = "#36", SetLastError = true)]
    58         public static extern IntPtr LocalFree(IntPtr hMem);
    59     }
    60 }

     希望能给想我一样的初接触Windows Mobile开发的程序员一些帮助。

  • 相关阅读:
    暑假N天乐【比赛篇】 —— 2019牛客暑期多校训练营(第七场)
    暑假N天乐【比赛篇】 —— 2019杭电暑期多校训练营(第六场)
    暑假N天乐【比赛篇】 —— 2019杭电暑期多校训练营(第五场)
    暑假N天乐【比赛篇】 —— 2019牛客暑期多校训练营(第六场)
    暑假N天乐【比赛篇】 —— 2019牛客暑期多校训练营(第五场)
    暑假N天乐【比赛篇】 —— 2019杭电暑期多校训练营(第四场)
    暑假N天乐【比赛篇】 —— 2019杭电暑期多校训练营(第三场)
    暑假N天乐【比赛篇】 —— 2019牛客暑期多校训练营(第四场)
    暑假N天乐【比赛篇】 —— 2019牛客暑期多校训练营(第三场)
    暑假N天乐【比赛篇】 —— 2019杭电暑期多校训练营(第二场)
  • 原文地址:https://www.cnblogs.com/angleSJW/p/2099808.html
Copyright © 2011-2022 走看看