I am trying out released VS 2013 Update 2 and building a sample Universal Application.
I have created a user control and on both MainPages added GridViews (on Windows Phone and Windows 8).
I want to change some things via code when app is running on Windows Phone.
Is there a way to do something like:
if(<deviceType> == "WindowsPhone")
{
}
else
{
}
Normally when building your app, you can use preprocessor directives. When building app for windows phone, VS as default defines WINDOWS_PHONE_APP (take a look at Project Properties -> Build -> Conditional compilation symbols). Therefore anywhere in your code you can put such a statement:
#if WINDOWS_PHONE_APP
// do when this is compiled as Windows Phone App
#else
// not for windows phoen
#endif
More information you can get at MSDN.
I would advise to use this approach, hence in most cases you know exactly when you will use specific code for Phone (ARM) or other platform. Of course if you need you can define more symbols for specific build configurations/platforms.
Remarks: Since W10, where you need to check the platform in Run-Time, then you can use ApiInformation class and check if specific type exists in the api. For example like this:
if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1))
// do code for mobile
else
// do code for other
That's what worked for me in Universal Windows (Windows 10) project
public static Platform DetectPlatform()
{
bool isHardwareButtonsAPIPresent =
ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
if (isHardwareButtonsAPIPresent)
{
return Platform.WindowsPhone;
}
else
{
return Platform.Windows;
}
}
If you want an in-code method of determining the current device, you could try this:
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;
}
}
Source: https://gist.github.com/Amrykid/2fd65ae1815a928fe753
OR you can do this
Add this to
App.Xaml.Cs
public static bool IsMobile
{
get
{
var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;
return (qualifiers.ContainsKey("DeviceFamily") && qualifiers["DeviceFamily"] == "Mobile");
}
}
From 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
It's a workaround
//PC customization
if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
{
}
//Mobile customization
if(ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
{
}
Related
I am working with Unity and the Mixed Reality Toolkit. My issue is that "HP Reverb G2" is not detected using Windows Mixed Reality, but it works if I parse with SteamVR. My goal is to detect if the headset is on my head without using SteamVR.
My current solution, which doesn't work, is as follows:
public static bool IsHMDMounted()
{
if (headDevice == null || headDevice.isValid == false)
{
headDevice = InputDevices.GetDeviceAtXRNode(XRNode.Head);
}
if (headDevice != null)
{
bool presenceFeatureSupported = headDevice.TryGetFeatureValue(CommonUsages.userPresence, out bool userPresent);
if (headDevice.isValid && presenceFeatureSupported)
{
return userPresent;
}
else
{
return false;
}
}
else
{
return false;
}
}
There is a discussion related to this issue on the Unity forums - Question - OpenXR -- Is it no longer possible to get descriptive device names? - Unity Forum.
Referring to this thread, it seems that Unity does not expose the device information provided by Open XR, but you can get this information by intercepting the API of Open XR according to the method mentioned in the thread - https://forum.unity.com/threads/openxr-is-it-no-longer-possible-to-get-descriptive-device-names.1051493/#post-8275923.
So making a mobile application that works on UWP, IOS and Android but since not all librarys work on every platform I'm using the library based on what device is used by
if (Device.RuntimePlatform == Device.Android) { }
And I'm currently only working on the Android part of the application.
I'm using Android.Media to play a single audio file out of multiple speakers. And to do that I'm using a Picker that has the available audio output devices. This part works.
But I'm getting a error while trying to select the PreferredDevice:
Java.Lang.NoSuchMethodError: 'no non-static method "Landroid/media/MediaPlayer;.setPreferredDevice(Landroid/media/AudioDeviceInfo;)Z"'
The code line that is giving the error is:
mediaPlayer1.SetPreferredDevice(audioDeviceInfo);
the full method that is being run is:
newoutput.SelectedIndexChanged += (changed, args) =>
{
Context context = Android.App.Application.Context;
AudioManager audioMan = (AudioManager)context.GetSystemService(Context.AudioService);
AudioDeviceInfo audioDeviceInfo = audioMan.GetDevices(GetDevicesTargets.Outputs)[newoutput.SelectedIndex];
mediaPlayer1.SetPreferredDevice(audioDeviceInfo);
};
I can't find many examples that use the method and they don't usually go with a mediaplayer that is created by button press.
You can use this code
private AudioDeviceInfo findAudioDevice(int deviceType) {
AudioManager manager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] adis = manager.getDevices(GET_DEVICES_OUTPUTS);
for (AudioDeviceInfo adi : adis) {
if (adi.getType() == deviceType) {
return adi;
}
}
return null;
}
Then set your input:
audioRecord.setPreferredDevice(findAudioDevice([newoutput.SelectedIndex]));
We have an UWP application and we would like to have the following scenario:
open Microsoft word from it with a document
edit document
close document and get data to our application.
We have an Silverlight application that uses the code below and resolves the problem nicely. Can we do something similar in UWP? Programmatically open Word and wait for instance closing.
private void SetupWordInstance(bool visible = true)
{
if (AutomationFactory.IsAvailable)
{
_wordApp = null;
try
{
_wordApp = AutomationFactory.CreateObject("Word.Application");
_wordVersion = _wordApp.Version;
}
catch
{
try
{
_wordApp = AutomationFactory.CreateObject("Word.Application");
_wordVersion = _wordApp.Version;
}
catch (Exception)
{
Utils.ShowMessage(Resource.MissingWordApplicationErrorMessage);
}
}
if (_wordApp != null)
{
AutomationEvent beforeCloseEvent = AutomationFactory.GetEvent(_wordApp, "DocumentBeforeClose");
beforeCloseEvent.AddEventHandler(new BeforeCloseAppDelegate(BeforeCloseApp));
AutomationEvent quitEvent = AutomationFactory.GetEvent(_wordApp, "Quit");
quitEvent.AddEventHandler(new QuitAppDelegate(QuitApp));
if (visible)
{
_wordApp.Visible = true;
_wordApp.Activate();
FocusWordInstance();
}
}
}
else
{
Utils.ShowMessage(Resource.MissingAutomationErrorMessage);
}
}
There is a possibility that it can correspond by the technology called desktop bridge which Microsoft provides. Here's an explanation. Easily, it is to extract the Windows Desktop function not available in UWP and provide it together with application.
Docs/Windows/UWP/Develop/Porting apps to Windows 10/Desktop Bridge
The following is a sample when using Excel.
Desktop app bridge to UWP Samples
UWP calling Office Interop APIs
Windows Application Packaging Project Samples
Excel.Interop
Since the definition of Word API is below, it seems that it can be used as above.
Microsoft.Office.Interop.Word Namespace
Currently I develop a projekt in C#. In this project I use the DirectX API. Now I want to implement a function to check whether DirectX is available or not?
Do you have an idea how to do this?
Thank you for your help!
Do you need to detect if there's DirectX compatible GPU in the system, so that Direct3D9 device can be created, which is not the case with some virtual operating systems etc? That one can be tested simply by creating a device instance and catching the exception it possibly throws.
DirectX install existence itself can be checked by looking into Windows\System32 folder. For example, check d3d9d.dll, and D3DX9_43.dll.
Another way to get the DirectX - Version:
void CheckDirectXMajorVersion()
{
int directxMajorVersion = 0;
var OSVersion = Environment.OSVersion;
// if Windows Vista or later
if (OSVersion.Version.Major >= 6)
{
// if Windows 7 or later
if (OSVersion.Version.Major > 6 || OSVersion.Version.Minor >= 1)
{
directxMajorVersion = 11;
}
// if Windows Vista
else
{
directxMajorVersion = 10;
}
}
// if Windows XP or earlier.
else
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\DirectX"))
{
string versionStr = key.GetValue("Version") as string;
if (!string.IsNullOrEmpty(versionStr))
{
var versionComponents = versionStr.Split('.');
if (versionComponents.Length > 1)
{
int directXLevel;
if (int.TryParse(versionComponents[1], out directXLevel))
{
directxMajorVersion = directXLevel;
}
}
}
}
}
Console.WriteLine("DirectX Version: " + directxMajorVersion.ToString());
Console.ReadKey();
}
I have 2 projects- one that is a web service and the other is a windows mobile application that queries that webservice.
Say for instance I have a class called 'Animal'. I want to use the webservice to return an instance of an Animal to the mobile device. The problem being that the mobile device obviously doesnt support the full .net framework, and the class Animal has some features that require the full framework.
What are my best options here? The class Animal will really only contain properties that are just text. Am I best parsing the data into an XML message and sending this back to the mobile device (so not actually using the Animal object on the mobile device?) or do I create 2 classes, one for each platform?
Thanks
You can share a code file between two projects. Right click your project, choose Add -> Existing item, and then click the down arrow next to the Add button, you will see a "Add as Link" option there, if you know you class will compile for both projects even if they target different platforms, you can use this to share the class for both projects
I run Windows and Mobile using the same code.
Mobile devices have the word PocketPC defined in the Project's Properties, therefore, all you have to do (since you are coding in C#) is:
public static bool CreateDirectoryWithPermission(string path) {
bool ok = false;
DirectoryInfo dir = new DirectoryInfo(path);
#if !PocketPC
try {
DirectorySecurity ds;
if (dir.Exists) {
ds = dir.GetAccessControl();
} else {
ds = dir.Parent.GetAccessControl();
}
string user = Environment.UserDomainName + #"\" + Environment.UserName;
FileSystemAccessRule rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow);
ds.AddAccessRule(rule);
dir.Create(ds);
ok = true;
} catch (Exception) { }
#endif
if (!ok) {
try {
dir.Create();
ok = true;
} catch (Exception) { }
}
return ok;
}
If I remember correctly, System.Security.AccessControl is not defined under Windows Mobile, so the DirectorySecurity is undefined.
UPDATE:
Here is another way to do what you are interested in: Create a Serializable class in a completely separate namespace, use that namespace in both projects, and pass the serialized data from the Webservice to the Mobile device. I do that, as well, but there is more code.
namespace LocksAnimal {
[Serializable()]
public class Animal {
private string name;
public Animal() {
name = "Lock";
}
public string GetName() {
#ifdef PocketPC
return name + " (Mobile Version)";
#else
return name + " (Webservice Version)";
#endif
}
}
}
The Webservice version, of course, can access more detailed information (like GetAccessControl() shown in the first code segment).
I hope this gives you some ideas.