WindowsMobile6.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)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13//
14//Copyright(c)MicrosoftCorporation.Allrightsreserved.
15//
16//
17//UseofthissourcecodeissubjecttothetermsoftheMicrosoftend-user
18//licenseagreement(EULA)underwhichyoulicensedthisSOFTWAREPRODUCT.
19//IfyoudidnotacceptthetermsoftheEULA,youarenotauthorizedtouse
20//thissourcecode.ForacopyoftheEULA,pleaseseetheLICENSE.RTFonyour
21//installmedia.
22usingSystem;
23usingSystem.Drawing;
24usingSystem.Collections;
25usingSystem.Windows.Forms;
26usingSystem.Data;
27usingMicrosoft.WindowsMobile.Samples.Location;
28
29namespaceGpsTest
30{
31/// summary
32///SummarydescriptionforForm1.
33/// /summary
34publicclassForm1:System.Windows.Forms.Form
35{
36privateSystem.Windows.Forms.MenuItemexitMenuItem;
37privateSystem.Windows.Forms.MainMenumainMenu1;
38privateSystem.Windows.Forms.Labelstatus;
39privateMenuItemmenuItem2;
40privateMenuItemstartGpsMenuItem;
41privateMenuItemstopGpsMenuItem;
42
43
44privateEventHandlerupdateDataHandler;
45GpsDeviceStatedevice=null;
46GpsPositionposition=null;
47
48Gpsgps=newGps();
49
50publicForm1()
51{
52//
53//RequiredforWindowsFormDesignersupport
54//
55InitializeComponent();
56
57//
58//TODO:AddanyconstructorcodeafterInitializeComponentcall
59//
60}
61/// summary
62///Cleanupanyresourcesbeingused.
63/// /summary
64protectedoverridevoidDispose(booldisposing)
65{
66base.Dispose(disposing);
67}
68#regionWindowsFormDesignergeneratedcode
69/// summary
70///RequiredmethodforDesignersupport-donotmodify
71///thecontentsofthismethodwiththecodeeditor.
72/// /summary
73privatevoidInitializeComponent()
74{
75this.mainMenu1=newSystem.Windows.Forms.MainMenu();
76this.exitMenuItem=newSystem.Windows.Forms.MenuItem();
77this.menuItem2=newSystem.Windows.Forms.MenuItem();
78this.startGpsMenuItem=newSystem.Windows.Forms.MenuItem();
79this.stopGpsMenuItem=newSystem.Windows.Forms.MenuItem();
80this.status=newSystem.Windows.Forms.Label();
81//
82//mainMenu1
83//
84this.mainMenu1.MenuItems.Add(this.exitMenuItem);
85this.mainMenu1.MenuItems.Add(this.menuItem2);
86//
87//exitMenuItem
88//
89this.exitMenuItem.Text="Exit";
90this.exitMenuItem.Click+=newSystem.EventHandler(this.exitMenuItem_Click);
91//
92//menuItem2
93//
94this.menuItem2.MenuItems.Add(this.startGpsMenuItem);
95this.menuItem2.MenuItems.Add(this.stopGpsMenuItem);
96this.menuItem2.Text="GPS";
97//
98//startGpsMenuItem
99//
100this.startGpsMenuItem.Text="StartGPS";
101this.startGpsMenuItem.Click+=newSystem.EventHandler(this.startGpsMenuItem_Click);
102//
103//stopGpsMenuItem
104//
105this.stopGpsMenuItem.Enabled=false;
106this.stopGpsMenuItem.Text="StopGPS";
107this.stopGpsMenuItem.Click+=newSystem.EventHandler(this.stopGpsMenuItem_Click);
108//
109//status
110//
111this.status.Location=newSystem.Drawing.Point(0,0);
112this.status.Size=newSystem.Drawing.Size(237,173);
113this.status.Text="label1";
114//
115//Form1
116//
117this.ClientSize=newSystem.Drawing.Size(240,268);
118this.Controls.Add(this.status);
119this.Menu=this.mainMenu1;
120this.Text="Form1";
121this.Load+=newSystem.EventHandler(this.Form1_Load);
122this.Closed+=newSystem.EventHandler(this.Form1_Closed);
123
124}
125#endregion
126
127/// summary
128///Themainentrypointfortheapplication.
129/// /summary
130
131staticvoidMain()
132{
133Application.Run(newForm1());
134}
135
136privatevoidexitMenuItem_Click(objectsender,EventArgse)
137{
138if(gps.Opened)
139{
140gps.Close();
141}
142
143Close();
144}
145
146privatevoidForm1_Load(objectsender,System.EventArgse)
147{
148updateDataHandler=newEventHandler(UpdateData);
149
150status.Text="";
151
152status.Width=Screen.PrimaryScreen.WorkingArea.Width;
153status.Height=Screen.PrimaryScreen.WorkingArea.Height;
154
155gps.DeviceStateChanged+=newDeviceStateChangedEventHandler(gps_DeviceStateChanged);
156gps.LocationChanged+=newLocationChangedEventHandler(gps_LocationChanged);
157}
158
159protectedvoidgps_LocationChanged(objectsender,LocationChangedEventArgsargs)
160{
161position=args.Position;
162
163//calltheUpdateDatamethodviatheupdateDataHandlersothatwe
164//updatetheUIontheUIthread
165Invoke(updateDataHandler);
166
167}
168
169voidgps_DeviceStateChanged(objectsender,DeviceStateChangedEventArgsargs)
170{
171device=args.DeviceState;
172
173//calltheUpdateDatamethodviatheupdateDataHandlersothatwe
174//updatetheUIontheUIthread
175Invoke(updateDataHandler);
176}
177
178voidUpdateData(objectsender,System.EventArgsargs)
179{
180if(gps.Opened)
181{
182stringstr="";
183if(device!=null)
184{
185str=device.FriendlyName+""+device.ServiceState+","+device.DeviceState+"\n";
186}
187
188if(position!=null)
189{
190
191if(position.LatitudeValid)
192{
193str+="Latitude(DD):\n"+position.Latitude+"\n";
194str+="Latitude(D,M,S):\n"+position.LatitudeInDegreesMinutesSeconds+"\n";
195}
196
197if(position.LongitudeValid)
198{
199str+="Longitude(DD):\n"+position.Longitude+"\n";
200str+="Longitude(D,M,S):\n"+position.LongitudeInDegreesMinutesSeconds+"\n";
201}
202
203if(position.SatellitesInSolutionValid
204position.SatellitesInViewValid
205position.SatelliteCountValid)
206{
207str+="SatelliteCount:\n"+position.GetSatellitesInSolution().Length+"/"+
208position.GetSatellitesInView().Length+"("+
209position.SatelliteCount+")\n";
210}
211
212if(position.TimeValid)
213{
214str+="Time:\n"+position.Time.ToString()+"\n";
215}
216}
217
218status.Text=str;
219
220}
221}
222
223privatevoidForm1_Closed(objectsender,System.EventArgse)
224{
225if(gps.Opened)
226{
227gps.Close();
228}
229}
230
231privatevoidstopGpsMenuItem_Click(objectsender,EventArgse)
232{
233if(gps.Opened)
234{
235gps.Close();
236}
237
238startGpsMenuItem.Enabled=true;
239stopGpsMenuItem.Enabled=false;
240}
241
242privatevoidstartGpsMenuItem_Click(objectsender,EventArgse)
243{
244if(!gps.Opened)
245{
246gps.Open();
247}
248
249startGpsMenuItem.Enabled=false;
250stopGpsMenuItem.Enabled=true;
251}
252}
253}

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

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

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

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13#regionUsingdirectives
14
15usingSystem;
16
17#endregion
18
19namespaceMicrosoft.WindowsMobile.Samples.Location
20{
21/// summary
22///classthatrepresentsagpscoordinateindegrees,minutes,andseconds.
23/// /summary
24publicclassDegreesMinutesSeconds
25{
26
27boolisPositive;
28/// summary
29///Returnstrueifthedegrees,minutesandsecondsrefertoapositivevalue,
30///falseotherwise.
31/// /summary
32publicboolIsPositive
33{
34get{returnisPositive;}
35}
36
37uintdegrees;
38/// summary
39///Thedegreesunitofthecoordinate
40/// /summary
41publicuintDegrees
42{
43get{returndegrees;}
44}
45
46uintminutes;
47/// summary
48///Theminutesunitofthecoordinate
49/// /summary
50publicuintMinutes
51{
52get{returnminutes;}
53}
54
55doubleseconds;
56/// summary
57///Thesecondsunitofthecoordinate
58/// /summary
59publicdoubleSeconds
60{
61get{returnseconds;}
62}
63
64/// summary
65///ConstructsanewinstanceofDegreesMinutesSecondsconverting
66///fromdecimaldegrees
67/// /summary
68/// param Initialvalueasdecimaldegrees /param
69publicDegreesMinutesSeconds(doubledecimalDegrees)
70{
71isPositive=(decimalDegrees 0);
72
73degrees=(uint)Math.Abs(decimalDegrees);
74
75doubledoubleMinutes=(Math.Abs(decimalDegrees)-Math.Abs((double)degrees))*60.0;
76minutes=(uint)doubleMinutes;
77
78seconds=(doubleMinutes-(double)minutes)*60.0;
79}
80
81/// summary
82///ConstructsanewinstanceofDegreesMinutesSeconds
83/// /summary
84/// param Trueifthecoordinatesarepositivecoordinate,falseifthey
85///arenegativecoordinates. /param
86/// param Degreesunitofthecoordinate /param
87/// param Minutesunitofthecoordinate /param
88/// param Secondsunitofthecoordinate.Thisshouldbeapositivevalue. /param
89publicDegreesMinutesSeconds(boolisPositive,uintdegrees,uintminutes,doubleseconds)
90{
91this.isPositive=isPositive;
92this.degrees=degrees;
93this.minutes=minutes;
94this.seconds=seconds;
95}
96
97/// summary
98///Convertsthedecimal,minutes,secondscoordinateto
99///decimaldegrees
100/// /summary
101/// returns /returns
102publicdoubleToDecimalDegrees()
103{
104doubleval=(double)degrees+((double)minutes/60.0)+((double)seconds/3600.0);
105val=isPositive?val:val*-1;
106returnval;
107}
108
109/// summary
110///Convertstheinstancetoastringinformat:DM'S"
111/// /summary
112/// returns stringrepresentationofdegrees,minutes,seconds /returns
113publicoverridestringToString()
114{
115returndegrees+"d"+minutes+"'"+seconds+"\"";
116}
117}
118}

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

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13#regionUsingdirectives
14
15usingSystem;
16
17#endregion
18
19namespaceMicrosoft.WindowsMobile.Samples.Location
20{
21/// summary
22///EventargsusedforDeviceStateChangedevent.
23/// /summary
24publicclassDeviceStateChangedEventArgs:EventArgs
25{
26publicDeviceStateChangedEventArgs(GpsDeviceStatedeviceState)
27{
28this.deviceState=deviceState;
29}
30
31/// summary
32///GetsthenewdevicestatewhentheGPSreportsanewdevicestate.
33/// /summary
34publicGpsDeviceStateDeviceState
35{
36get
37{
38returndeviceState;
39}
40}
41
42privateGpsDeviceStatedeviceState;
43}
44}

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

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13usingSystem;
14usingSystem.Runtime.InteropServices;
15usingSystem.Collections;
16usingSystem.Text;
17
18
19namespaceMicrosoft.WindowsMobile.Samples.Location
20{
21publicdelegatevoidLocationChangedEventHandler(objectsender,LocationChangedEventArgsargs);
22publicdelegatevoidDeviceStateChangedEventHandler(objectsender,DeviceStateChangedEventArgsargs);
23
24/// summary
25///SummarydescriptionforGPS.
26/// /summary
27publicclassGps
28{
29//handletothegpsdevice
30IntPtrgpsHandle=IntPtr.Zero;
31
32//handletothenativeeventthatissignalledwhentheGPS
33//devicesgetsanewlocation
34IntPtrnewLocationHandle=IntPtr.Zero;
35
36//handletothenativeeventthatissignalledwhentheGPS
37//devicestatechanges
38IntPtrdeviceStateChangedHandle=IntPtr.Zero;
39
40//handletothenativeeventthatweusetostopourevent
41//thread
42IntPtrstopHandle=IntPtr.Zero;
43
44//holdsoureventthreadinstance
45System.Threading.ThreadgpsEventThread=null;View Code 1eventLocationChangedEventHandlerlocationChanged;
2
3/// summary
4///EventthatisraisedwhentheGPSlocactiondatachanges
5/// /summary
6publiceventLocationChangedEventHandlerLocationChanged
7{
8add
9{
10locationChanged+=value;
11
12//createoureventthreadonlyiftheuserdecidestolisten
13CreateGpsEventThread();
14}
15remove
16{
17locationChanged-=value;
18}
19}
20
21
22eventDeviceStateChangedEventHandlerdeviceStateChanged;
23
24/// summary
25///EventthatisraisedwhentheGPSdevicestatechanges
26/// /summary
27publiceventDeviceStateChangedEventHandlerDeviceStateChanged
28{
29add
30{
31deviceStateChanged+=value;
32
33//createoureventthreadonlyiftheuserdecidestolisten
34CreateGpsEventThread();
35}
36remove
37{
38deviceStateChanged-=value;
39}
40}
41
42/// summary
43///True:TheGPSdevicehasbeenopened.False:Ithasnotbeenopened
44/// /summary
45publicboolOpened
46{
47get{returngpsHandle!=IntPtr.Zero;}
48}
49
50publicGps()
51{
52}
53
54~Gps()
55{
56//makesurethattheGPSwasclosed.
57Close();
58}
59
60/// summary
61///OpenstheGPSdeviceandpreparestoreceivedatafromit.
62/// /summary
63publicvoidOpen()
64{
65if(!Opened)
66{
67//createhandlesforGPSevents
68newLocationHandle=CreateEvent(IntPtr.Zero,0,0,null);
69deviceStateChangedHandle=CreateEvent(IntPtr.Zero,0,0,null);
70stopHandle=CreateEvent(IntPtr.Zero,0,0,null);
71
72gpsHandle=GPSOpenDevice(newLocationHandle,deviceStateChangedHandle,null,0);
73
74//ifeventswerehookedupbeforethedevicewasopened,we'llneed
75//tocreatethegpseventthread.
76if(locationChanged!=null||deviceStateChanged!=null)
77{
78CreateGpsEventThread();
79}
80}
81}
82
83/// summary
84///Closesthegpsdevice.
85/// /summary
86publicvoidClose()
87{
88if(gpsHandle!=IntPtr.Zero)
89{
90GPSCloseDevice(gpsHandle);
91gpsHandle=IntPtr.Zero;
92}
93
94//Setournativestopeventsowecanexitoureventthread.
95if(stopHandle!=IntPtr.Zero)
96{
97EventModify(stopHandle,eventSet);
98}
99
100//blockuntiloureventthreadisfinishedbefore
101//wecloseournativeeventhandles
102lock(this)
103{
104if(newLocationHandle!=IntPtr.Zero)
105{
106CloseHandle(newLocationHandle);
107newLocationHandle=IntPtr.Zero;
108}
109
110if(deviceStateChangedHandle!=IntPtr.Zero)
111{
112CloseHandle(deviceStateChangedHandle);
113deviceStateChangedHandle=IntPtr.Zero;
114}
115
116if(stopHandle!=IntPtr.Zero)
117{
118CloseHandle(stopHandle);
119stopHandle=IntPtr.Zero;
120}
121}
122}
123
124/// summary
125///GetthepositionreportedbytheGPSreceiver
126/// /summary
127/// returns GpsPositionclasswithallthepositiondetails /returns
128publicGpsPositionGetPosition()
129{
130returnGetPosition(TimeSpan.Zero);
131}
132
133
134/// summary
135///GetthepositionreportedbytheGPSreceiverthatisnoolderthan
136///themaxAgepassedin
137/// /summary
138/// param Maxageofthegpspositiondatathatyouwantback.
139///Ifthereisnodatawithintherequiredage,nullisreturned.
140///ifmaxAge==TimeSpan.Zero,thentheageofthedataisignored /param
141/// returns GpsPositionclasswithallthepositiondetails /returns
142publicGpsPositionGetPosition(TimeSpanmaxAge)
143{
144GpsPositiongpsPosition=null;
145if(Opened)
146{
147//allocatethenecessarymemoryonthenativeside.Wehaveaclass(GpsPosition)that
148//hasthesamememorylayoutasitsnativecounterpart
149IntPtrptr=Utils.LocalAlloc(Marshal.SizeOf(typeof(GpsPosition)));
150
151//fillintherequiredfields
152gpsPosition=newGpsPosition();
153gpsPosition.dwVersion=1;
154gpsPosition.dwSize=Marshal.SizeOf(typeof(GpsPosition));
155
156//Marshalourdatatothenativepointerweallocated.
157Marshal.StructureToPtr(gpsPosition,ptr,false);
158
159//callnativemethodpassinginournativebuffer
160intresult=GPSGetPosition(gpsHandle,ptr,500000,0);
161if(result==0)
162{
163//nativecallsucceeded,marshalnativedatatoourmanageddata
164gpsPosition=(GpsPosition)Marshal.PtrToStructure(ptr,typeof(GpsPosition));
165
166if(maxAge!=TimeSpan.Zero)
167{
168//checktoseeifthedataisrecentenough.
169if(!gpsPosition.TimeValid||DateTime.Now-maxAge gpsPosition.Time)
170{
171gpsPosition=null;
172}
173}
174}
175
176//freeournativememory
177Utils.LocalFree(ptr);
178}
179
180returngpsPosition;
181}View Code 1/// summary
2///Queriesthedevicestate.
3/// /summary
4/// returns Devicestateinformation /returns
5publicGpsDeviceStateGetDeviceState()
6{
7GpsDeviceStatedevice=null;
8
9//allocateabufferonthenativeside.Sincethe
10IntPtrpGpsDevice=Utils.LocalAlloc(GpsDeviceState.GpsDeviceStructureSize);
11
12//GPS_DEVICEstructurehasarraysofcharacters,it'seasiertojust
13//writedirectlyintomemoryratherthancreateamanagedstructurewith
14//thesamelayout.
15Marshal.WriteInt32(pGpsDevice,1);//writeoutGPSversionof1
16Marshal.WriteInt32(pGpsDevice,4,GpsDeviceState.GpsDeviceStructureSize);//writeoutdwSizeofstructure
17
18intresult=GPSGetDeviceState(pGpsDevice);
19
20if(result==0)
21{
22//instantiatetheGpsDeviceStateclasspassinginthenativepointer
23device=newGpsDeviceState(pGpsDevice);
24}
25
26//freeournativememory
27Utils.LocalFree(pGpsDevice);
28
29returndevice;
30}
31
32/// summary
33///Createsoureventthreadthatwillreceivenativeevents
34/// /summary
35privatevoidCreateGpsEventThread()
36{
37//weonlywanttocreatethethreadifwedon'thaveonecreatedalready
38//andwehaveopenedthegpsdevice
39if(gpsEventThread==null gpsHandle!=IntPtr.Zero)
40{
41//CreateandstartthreadtolistenforGPSevents
42gpsEventThread=newSystem.Threading.Thread(newSystem.Threading.ThreadStart(WaitForGpsEvents));
43gpsEventThread.Start();
44}
45}
46
47/// summary
48///MethodusedtolistenfornativeeventsfromtheGPS.
49/// /summary
50privatevoidWaitForGpsEvents()
51{
52lock(this)
53{
54boollistening=true;
55//allocate3handlesworthofmemorytopasstoWaitForMultipleObjects
56IntPtrhandles=Utils.LocalAlloc(12);
57
58//writethethreehandleswearelisteningfor.
59Marshal.WriteInt32(handles,0,stopHandle.ToInt32());
60Marshal.WriteInt32(handles,4,deviceStateChangedHandle.ToInt32());
61Marshal.WriteInt32(handles,8,newLocationHandle.ToInt32());
62
63while(listening)
64{
65intobj=WaitForMultipleObjects(3,handles,0,-1);
66if(obj!=waitFailed)
67{
68switch(obj)
69{
70case0:
71//we'vebeensignalledtostop
72listening=false;
73break;
74case1:
75//devicestatehaschanged
76if(deviceStateChanged!=null)
77{
78deviceStateChanged(this,newDeviceStateChangedEventArgs(GetDeviceState()));
79}
80break;
81case2:
82//locationhaschanged
83if(locationChanged!=null)
84{
85locationChanged(this,newLocationChangedEventArgs(GetPosition()));
86}
87break;
88}
89}
90}
91
92//freethememoryweallocatedforthenativehandles
93Utils.LocalFree(handles);
94
95//clearourgpsEventThreadsothatwecanrecreatethisthreadagain
96//iftheeventsarehookedupagain.
97gpsEventThread=null;
98}
99}
100
101#regionPInvokestogpsapi.dll
102[DllImport("gpsapi.dll")]
103staticexternIntPtrGPSOpenDevice(IntPtrhNewLocationData,IntPtrhDeviceStateChange,stringszDeviceName,intdwFlags);
104
105[DllImport("gpsapi.dll")]
106staticexternintGPSCloseDevice(IntPtrhGPSDevice);
107
108[DllImport("gpsapi.dll")]
109staticexternintGPSGetPosition(IntPtrhGPSDevice,IntPtrpGPSPosition,intdwMaximumAge,intdwFlags);
110
111[DllImport("gpsapi.dll")]
112staticexternintGPSGetDeviceState(IntPtrpGPSDevice);
113#endregion
114
115#regionPInvokestocoredll.dll
116[DllImport("coredll.dll")]
117staticexternIntPtrCreateEvent(IntPtrlpEventAttributes,intbManualReset,intbInitialState,StringBuilderlpName);
118
119[DllImport("coredll.dll")]
120staticexternintCloseHandle(IntPtrhObject);
121
122constintwaitFailed=-1;
123[DllImport("coredll.dll")]
124staticexternintWaitForMultipleObjects(intnCount,IntPtrlpHandles,intfWaitAll,intdwMilliseconds);
125
126constinteventSet=3;
127[DllImport("coredll.dll")]
128staticexternintEventModify(IntPtrhHandle,intdwFunc);
129
130#endregion

GpsDeviceState.cs GPS设备的状态管理

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13#regionUsingdirectives
14
15usingSystem;
16usingSystem.Runtime.InteropServices;
17
18#endregion
19
20publicenumGpsServiceState:int
21{
22Off=0,
23On=1,
24StartingUp=2,
25ShuttingDown=3,
26Unloading=4,
27Uninitialized=5,
28Unknown=-1
29}
30
31namespaceMicrosoft.WindowsMobile.Samples.Location
32{
33
34[StructLayout(LayoutKind.Sequential)]
35internalstructFileTime
36{
37intdwLowDateTime;
38intdwHighDateTime;
39}
40
41/// summary
42///GpsDeviceStateholdsthestateofthegpsdeviceandthefriendlynameifthe
43///gpssupportsthem.
44/// /summary
45[StructLayout(LayoutKind.Sequential)]
46publicclassGpsDeviceState
47{
48publicstaticintGpsMaxFriendlyName=64;
49publicstaticintGpsDeviceStructureSize=216;
50
51intserviceState=0;
52/// summary
53///StateoftheGPSIntermediateDriverservice
54/// /summary
55publicGpsServiceStateServiceState
56{
57get{return(GpsServiceState)serviceState;}
58}
59
60intdeviceState=0;
61/// summary
62///StatusoftheactualGPSdevicedriver.
63/// /summary
64publicGpsServiceStateDeviceState
65{
66get{return(GpsServiceState)deviceState;}
67}
68
69stringfriendlyName="";
70/// summary
71///FriendlynameoftherealGPSdevicewearecurrentlyusing.
72/// /summary
73publicstringFriendlyName
74{
75get{returnfriendlyName;}
76}
77
78/// summary
79///ConstructorofGpsDeviceState.Itcopiesvaluesfromthenativepointer
80///passedin.
81/// /summary
82/// param Nativepointertomemorythatcontains
83///theGPS_DEVICEdata /param
84publicGpsDeviceState(IntPtrpGpsDevice)
85{
86//makesureourpointerisvalid
87if(pGpsDevice==IntPtr.Zero)
88{
89thrownewArgumentException();
90}
91
92//readintheservicestatewhichstartsatoffset8
93serviceState=Marshal.ReadInt32(pGpsDevice,8);
94//readinthedevicestatewhichstartsatoffset12
95deviceState=Marshal.ReadInt32(pGpsDevice,12);
96
97//thefriendlynamestartsatoffset88
98IntPtrpFriendlyName=(IntPtr)(pGpsDevice.ToInt32()+88);
99//marshalthenativestringintoourgpsFriendlyName
100friendlyName=Marshal.PtrToStringUni(pFriendlyName);
101}
102}
103}

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

View Code #regionUsingdirectives

usingSystem;
usingSystem.Runtime.InteropServices;
usingSystem.Collections;

#endregion

namespaceMicrosoft.WindowsMobile.Samples.Location
{
#regionInternalNativeStructures
[StructLayout(LayoutKind.Sequential)]
internalstructSystemTime
{
internalshortyear;
internalshortmonth;
internalshortdayOfWeek;
internalshortday;
internalshorthour;
internalshortminute;
internalshortsecond;
internalshortmillisecond;
}

[StructLayout(LayoutKind.Sequential)]
internalstructSatelliteArray
{
inta,b,c,d,e,f,g,h,i,j,k,l;

publicintCount
{
get{return12;}
}

publicintthis[intvalue]
{
get
{
if(value==0)returna;
elseif(value==1)returnb;
elseif(value==2)returnc;
elseif(value==3)returnd;
elseif(value==4)returne;
elseif(value==5)returnf;
elseif(value==6)returng;
elseif(value==7)returnh;
elseif(value==8)returni;
elseif(value==9)returnj;
elseif(value==10)returnk;
elseif(value==11)returnl;
elsethrownewArgumentOutOfRangeException("valuemustbe0-11");
}
}
}
#endregion

enumFixQuality:int
{
Unknown=0,
Gps,
DGps
}
enumFixType:int
{
Unknown=0,
XyD,
XyzD
}

enumFixSelection:int
{
Unknown=0,
Auto,
Manual
}

publicclassSatellite
{
publicSatellite(){}
publicSatellite(intid,intelevation,intazimuth,intsignalStrength)
{
this.id=id;
this.elevation=elevation;
this.azimuth=azimuth;
this.signalStrength=signalStrength;
}

intid;
/// summary
///Idofthesatellite
/// /summary
publicintId
{
get
{
returnid;
}
set
{
id=value;
}
}


intelevation;
/// summary
///Elevationofthesatellite
/// /summary
publicintElevation
{
get
{
returnelevation;
}
set
{
elevation=value;
}
}


intazimuth;
/// summary
///Azimuthofthesatellite
/// /summary
publicintAzimuth
{
get
{
returnazimuth;
}
set
{
azimuth=value;
}
}


intsignalStrength;
/// summary
///SignalStrenthofthesatellite
/// /summary
publicintSignalStrength
{
get
{
returnsignalStrength;
}
set
{
signalStrength=value;
}
}

}

[StructLayout(LayoutKind.Sequential)]
publicclassGpsPosition
{
internalGpsPosition(){}
internalstaticintGPS_VALID_UTC_TIME=0x00000001;
internalstaticintGPS_VALID_LATITUDE=0x00000002;
internalstaticintGPS_VALID_LONGITUDE=0x00000004;
internalstaticintGPS_VALID_SPEED=0x00000008;
internalstaticintGPS_VALID_HEADING=0x00000010;
internalstaticintGPS_VALID_MAGNETIC_VARIATION=0x00000020;
internalstaticintGPS_VALID_ALTITUDE_WRT_SEA_LEVEL=0x00000040;
internalstaticintGPS_VALID_ALTITUDE_WRT_ELLIPSOID=0x00000080;
internalstaticintGPS_VALID_POSITION_DILUTION_OF_PRECISION=0x00000100;
internalstaticintGPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION=0x00000200;
internalstaticintGPS_VALID_VERTICAL_DILUTION_OF_PRECISION=0x00000400;
internalstaticintGPS_VALID_SATELLITE_COUNT=0x00000800;
internalstaticintGPS_VALID_SATELLITES_USED_PRNS=0x00001000;
internalstaticintGPS_VALID_SATELLITES_IN_VIEW=0x00002000;
internalstaticintGPS_VALID_SATELLITES_IN_VIEW_PRNS=0x00004000;
internalstaticintGPS_VALID_SATELLITES_IN_VIEW_ELEVATION=0x00008000;
internalstaticintGPS_VALID_SATELLITES_IN_VIEW_AZIMUTH=0x00010000;
internalstaticintGPS_VALID_SATELLITES_IN_VIEW_SIGNAL_TO_NOISE_RATIO=0x00020000;


internalintdwVersion=1;//CurrentversionofGPSIDclientisusing.
internalintdwSize=0;//sizeof(_GPS_POSITION)

//Notallfieldsinthestructurebelowareguaranteedtobevalid.
//WhichfieldsarevaliddependonGPSdevicebeingused,howstaletheAPIallows
//thedatatobe,andcurrentsignal.
//ValidfieldsarespecifiedindwValidFields,basedonGPS_VALID_XXXflags.
internalintdwValidFields=0;

//Additionalinformationaboutthislocationstructure(GPS_DATA_FLAGS_XXX)
internalintdwFlags=0;

//**Timerelated
internalSystemTimestUTCTime=newSystemTime();//UTCaccordingtoGPSclock.

//**Position+headingrelated
internaldoubledblLatitude=0.0;//Degreeslatitude.Northispositive
internaldoubledblLongitude=0.0;//Degreeslongitude.Eastispositive
internalfloatflSpeed=0.0f;//Speedinknots
internalfloatflHeading=0.0f;//Degreesheading(coursemadegood).TrueNorth=0
internaldoubledblMagneticVariation=0.0;//Magneticvariation.Eastispositive
internalfloatflAltitudeWRTSeaLevel=0.0f;//Altitutewithregardstosealevel,inmeters
internalfloatflAltitudeWRTEllipsoid=0.0f;//Altitudewithregardstoellipsoid,inmeters

//**Qualityofthisfix
//Wheredidwegetfixfrom?
internalFixQualityfixQuality=FixQuality.Unknown;
//Isthis2dor3dfix?
internalFixTypefixType=FixType.Unknown;
//Autoormanualselectionbetween2dor3dmode
internalFixSelectionselectionType=FixSelection.Unknown;
//PositionDilutionOfPrecision
internalfloatflPositionDilutionOfPrecision=0.0f;
//HorizontalDilutionOfPrecision
internalfloatflHorizontalDilutionOfPrecision=0.0f;
//VerticalDilutionOfPrecision
internalfloatflVerticalDilutionOfPrecision=0.0f;

//**Satelliteinformation
//Numberofsatellitesusedinsolution
internalintdwSatelliteCount=0;
//PRNnumbersofsatellitesusedinthesolution
internalSatelliteArrayrgdwSatellitesUsedPRNs=newSatelliteArray();
//Numberofsatellitesinview.From0-GPS_MAX_SATELLITES
internalintdwSatellitesInView=0;
//PRNnumbersofsatellitesinview
internalSatelliteArrayrgdwSatellitesInViewPRNs=newSatelliteArray();
//Elevationofeachsatelliteinview
internalSatelliteArrayrgdwSatellitesInViewElevation=newSatelliteArray();
//Azimuthofeachsatelliteinview
internalSatelliteArrayrgdwSatellitesInViewAzimuth=newSatelliteArray();
//Signaltonoiseratioofeachsatelliteinview
internalSatelliteArrayrgdwSatellitesInViewSignalToNoiseRatio=newSatelliteArray();View Code /// summary
///UTCaccordingtoGPSclock.
/// /summary
publicDateTimeTime
{
get
{
DateTimetime=newDateTime(stUTCTime.year,stUTCTime.month,stUTCTime.day,stUTCTime.hour,stUTCTime.minute,stUTCTime.second,stUTCTime.millisecond);
returntime;
}

}
/// summary
///TrueiftheTimepropertyisvalid,falseifinvalid
/// /summary
publicboolTimeValid
{
get{return(dwValidFields GPS_VALID_UTC_TIME)!=0;}
}


/// summary
///Satellitesusedinthesolution
/// /summary
/// returns ArrayofSatellites /returns
publicSatellite[]GetSatellitesInSolution()
{
Satellite[]inViewSatellites=GetSatellitesInView();
ArrayListlist=newArrayList();
for(intindex=0;index dwSatelliteCount;index++)
{
Satellitefound=null;
for(intviewIndex=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
///TrueiftheSatellitesInSolutionpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInSolutionValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_USED_PRNS)!=0;}
}



/// summary
///Satellitesinview
/// /summary
/// returns ArrayofSatellites /returns
publicSatellite[]GetSatellitesInView()
{
Satellite[]satellites=null;
if(dwSatellitesInView!=0)
{
satellites=newSatellite[dwSatellitesInView];
for(intindex=0;index satellites.Length;index++)
{
satellites[index]=newSatellite();
satellites[index].Azimuth=rgdwSatellitesInViewAzimuth[index];
satellites[index].Elevation=rgdwSatellitesInViewElevation[index];
satellites[index].Id=rgdwSatellitesInViewPRNs[index];
satellites[index].SignalStrength=rgdwSatellitesInViewSignalToNoiseRatio[index];
}
}

returnsatellites;
}
/// summary
///TrueiftheSatellitesInViewpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInViewValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_IN_VIEW)!=0;}
}


/// summary
///Numberofsatellitesusedinsolution
/// /summary
publicintSatelliteCount
{
get{returndwSatelliteCount;}
}
/// summary
///TrueiftheSatelliteCountpropertyisvalid,falseifinvalid
/// /summary
publicboolSatelliteCountValid
{
get{return(dwValidFields GPS_VALID_SATELLITE_COUNT)!=0;}
}

/// summary
///Numberofsatellitesinview.
/// /summary
publicintSatellitesInViewCount
{
get{returndwSatellitesInView;}
}
/// summary
///TrueiftheSatellitesInViewCountpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInViewCountValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_IN_VIEW)!=0;}
}

/// summary
///Speedinknots
/// /summary
publicfloatSpeed
{
get{returnflSpeed;}
}
/// summary
///TrueiftheSpeedpropertyisvalid,falseifinvalid
/// /summary
publicboolSpeedValid
{
get{return(dwValidFields GPS_VALID_SPEED)!=0;}
}

/// summary
///Altitudewithregardstoellipsoid,inmeters
/// /summary
publicfloatEllipsoidAltitude
{
get{returnflAltitudeWRTEllipsoid;}
}
/// summary
///TrueiftheEllipsoidAltitudepropertyisvalid,falseifinvalid
/// /summary
publicboolEllipsoidAltitudeValid
{
get{return(dwValidFields GPS_VALID_ALTITUDE_WRT_ELLIPSOID)!=0;}
}

/// summary
///Altitutewithregardstosealevel,inmeters
/// /summary
publicfloatSeaLevelAltitude
{
get{returnflAltitudeWRTSeaLevel;}
}
/// summary
///TrueiftheSeaLevelAltitudepropertyisvalid,falseifinvalid
/// /summary
publicboolSeaLevelAltitudeValid
{
get{return(dwValidFields GPS_VALID_ALTITUDE_WRT_SEA_LEVEL)!=0;}
}

/// summary
///Latitudeindecimaldegrees.Northispositive
/// /summary
publicdoubleLatitude
{
get{returndblLatitude;}
}
/// summary
///Latitudeindegrees,minutes,seconds.Northispositive
/// /summary
publicDegreesMinutesSecondsLatitudeInDegreesMinutesSeconds
{
get{returnnewDegreesMinutesSeconds(dblLatitude);}
}

/// summary
///TrueiftheLatitudepropertyisvalid,falseifinvalid
/// /summary
publicboolLatitudeValid
{
get{return(dwValidFields GPS_VALID_LATITUDE)!=0;}
}

/// summary
///Longitudeindecimaldegrees.Eastispositive
/// /summary
publicdoubleLongitude
{
get{returndblLongitude;}
}

/// summary
///Longitudeindegrees,minutes,seconds.Eastispositive
/// /summary
publicDegreesMinutesSecondsLongitudeInDegreesMinutesSeconds
{
get{returnnewDegreesMinutesSeconds(dblLongitude);}
}
/// summary
///TrueiftheLongitudepropertyisvalid,falseifinvalid
/// /summary
publicboolLongitudeValid
{
get{return(dwValidFields GPS_VALID_LONGITUDE)!=0;}
}

/// summary
///Degreesheading(coursemadegood).TrueNorth=0
/// /summary
publicfloatHeading
{
get{returnflHeading;}
}
/// summary
///TrueiftheHeadingpropertyisvalid,falseifinvalid
/// /summary
publicboolHeadingValid
{
get{return(dwValidFields GPS_VALID_HEADING)!=0;}
}

/// summary
///PositionDilutionOfPrecision
/// /summary
publicfloatPositionDilutionOfPrecision
{
get{returnflPositionDilutionOfPrecision;}
}
/// summary
///TrueifthePositionDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolPositionDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_POSITION_DILUTION_OF_PRECISION)!=0;}
}

/// summary
///HorizontalDilutionOfPrecision
/// /summary
publicfloatHorizontalDilutionOfPrecision
{
get{returnflHorizontalDilutionOfPrecision;}
}
/// summary
///TrueiftheHorizontalDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolHorizontalDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION)!=0;}
}

/// summary
///VerticalDilutionOfPrecision
/// /summary
publicfloatVerticalDilutionOfPrecision
{
get{returnflVerticalDilutionOfPrecision;}
}
/// summary
///TrueiftheVerticalDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolVerticalDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_VERTICAL_DILUTION_OF_PRECISION)!=0;}
}
}

}View Code /// summary
///UTCaccordingtoGPSclock.
/// /summary
publicDateTimeTime
{
get
{
DateTimetime=newDateTime(stUTCTime.year,stUTCTime.month,stUTCTime.day,stUTCTime.hour,stUTCTime.minute,stUTCTime.second,stUTCTime.millisecond);
returntime;
}

}
/// summary
///TrueiftheTimepropertyisvalid,falseifinvalid
/// /summary
publicboolTimeValid
{
get{return(dwValidFields GPS_VALID_UTC_TIME)!=0;}
}


