正在Windows通用应用程序中检测当前设备
本文关键字:检测 Windows 应用程序 正在 | 更新日期: 2023-09-27 17:59:44
我正在试用已发布的VS2013Update2,并构建一个示例通用应用程序。
我已经创建了一个用户控件,并在两个主页上添加了GridViews(在WindowsPhone和Windows8上)。
当应用程序在Windows Phone上运行时,我想通过代码更改一些内容。
有没有办法做这样的事情:
if(<deviceType> == "WindowsPhone")
{
}
else
{
}
通常在构建应用程序时,可以使用预处理器指令。在为windows phone构建应用程序时,VS默认定义WINDOWS_PHONE_APP
(请查看项目属性->构建->条件编译符号)。因此,在代码中的任何位置,都可以放置这样的语句:
#if WINDOWS_PHONE_APP
// do when this is compiled as Windows Phone App
#else
// not for windows phoen
#endif
您可以在MSDN上获得更多信息。
我建议使用这种方法,因此在大多数情况下,您确切地知道何时将使用手机(ARM)或其他平台的特定代码。当然,如果需要,您可以为特定的构建配置/平台定义更多的符号。
备注:由于W10需要在运行时中检查平台,因此可以使用ApiInformation类检查api中是否存在特定类型。例如:
if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
// do code for mobile
else
// do code for other
这就是我在通用Windows(Windows 10)项目中的工作原理
public static Platform DetectPlatform()
{
bool isHardwareButtonsAPIPresent =
ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
if (isHardwareButtonsAPIPresent)
{
return Platform.WindowsPhone;
}
else
{
return Platform.Windows;
}
}
如果你想要一种确定当前设备的代码内方法,你可以尝试一下:
public Windows.Foundation.Metadata.Platform DetectPlatform()
{
try
{
//Calls an unsupported API.
Windows.Networking.BackgroundTransfer.BackgroundDownloader.RequestUncontrainedDownloadsAsync(null);
}
catch (NotImplementedException)
{
//The API isn't supported on Windows Phone. Thus, the current platform is Windows Phone.
return Windows.Foundation.Metadata.Platform.WindowsPhone;
}
catch(Exception)
{
//Otherwise, this is Windows (desktop/RT).
return Windows.Foundation.Metadata.Platform.Windows;
}
}
来源:https://gist.github.com/Amrykid/2fd65ae1815a928fe753
或者您可以执行此
将此添加到
应用Xaml.Cs
public static bool IsMobile
{
get
{
var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;
return (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile");
}
}
来自GitHub
public static class DeviceTypeHelper
{
public static DeviceFormFactorType GetDeviceFormFactorType()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Mobile":
return DeviceFormFactorType.Phone;
case "Windows.Desktop":
return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse
? DeviceFormFactorType.Desktop
: DeviceFormFactorType.Tablet;
case "Windows.Universal":
return DeviceFormFactorType.IoT;
case "Windows.Team":
return DeviceFormFactorType.SurfaceHub;
default:
return DeviceFormFactorType.Other;
}
}
}
public enum DeviceFormFactorType
{
Phone,
Desktop,
Tablet,
IoT,
SurfaceHub,
Other
}
https://gist.githubusercontent.com/wagonli/40d8a31bd0d6f0dd7a5d/raw/f6175de5fcad40cc257edc3748c0e349495d17f6/DeviceTypeHelper.cs
这是一个变通方法
//PC customization
if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
{
}
//Mobile customization
if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
}