Discovering if a keyboard is attached to a Surface Pro device - c#

I have a UWP app running on a surface pro device and I am trying to tell if a keyboard is attached to the device (this is the surface pro keyboard so attaches to the bottom, not usb) so that my application can go down different code paths.
Here is the list of things I have tried and their results:
1.
How to detect if the surface keyboard is attached?
KeyboardCapabilities keyboardCapabilities = new Windows.Devices.Input.KeyboardCapabilities();
return keyboardCapabilities.KeyboardPresent != 0 ? true : false;
But this always returns true on a surface pro device as specified here: Windows 8 WinRT KeyboardCapabilities.KeyboardPresent is always true
2. How to detect if the surface keyboard is attached?
Converted the Network watcher to c#
public bool KeyboardAttached { get; set; }
private void SetupKeyboardWatcher()
{
var watcher = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher();
watcher.Added += Watcher_Added;
watcher.Updated += Watcher_Updated;
watcher.Removed += Watcher_Removed;
watcher.Start();
}
private void Watcher_Updated(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformationUpdate args)
{
if (args.Id.IndexOf("{884b96c3-56ef-11d1-bc8c-00a0c91405dd}") != -1)
{
if (args.Properties.ContainsKey("System.Devices.InterfaceEnabled"))
{
// keyboard is connected
KeyboardAttached = true;
}
else
{
// keyboard disconnected
KeyboardAttached = false;
}
}
}
private void Watcher_Added(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformation args)
{
if ((args.Id.IndexOf("{884b96c3-56ef-11d1-bc8c-00a0c91405dd}") != -1) && (args.Id.IndexOf("MSHW0007") == -1))
{
if (args.Properties.ContainsKey("System.Devices.InterfaceEnabled"))
{
// keyboard is connected
KeyboardAttached = true;
}
}
}
private void Watcher_Removed(Windows.Devices.Enumeration.DeviceWatcher sender, Windows.Devices.Enumeration.DeviceInformationUpdate args)
{
if (args.Id.IndexOf("{884b96c3-56ef-11d1-bc8c-00a0c91405dd}") != -1)
{
if (args.Properties.ContainsKey("System.Devices.InterfaceEnabled"))
{
// keyboard is connected
KeyboardAttached = true;
}
else
{
// keyboard disconnected
KeyboardAttached = false;
}
}
}
This returns keyboardAttached true when the onscreen keyboard shows up
3. How to detect if the surface keyboard is attached?
bool bIsDesktop = false;
var uiMode = UIViewSettings.GetForCurrentView().UserInteractionMode;
if (uiMode == Windows.UI.ViewManagement.UserInteractionMode.Mouse) // Typical of Desktop
bIsDesktop = true;
always returns true
Outside of my app the Windows OS acts differently depending on whether the keyboard is attached or not (it pops up a on screen keyboard) so there must be a way of doing it.
I'm not sure whether this link contains any information of relevance https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/keyboard-and-mouse-class-drivers
Is there a way of telling if a keyboard is attached to a surface pro device?

Related

Take photo just pressing the shutter release

I need some advice on how to use the camera in Xamarin.Forms.
Currently, NuGet Xam.Plugin.Media.
Media. With the following code, when you press a button from the UI, the camera starts up, takes a picture and displays the image on the screen.
private async void OnCameraTapped(object sender, EventArgs e)
{
var photo = await CaptureCamera();
Image.Source = ImageSource.FromStream() =>
{
return new MemoryStream(photo);
});
}
```
```
private async Task<byte[]> CaptureCamera()
{
await Plugin.Media.CrossMedia.Current. Initialize();
Initialize(); if (!Plugin.Media.CrossMedia.Current. IsCameraAvailable ||
!Plugin.Media.CrossMedia.Current. IsTakePhotoSupported)
{
return null;
}
var file = await Plugin.Media.CrossMedia. CrossMedia.
.TakePhotoAsync(
new Plugin.Media.Abstractions. StoreCameraMediaOptions
{
Directory = "Photo",
Name = DateTime.Now.ToString("yyyy_MMdd_HHHmm ") + "Photo.jpg",
});
if (file == null)
return null;
var bytes = new Queue<byte>();
using (var s = file.GetStream())
{
var length = s.Length;
int b;
while ((b = s.ReadByte()) ! = -1)
bytes.Enqueue((byte)b);
}
Dispose();
Dispose(); if (bytes == null) return null;
return bytes.ToArray();
}
However, this method uses Plugin.Media.CrossMedia, which means that the There are some restrictions. I would like to know how to get around those constraints.
Q) I need to press the shutter release and then press "OK" on the activated camera. I want to finish the process by just pressing the shutter release.
Q) The camera I started up defaults to out-camera. I want to take a picture of myself, so I want to start the in-camera as the default.
How can I get around the above two points?
My environment is as follows.
OS Windows 10 Home
IDE Visual Studio 2019 community
Xamarin.Form(.NET Standard 2.1)
Target Android 9.0(API 28)

