简体   繁体   English

如何在C#应用程序中使用HTML5地理定位

[英]How can I use HTML5 geolocation in C# application

I'm developing an anti-theft software to get computers exact location. 我正在开发一种防盗软件,以获得计算机的确切位置。 Notebooks with built-in gps are very rare in my country so I have to use HTML5 Geolocation in my application. 内置gps的笔记本在我的国家非常罕见,所以我必须在我的应用程序中使用HTML5 Geolocation

For Internet Explorer 9+, there is a registry key that you can add urls to allow a url without needing user verification. 对于Internet Explorer 9+,有一个注册表项,您可以添加URL以允许URL而无需用户验证。 If you add an REG_DWORD value named domain.com under HKCU\\Software\\Microsoft\\Internet Explorer\\Geolocation\\HostConsent path browser will allow geolocation request automatically. 如果在HKCU\\Software\\Microsoft\\Internet Explorer\\Geolocation\\HostConsent下添加名为domain.com的REG_DWORD值, HKCU\\Software\\Microsoft\\Internet Explorer\\Geolocation\\HostConsent路径浏览器将自动允许地理定位请求。 However I can't run Internet Explorer hidden so thats not working for me since thief shouldn't realize and see what's going on. 但是,我无法运行Internet Explorer隐藏,因此不适合我,因为小偷不应该意识到并看到发生了什么。

  • I need to run Internet Explorer hidden somehow 我需要以某种方式隐藏Internet Explorer
  • ...or I need to embed webkit or something to my application but I don't know how can I use it or how can I allow this request programmatically. ...或者我需要将webkit或其他内容嵌入到我的应用程序中,但我不知道如何使用它或如何以编程方式允许此请求。

I prefer second way because Internet Explorer is now terminated by Microsoft and I think next version will have different structure. 我更喜欢第二种方式,因为Internet Explorer现在已被Microsoft终止,我认为下一版本将具有不同的结构。

How can I embed and use Webkit or GeckoFX to my application? 如何在我的应用程序中嵌入和使用Webkit或GeckoFX? How can I allow a geolocation request programmatically in this application? 如何在此应用程序中以编程方式允许地理定位请求?

Relying on a hidden browser is a risky solution, and it will inevitably break at some point in the future. 依赖隐藏的浏览器是一个危险的解决方案,它将在未来的某个时刻不可避免地破裂。

Instead you want to build geolocation functionality into your own application. 相反,您希望在自己的应用程序中构建地理定位功能。 The two major sources of location info are your IP address (which you then feed into any of the GeoIP providers ) and cellular/Wi-Fi stations visible (which you feed into Google geolocation API ). 位置信息的两个主要来源是您的IP地址(然后您可以将其提供给任何GeoIP提供商 )和可见的蜂窝/ Wi-Fi站(您可以将其输入Google地理位置API )。

Have a look at the GeoCoordinateWatcher class which is defined in the System.Device assembly 查看System.Device程序集中定义的GeoCoordinateWatcher

The GeoCoordinateWatcher class supplies coordinate-based location data from the current location provider. GeoCoordinateWatcher类提供来自当前位置提供程序的基于坐标的位置数据。 The current location provider is prioritized as the highest on the computer, based on a number of factors, such as the age and accuracy of the data from all providers, the accuracy requested by location applications, and the power consumption and performance impact associated with the location provider. 根据许多因素,当前位置提供商优先考虑计算机上的最高位置,例如所有提供商的数据的年龄和准确性,位置应用程序请求的准确性以及与之相关的功耗和性能影响。位置提供者。 The current location provider might change over time, for instance, when a GPS device loses its satellite signal indoors and a Wi-Fi triangulation provider becomes the most accurate provider on the computer. 当前位置提供者可能随时间而改变,例如,当GPS设备在室内丢失其卫星信号并且Wi-Fi三角测量提供者成为计算机上最准确的提供者时。

Usage example : 用法示例:

static void Main(string[] args)
{
    GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

    watcher.StatusChanged += (sender, e) =>
    {
        Console.WriteLine("new Status : {0}", e.Status);
    };

    watcher.PositionChanged += (sender, e) =>
    {
        Console.WriteLine("position changed. Location : {0}, Timestamp : {1}",
            e.Position.Location, e.Position.Timestamp);
    };

    if(!watcher.TryStart(false, TimeSpan.FromMilliseconds(5000)))
    {
         throw new Exception("Can't access location"); 
    }

    Console.ReadLine();
}

I think this class relies on the same mechanism than the one use by Internet Explorer. 我认为这个类依赖于与Internet Explorer使用的机制相同的机制。

When you will use it, you will have an icon in your system notification tray telling that location has recently been accessed. 当您使用它时,系统通知托盘中会有一个图标,告知最近访问过该位置。

在此输入图像描述

You will also have an entry added on windows logs. 您还将在Windows日志中添加一个条目。

If you are deploying to a modern version of Windows, you could use the library native to .NET System.Device.Location which allows you to obtain device location information. 如果要部署到现代版本的Windows,则可以使用.NET System.Device.Location本机库,它允许您获取设备位置信息。

Here is a link on MSDN for how to use it GeoCoordinate Class 这是MSDN上有关如何使用GeoCoordinate类的链接

If using XAML, you can also try this method. 如果使用XAML,您也可以尝试此方法。 Detect Users Location using XAML 使用XAML检测用户位置

You can embed a webkit browser into your application by using PhantomJS . 您可以使用PhantomJS将webkit浏览器嵌入到您的应用程序中。 PhantomJS is a headless browser and can be added to your application through searching NuGet or the NuGet command line PM> Install-Package PhantomJS . PhantomJS是一个无头浏览器,可以通过搜索NuGet或NuGet命令行PM> Install-Package PhantomJS添加到您的应用程序中。 Once PhantomJS has been added to your project, you'll want to build a file to control phantom something like: 一旦PhantomJS添加到您的项目中,您将需要构建一个文件来控制幻像,例如:

 public string PhantomJson(string phantomControlFile, params string[] arguments)
        {
            string returnJsonString = String.Empty;

            if (!String.IsNullOrEmpty(URL))
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    FileName = Path.Combine(PhantomExecutionPath, "phantomjs.exe"),
                    UseShellExecute = false,
                    WorkingDirectory = PhantomExecutionPath,
                    Arguments = @"--proxy-type=none --ignore-ssl-errors=true {1} ""{0}"" {2}".FormatWith(URL, phantomControlFile, 
                        arguments.Any() ? String.Join(" ", arguments) : String.Empty)
                };

                StringBuilder receivedData = new StringBuilder();
                using (Process p = Process.Start(startInfo))
                {
                    p.OutputDataReceived += (o, e) =>
                    {
                        if (e.Data != null && e.Data != "failed")
                        {
                            //returnJsonString = e.Data;
                            receivedData.AppendLine(e.Data);
                        }
                    };
                    p.BeginOutputReadLine();
                    p.WaitForExit();
                }
                returnJsonString = receivedData.ToString();

                if (!String.IsNullOrEmpty(returnJsonString))
                {
                    return returnJsonString;
                }
                else
                {
                    throw new ArgumentNullException("Value returned null. Unable to retrieve data from server");
                }
            }
            else
            {
                throw new ArgumentNullException("Url cannot be null");
            }
        }

Then you'll want to build a control file to tell phantomjs where to go; 然后你会想要建立一个控制文件来告诉phantomjs去哪里; something like: 就像是:

var args, myurl, page, phantomExit, renderPage, system;

system = require("system");
args = system.args;
page = null;
myurl = args[1];

phantomExit = function(exitCode) { // this is needed as there are time out issues when it tries to exit.
  if (page) {
    page.close();
  }
  return setTimeout(function() {
    return phantom.exit(exitCode);
  }, 0);
};

renderPage = function(url) {
  page = require("webpage").create();
    return page.open(url, function(status) {
      if (status === 'success') {
         // Process Page and console.log out the values
         return phatomExit(0);
      } else {
         console.log("failed");
         return phantomExit(1);
      }
     });
   };
  renderPage(myurl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM