2012-10-29 70 views
4

我是C#的初學者,但我已經使用了很多Java。我正嘗試在我的應用程序中使用以下代碼來獲取位置數據。我想提出一個Windows 8桌面應用程序來使用我的設備的GPS傳感器:在Windows 8桌面應用中獲取位置

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Windows.Devices.Sensors; 
using Windows.Devices.Geolocation; 
using Windows.Devices.Geolocation.Geoposition; 
using Windows.Foundation; 

namespace Hello_Location 
{ 
    public partial class Form1 : 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     async private void Form1_Load(object sender, EventArgs e) 
     { 
      Geolocator loc = new Geolocator(); 
      try 
      { 
       loc.DesiredAccuracy = PositionAccuracy.High; 
       Geoposition pos = await loc.GetGeopositionAsync(); 
       var lat = pos.Coordinate.Latitude; 
       var lang = pos.Coordinate.Longitude; 
       Console.WriteLine(lat+ " " +lang); 
      } 
      catch (System.UnauthorizedAccessException) 
      { 
       // handle error 
      } 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 

     } 
    } 
} 

我得到這個錯誤:

'await' requires that the type 'Windows.Foundation.IAsyncOperation' have a suitable GetAwaiter method. Are you missing a using directive for 'System'? C:\Users\clidy\documents\visual studio 2012\Projects\Hello-Location\Hello-Location\Form1.cs

我該如何解決這個問題?

如果您可以指向我一些C#位置資源和Windows desktop應用程序的傳感器API,那麼它將非常有用。在Google上搜索時,我只能獲得Windows RT API。

+0

您引用的類型僅適用於Windows應用商店應用。您可能能夠關注[這些](http://www.wintellect.com/CS/blogs/jeffreyr/archive/2011/09/20/using-the-windows-runtime-from-a-non-metro- application.aspx)手動添加引用和構建的說明,但我沒有經驗。 –

+0

實際上[這篇文章](http://software.intel.com/en-us/articles/geo-location-on-windows-8-desktop-applications-using-winrt)聲稱它非常簡單。我還沒有測試過。我將在未來兩週內做更多的研究。 – Bart

回答

3

要解決您的錯誤,您必須參考Bart在問題的評論中給出的link

You might need to add a reference to System.Runtime.WindowsRuntime.dll as well if you are using mapped types like Windows Runtime event handlers:

...

That assembly resides in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5

最近,我發現了一個 「解決方案」 爲一個類似的問題:C# desktop application doesn't share my physical location。也許你可能對我的方法感興趣:https://stackoverflow.com/a/14645837/674700

它更像是一種解決方法,它並不針對Windows 8,但它最終工作。

+1

爲我工作..謝謝.. !! –

2

alex's solution works! 添加引用和地理位置API開始工作就像一個魅力!所以做其他傳感器的異步方法!

這裏是我剛開始使用它的一個功能。

async public void UseGeoLocation() 
{ 
    Geolocator _GeoLocator = new Geolocator(); 
    Geoposition _GeoPosition = 
     await _GeoLocator.GetGeopositionAsync(); 

    Clipboard.Clear(); 
    Clipboard.SetText("latitude," + 
     _GeoPosition.Coordinate.Latitude.ToString() + 
     "," + "longitude," + _GeoPosition.Coordinate.Longitude.ToString() + 
     "," + "heading," + _GeoPosition.Coordinate.Heading.ToString() + 
     "," + "speed," + _GeoPosition.Coordinate.Speed.ToString()); 

    Application.Exit(); 
} 
相關問題