Playback of Audio file on key press is delayed

I made a small program that plays back sounds when you press keys.
It uses a global keyboard hook to capture key presses and play back wav files using NAudio.
However playback lags on some computers and plays a few seconds after the key has been pressed. Could this be an HDD/SSD or CPU speed issue or is it a programming issue? What can be done to solve it?
Tried on 4 computers, 2 lagged, 2 did not.
My SSD/i7 - did not lag.
My HDD/Core2Duo - did not lag.
Friend's SSD/i7 - lagged.
Friend's HDD/i7 - lagged.
Program
Info
https://github.com/MattMcManis/Ink
Source
https://github.com/MattMcManis/Ink/tree/master/source/Ink
Download
https://github.com/MattMcManis/Ink/releases
App.xaml.cs
Start the Keyboard Listener.
// Application Startup
//
private void Application_Startup(object sender, StartupEventArgs e)
{
th = new Thread(() => RunKeyListener());
th.IsBackground = true;
th.Start();
th.Join();
}
// Keyboard Listener
//
private void RunKeyListener()
{
KListener.KeyDown += new RawKeyEventHandler(KListener_KeyDown);
}
// Key Down
//
void KListener_KeyDown(object sender, RawKeyEventArgs args)
{
Sound.KeyPressed(args);
}
MainWindow.xaml.cs
KeyboardListener Class is in here.
https://gist.github.com/Ciantic/471698
Sound.cs
private static string wavKeyChar = "Sounds\\character.wav";
private static string wavKeyNum = "Sounds\\number.wav";
public static WaveFileReader wav = null;
public static WaveOutEvent output = null;
// Key Pressed
//
public static void KeyPressed(RawKeyEventArgs args)
{
// Letters
if (args.Key >= Key.A && args.Key <= Key.Z)
{
PlaySound(wavKeyChar);
}
// Numbers
else if (args.Key >= Key.D0 && args.Key <= Key.D9)
{
PlaySound(wavKeyNum);
}
}
// Play Sound
//
public static void PlaySound(string sound)
{
wav = new WaveFileReader(sound);
output = new WaveOutEvent();
output.NumberOfBuffers = 3;
output.DesiredLatency = 500;
output.Init(wav);
output.Play();
}
Try to show a MessageBox or something, to understand if the delayed event is the sound itself or the keypress event.
If the MessageBox shows before the sound is played then it's not a problem of keyboard hook library.

swipe left or right in windows phone 8.1

I am looking to understand gesture or horizontal swipe event in windows phone 8.1. I have below code which works fine but don't how to understand the status of swipe. Whether it is right swipe or left swipe. So my question is How to identify swipe right and left?
void MainPage_PointerReleased(object sender, PointerRoutedEventArgs e)
{
var ps = e.GetIntermediatePoints(null);
if (ps != null && ps.Count > 0)
{
gr.ProcessUpEvent(ps[0]);
e.Handled = true;
gr.CompleteGesture();
}
}
void gr_CrossSliding(Windows.UI.Input.GestureRecognizer sender, Windows.UI.Input.CrossSlidingEventArgs args)
{
//How to know you swipe left and right
}
void MainPage_PointerMoved(object sender, PointerRoutedEventArgs e)
{
gr.ProcessMoveEvents(e.GetIntermediatePoints(null));
e.Handled = true;
}
void MainPage_PointerPressed(object sender, PointerRoutedEventArgs e)
{
var ps = e.GetIntermediatePoints(null);
if (ps != null && ps.Count > 0)
{
gr.ProcessDownEvent(ps[0]);
e.Handled = true;
}
}
And my constructor
Windows.UI.Input.CrossSlideThresholds cst = new Windows.UI.Input.CrossSlideThresholds();
cst.SelectionStart = 2;
cst.SpeedBumpStart = 3;
cst.SpeedBumpEnd = 4;
cst.RearrangeStart = 5;
gr.CrossSlideHorizontally = true;
gr.CrossSlideThresholds = cst;
gr.CrossSliding += gr_CrossSliding;
gr.GestureSettings = GestureSettings.CrossSlide;
One idea is to remember where was the first point pressed and then, upon release, check relesed position and compare with the rememered one. This should allow to idetify in which direction user has moved his finger.
Also if it would be possible, you can also think of using Velocities when using manipulation events - example at this post.

How to call method in Kinect SDK?