/// summary
///Satellitesusedinthesolution
/// /summary
/// returns ArrayofSatellites /returns
publicSatellite[]GetSatellitesInSolution()
{
Satellite[]inViewSatellites=GetSatellitesInView();
ArrayListlist=newArrayList();
for(intindex=0;index dwSatelliteCount;index++)
{
Satellitefound=null;
for(intviewIndex=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
///TrueiftheSatellitesInSolutionpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInSolutionValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_USED_PRNS)!=0;}
}



/// summary
///Satellitesinview
/// /summary
/// returns ArrayofSatellites /returns
publicSatellite[]GetSatellitesInView()
{
Satellite[]satellites=null;
if(dwSatellitesInView!=0)
{
satellites=newSatellite[dwSatellitesInView];
for(intindex=0;index satellites.Length;index++)
{
satellites[index]=newSatellite();
satellites[index].Azimuth=rgdwSatellitesInViewAzimuth[index];
satellites[index].Elevation=rgdwSatellitesInViewElevation[index];
satellites[index].Id=rgdwSatellitesInViewPRNs[index];
satellites[index].SignalStrength=rgdwSatellitesInViewSignalToNoiseRatio[index];
}
}

returnsatellites;
}
/// summary
///TrueiftheSatellitesInViewpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInViewValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_IN_VIEW)!=0;}
}


/// summary
///Numberofsatellitesusedinsolution
/// /summary
publicintSatelliteCount
{
get{returndwSatelliteCount;}
}
/// summary
///TrueiftheSatelliteCountpropertyisvalid,falseifinvalid
/// /summary
publicboolSatelliteCountValid
{
get{return(dwValidFields GPS_VALID_SATELLITE_COUNT)!=0;}
}

/// summary
///Numberofsatellitesinview.
/// /summary
publicintSatellitesInViewCount
{
get{returndwSatellitesInView;}
}
/// summary
///TrueiftheSatellitesInViewCountpropertyisvalid,falseifinvalid
/// /summary
publicboolSatellitesInViewCountValid
{
get{return(dwValidFields GPS_VALID_SATELLITES_IN_VIEW)!=0;}
}

/// summary
///Speedinknots
/// /summary
publicfloatSpeed
{
get{returnflSpeed;}
}
/// summary
///TrueiftheSpeedpropertyisvalid,falseifinvalid
/// /summary
publicboolSpeedValid
{
get{return(dwValidFields GPS_VALID_SPEED)!=0;}
}

/// summary
///Altitudewithregardstoellipsoid,inmeters
/// /summary
publicfloatEllipsoidAltitude
{
get{returnflAltitudeWRTEllipsoid;}
}
/// summary
///TrueiftheEllipsoidAltitudepropertyisvalid,falseifinvalid
/// /summary
publicboolEllipsoidAltitudeValid
{
get{return(dwValidFields GPS_VALID_ALTITUDE_WRT_ELLIPSOID)!=0;}
}

/// summary
///Altitutewithregardstosealevel,inmeters
/// /summary
publicfloatSeaLevelAltitude
{
get{returnflAltitudeWRTSeaLevel;}
}
/// summary
///TrueiftheSeaLevelAltitudepropertyisvalid,falseifinvalid
/// /summary
publicboolSeaLevelAltitudeValid
{
get{return(dwValidFields GPS_VALID_ALTITUDE_WRT_SEA_LEVEL)!=0;}
}

/// summary
///Latitudeindecimaldegrees.Northispositive
/// /summary
publicdoubleLatitude
{
get{returndblLatitude;}
}
/// summary
///Latitudeindegrees,minutes,seconds.Northispositive
/// /summary
publicDegreesMinutesSecondsLatitudeInDegreesMinutesSeconds
{
get{returnnewDegreesMinutesSeconds(dblLatitude);}
}

/// summary
///TrueiftheLatitudepropertyisvalid,falseifinvalid
/// /summary
publicboolLatitudeValid
{
get{return(dwValidFields GPS_VALID_LATITUDE)!=0;}
}

/// summary
///Longitudeindecimaldegrees.Eastispositive
/// /summary
publicdoubleLongitude
{
get{returndblLongitude;}
}

/// summary
///Longitudeindegrees,minutes,seconds.Eastispositive
/// /summary
publicDegreesMinutesSecondsLongitudeInDegreesMinutesSeconds
{
get{returnnewDegreesMinutesSeconds(dblLongitude);}
}
/// summary
///TrueiftheLongitudepropertyisvalid,falseifinvalid
/// /summary
publicboolLongitudeValid
{
get{return(dwValidFields GPS_VALID_LONGITUDE)!=0;}
}

/// summary
///Degreesheading(coursemadegood).TrueNorth=0
/// /summary
publicfloatHeading
{
get{returnflHeading;}
}
/// summary
///TrueiftheHeadingpropertyisvalid,falseifinvalid
/// /summary
publicboolHeadingValid
{
get{return(dwValidFields GPS_VALID_HEADING)!=0;}
}

/// summary
///PositionDilutionOfPrecision
/// /summary
publicfloatPositionDilutionOfPrecision
{
get{returnflPositionDilutionOfPrecision;}
}
/// summary
///TrueifthePositionDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolPositionDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_POSITION_DILUTION_OF_PRECISION)!=0;}
}

