本文告诉大家如何在应用运行过程判断自己的 WPF 应用被转制为 UWP 应用运行
通过 kernel32 的 GetCurrentPackageFullName 方法即可判断,此方法要求是在 Win10 或以上版本才能使用哦。当然了,如果在 Win10 以下的版本,如 Win7 那默认就跑不了 UWP 应用,也就不需要判断了
判断代码如下
const long APPMODEL_ERROR_NO_PACKAGE = 15700L;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern int GetCurrentPackageFullName(ref int packageFullNameLength, StringBuilder packageFullName);
public bool IsRunningAsUwp()
{
int length = 0;
StringBuilder sb = new StringBuilder(0);
int result = GetCurrentPackageFullName(ref length, sb);
sb = new StringBuilder(length);
result = GetCurrentPackageFullName(ref length, sb);
return result != APPMODEL_ERROR_NO_PACKAGE;
}
在开始判断之前,先判断系统版本,代码如下
public bool IsRunningAsUwp()
{
if (IsWindows7OrLower)
{
return false;
}
else
{
int length = 0;
StringBuilder sb = new StringBuilder(0);
int result = GetCurrentPackageFullName(ref length, sb);
sb = new StringBuilder(length);
result = GetCurrentPackageFullName(ref length, sb);
return result != APPMODEL_ERROR_NO_PACKAGE;
}
}
private bool IsWindows7OrLower
{
get
{
int versionMajor = Environment.OSVersion.Version.Major;
int versionMinor = Environment.OSVersion.Version.Minor;
double version = versionMajor + (double)versionMinor / 10;
return version <= 6.1;
}
}
Call Windows Runtime APIs in desktop apps - Windows apps
Desktop Bridge – Identify the application’s context