简体   繁体   中英

How to get current location in Windows Form c#

I wanted to get the location of the user in Windows Forms so I copied a code on the internet to get the current location of the device, but it doesn't work. I've tried multiple other codes but none of them seem to be working.

This is the code:

using System;
using System.Device.Location;

namespace CSharpProject
{
    public class Location
    {
        GeoCoordinateWatcher watcher;
        GeoCoordinate coord;

        public GeoCoordinate Coordination
        { 
            get
            {
                return coord;
            }
        }

        public void GetCurrentLocation()
        {
            watcher = new GeoCoordinateWatcher();
            watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
            coord = watcher.Position.Location;

            if (coord.IsUnknown == true)
                throw new Exception("Unknown Location!");
        }
    }
}

It always goes to the "Unknown Location." section.

The first parameter of the TryStart method must be set to True and make sure that you included System.Device.Location in your usings list.

       watcher.TryStart(true, TimeSpan.FromMilliseconds(1000));

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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