/// summary
///HorizontalDilutionOfPrecision
/// /summary
publicfloatHorizontalDilutionOfPrecision
{
get{returnflHorizontalDilutionOfPrecision;}
}
/// summary
///TrueiftheHorizontalDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolHorizontalDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_HORIZONTAL_DILUTION_OF_PRECISION)!=0;}
}

/// summary
///VerticalDilutionOfPrecision
/// /summary
publicfloatVerticalDilutionOfPrecision
{
get{returnflVerticalDilutionOfPrecision;}
}
/// summary
///TrueiftheVerticalDilutionOfPrecisionpropertyisvalid,falseifinvalid
/// /summary
publicboolVerticalDilutionOfPrecisionValid
{
get{return(dwValidFields GPS_VALID_VERTICAL_DILUTION_OF_PRECISION)!=0;}
}
}

}

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

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13#regionUsingdirectives
14
15usingSystem;
16
17#endregion
18
19namespaceMicrosoft.WindowsMobile.Samples.Location
20{
21/// summary
22///EventargsusedforLocationChangedevents.
23/// /summary
24publicclassLocationChangedEventArgs:EventArgs
25{
26publicLocationChangedEventArgs(GpsPositionposition)
27{
28this.position=position;
29}
30
31/// summary
32///GetsthenewpositionwhentheGPSreportsanewposition.
33/// /summary
34publicGpsPositionPosition
35{
36get
37{
38returnposition;
39}
40}
41
42privateGpsPositionposition;
43
44}
45}

Utils.cs

View Code 1//
2//Copyright(c)MicrosoftCorporation.Allrightsreserved.
3//
4//
5//UseofthissamplesourcecodeissubjecttothetermsoftheMicrosoft
6//licenseagreementunderwhichyoulicensedthissamplesourcecode.If
7//youdidnotacceptthetermsofthelicenseagreement,youarenot
8//authorizedtousethissamplesourcecode.Forthetermsofthelicense,
9//pleaseseethelicenseagreementbetweenyouandMicrosoftor,ifapplicable,
10//seetheLICENSE.RTFonyourinstallmediaortherootofyourtoolsinstallation.
11//THESAMPLESOURCECODEISPROVIDED"ASIS",WITHNOWARRANTIESORINDEMNITIES.
12//
13#regionUsingdirectives
14
15usingSystem;
16
17#endregion
18
19namespaceMicrosoft.WindowsMobile.Samples.Location.Utils
20{
21/// summary
22///SummarydescriptionforUtils.
23/// /summary
24publicclassUtils
25{
26publicUtils()
27{
28}
29
30publicstaticIntPtrLocalAlloc(intbyteCount)
31{
32IntPtrptr=Win32.LocalAlloc(Win32.LMEM_ZEROINIT,byteCount);
33if(ptr==IntPtr.Zero)
34{
35thrownewOutOfMemoryException();
36}
37
38returnptr;
39}
40
41publicstaticvoidLocalFree(IntPtrhMem)
42{
43IntPtrptr=Win32.LocalFree(hMem);
44if(ptr!=IntPtr.Zero)
45{
46thrownewArgumentException();
47}
48}
49}
50
51publicclassWin32
52{
53publicconstintLMEM_ZEROINIT=0x40;
54[System.Runtime.InteropServices.DllImport("coredll.dll",EntryPoint="#33",SetLastError=true)]
55publicstaticexternIntPtrLocalAlloc(intflags,intbyteCount);
56
57[System.Runtime.InteropServices.DllImport("coredll.dll",EntryPoint="#36",SetLastError=true)]
58publicstaticexternIntPtrLocalFree(IntPtrhMem);
59}
60}

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