I have a program that checks if the Kinect is connected to the computer. However, I don't really know if I need to call a method (I would assume so) and where? I've attached the code that I got from an introductory Kinect book. Thanks!
using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Kinect;
namespace test
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
KinectSensor kinectSensor;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
KinectSensor.KinectSensors.StatusChanged += Kinects_StatusChanged;
foreach (KinectSensor kinect in KinectSensor.KinectSensors)
{
if (kinect.Status == KinectStatus.Connected)
{
kinectSensor = kinect;
MessageBox.Show("Connected");
break;
}
}
if (KinectSensor.KinectSensors.Count == 0)
MessageBox.Show("No Kinect Found");
else
Initialize();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Kinects_StatusChanged(object sender, StatusChangedEventArgs e)
{
switch (e.Status)
{
case KinectStatus.Connected:
if (kinectSensor == null)
{
kinectSensor = e.Sensor;
Initialize();
}
break;
case KinectStatus.Disconnected:
if (kinectSensor == e.Sensor)
{
Clean();
MessageBox.Show("Kinect was disconnected");
}
break;
case KinectStatus.NotReady:
break;
case KinectStatus.NotPowered:
if (kinectSensor == e.Sensor)
{
Clean();
MessageBox.Show("Kinect is not powered anymore.");
}
break;
default:
MessageBox.Show("Unhandled Status: " + e.Status);
break;
}
}
private void Initialize()
{
if (kinectSensor == null)
return;
kinectSensor.Start();
}
private void Clean()
{
if (kinectSensor != null)
{
kinectSensor.Stop();
kinectSensor = null;
}
}
}
}
Download the Kinect for Windows Developer Toolkit. There are multiple examples in there on how to do multiple things, that will get you started and help you understand how to talk to the Kinect.
Once you've connected to the Kinect you need to set it up and then subscribe to the event callbacks. You'll end up with a function that looks something like this:
private void InitializeKinectServices(KinectSensorManager kinectSensorManager, KinectSensor sensor)
{
// configure the color stream
kinectSensorManager.ColorFormat = ColorImageFormat.RgbResolution640x480Fps30;
kinectSensorManager.ColorStreamEnabled = true;
// configure the depth stream
kinectSensorManager.DepthStreamEnabled = true;
kinectSensorManager.TransformSmoothParameters =
new TransformSmoothParameters
{
// as the smoothing value is increased responsiveness to the raw data
// decreases; therefore, increased smoothing leads to increased latency.
Smoothing = 0.5f,
// higher value corrects toward the raw data more quickly,
// a lower value corrects more slowly and appears smoother.
Correction = 0.5f,
// number of frames to predict into the future.
Prediction = 0.5f,
// determines how aggressively to remove jitter from the raw data.
JitterRadius = 0.05f,
// maximum radius (in meters) that filtered positions can deviate from raw data.
MaxDeviationRadius = 0.04f
};
// configure the skeleton stream
sensor.SkeletonFrameReady += OnSkeletonFrameReady;
kinectSensorManager.SkeletonStreamEnabled = true;
// initialize the gesture recognizer
_gestureController = new GestureController();
_gestureController.GestureRecognized += OnGestureRecognized;
kinectSensorManager.KinectSensorEnabled = true;
if (!kinectSensorManager.KinectSensorAppConflict)
{
// additional init
}
}
This is my generic setup function, which is based off of examples from the Developer Toolkit. You will not be able to just plug this into your code and it will work. Having a look at the examples in the Toolkit will give you an understanding of where this happens and how to best manage it.
The KinectExplorer example is a good overall project to look over. It will also give you a clear understanding of how the function above works (it has the same function).

Windows 8 metro apps Switching between 2 cameras

I am using MediaCapture class for camera view. But i have a problem that it supports only front camera of tablet, i want to switch between front and back camera by clicking a button.
How can i do it??
Sajid,
This example code from the Win8 Dev Center will show you how to enumerate through the camera devices connected to a current machine: http://code.msdn.microsoft.com/windowsapps/Media-Capture-Sample-adf87622
And here's another example which deals with DeviceEnumeration more specifically: http://code.msdn.microsoft.com/windowsapps/Device-Enumeration-Sample-a6e45169
Relevant code (from first link) :
private async void EnumerateWebcamsAsync()
{
try
{
ShowStatusMessage("Enumerating Webcams...");
m_devInfoCollection = null;
EnumedDeviceList2.Items.Clear();
m_devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (m_devInfoCollection.Count == 0)
{
ShowStatusMessage("No WebCams found.");
}
else
{
for (int i = 0; i < m_devInfoCollection.Count; i++)
{
var devInfo = m_devInfoCollection[i];
EnumedDeviceList2.Items.Add(devInfo.Name);
}
EnumedDeviceList2.SelectedIndex = 0;
ShowStatusMessage("Enumerating Webcams completed successfully.");
btnStartDevice2.IsEnabled = true;
}
}
catch (Exception e)
{
ShowExceptionMessage(e);
}
}
edit: this code is taken from the AdvancedCapture.xaml.cs file from the first code sample I posted.

Categories

Resources