【问题标题】:Referencing WinRT/UWP libraries in a .NET desktop application while maintaining support for Windows 7在 .NET 桌面应用程序中引用 WinRT/UWP 库,同时保持对 Windows 7 的支持
【发布时间】:2017-08-30 08:51:09
【问题描述】:

我正在尝试在我的桌面应用程序中引用“Windows.Networking.Connectivity”类。我基本上对在我的应用中处理计量连接感兴趣。

基本上我想做的很简单:

var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();
            if (connectionCost.NetworkCostType == NetworkCostType.Unknown
                    || connectionCost.NetworkCostType == NetworkCostType.Unrestricted)
            {
                //Connection cost is unknown/unrestricted
            }
            else
            {
                //Metered Network
            }

我所知道的允许桌面应用程序引用 UWP 程序集的唯一方法是手动编辑项目文件并将以下行添加到 csproj 文件:

<TargetPlatformVersion>8.0</TargetPlatformVersion>

应用代码和“破解”工作正常,但问题是这样做会阻止我的应用在我需要支持的 Windows 7 上运行。

我想知道是否有一种方法可以在桌面应用程序中引用 UWP 程序集,而不必放弃对 Windows 7 的支持。

由于目前我只想检查连接是否被计量,我愿意接受有关如何在不引用 Windows 程序集的情况下获取此信息的建议。

【问题讨论】:

    标签: c# windows network-programming connection desktop-application


    【解决方案1】:

    我找到了一种无需指定目标平台即可使用反射和调用 UWP 方法的方法。就我而言,这就是我所做的:

    var networkInfoType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
                var profileType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
                var profileObj = networkInfoType.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);
                dynamic profDyn = profileObj;
                var costObj = profDyn.GetConnectionCost();
                dynamic dynCost = costObj;
    
                var costType = (NetworkCostType)dynCost.NetworkCostType;
                if (costType == NetworkCostType.Unknown
                        || costType == NetworkCostType.Unrestricted)
                {
                    //Connection cost is unknown/unrestricted
                }
                else
                {
                    //Metered Network
                }
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2021-03-27
      • 1970-01-01
      • 2016-02-07
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多