Silverlight, update gui by changing img source c# - c#

I'm trying to make a binary clock, an it works fine.
It works like this.
Every time you call a method called run, it sets the time, and change some img source (the img is my lamp, change img source every time it shut off or on).
But how can I get it to run all the time?
If I make a loop it won't start on my mobile, and it's like using threading does do anything.
Is there a method for update the gui after you change some properties?
XMAL Code
<phone:PhoneApplicationPage
x:Class="BinSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Image Height="80" HorizontalAlignment="Left" Margin="141,187,0,0" Name="imag1" Stretch="Fill" VerticalAlignment="Top" Width="106" Source="/BinSample;component/img/knapSluk.png" />
</Grid>
</Grid>
public MainPage()
{
InitializeComponent();
//test one
//try to make a neverending loop
Run();
//testc two
//try loop with thread an sleep funtion.
thredRun();
}
public void thredRun()
{
new Thread(new ThreadStart(thredRun));
while (true)
{
Run();
Thread.Sleep(100);
}
}
public void Run()
{
while (true)
{
int hour = DateTime.Now.Hour;
if (hour % 10 == 0)
imag1.Source = new BitmapImage(new Uri("img/knapTaand.png", UriKind.Relative));
else
imag1.Source = new BitmapImage(new Uri("img/knapSluk.png", UriKind.Relative));
}
}
}

There are a few problems here.
First you are not using the Thread class correctly, check this tutorial to get started
Even when you do correct your usage of the Thread class, you are either going to end up blocking the UI Thread, or you will end up with a Cross-Thread exception.
In this case, perhaps the easiest way for you to achieve what you want is to use a DispatcherTimer
public MainPage()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer() { Interval = TimeSpan.FromHours(1) };
timer.Tick += new EventHandler(timer_Tick);
SetImageSource();
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
SetImageSource();
}
void SetImageSource()
{
int hour = DateTime.Now.Hour;
if (hour % 10 == 0)
imag1.Source = new BitmapImage(new Uri("img/knapTaand.png", UriKind.Relative));
else
imag1.Source = new BitmapImage(new Uri("img/knapSluk.png", UriKind.Relative));
}

Related

WPF Need to find a way to identify TypeOf on custom Page class

I have a Window class called MainWindow, and in its constructor, builds a default Page class I call, MonitorPage that populates my window with this page at launch. In my MainWindow, I have three buttons that act as page tabs or menu buttons that upon clicking them will create an instance of a different Page class, in my case I have three unique pages. MonitorPage, DataBasePage, HelpPage. In my MainWindow, I want to "grey-out" the tab button when that corresponding page is up. I have a method in MainWindow called, PageState(), that tries to identify which page is currently up to enable or disable and grey out the tabs. My problem is that I get a NullReferenceException in my method at the first IF check.
The Error I'm Getting:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Controls.ContentControl.Content.get returned null.
C#:
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
namespace EyeInTheSky
{
/// <summary>
/// Interaction logic for MainWindow.xaml + backend code for FileSystemWatcher project
/// </summary>
public partial class MainWindow : Window
{
#region Fields
private FileSystemWatcher _watcher = new FileSystemWatcher();
private ObservableCollection<string[]> _eventList = new ObservableCollection<string[]>();
#endregion
public MainWindow()
{
InitializeComponent();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
PageState();
}
private void PageState()
{
if (Main.Content.GetType() == typeof(MonitorPage))
{
Menu_MonitorButton.IsEnabled = false;
Menu_MonitorButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = true;
}
else if (Main.GetType() == typeof(DataBasePage))
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = false;
Menu_DataBaseButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_HelpButton.IsEnabled = true;
}
else
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = false;
Menu_HelpButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
}
}
private void Menu_MonitorButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
}
private void MenuStrip_DataBaseButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new DataBasePage(ref _eventList);
}
private void MenuStrip_HelpButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new HelpPage();
}
}
}
XAML:
<Window x:Name="Home" x:Class="EyeInTheSky.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EyeInTheSky"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="Eye In The Sky - Windows File System Watcher" Height="450" Width="1105" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" TextOptions.TextFormattingMode="Ideal" Background="#FF39393E" Foreground="#FFE4E4E4" FontFamily="Roboto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27*"/>
<RowDefinition Height="394*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="240*"/>
<ColumnDefinition Width="859*"/>
</Grid.ColumnDefinitions>
<Frame x:Name="Main" Height="421" VerticalAlignment="Top" Grid.RowSpan="2" Grid.ColumnSpan="2" Panel.ZIndex="1"/>
<DockPanel HorizontalAlignment="Left" Height="27" LastChildFill="False" VerticalAlignment="Top" Width="240" Panel.ZIndex="10000">
<StackPanel x:Name="Menu" Orientation="Horizontal" HorizontalAlignment="Left" Height="27" VerticalAlignment="Top" Width="240" Background="#FF4E4E53">
<Button x:Name="Menu_MonitorButton" Content="Monitor" Width="80" Click="Menu_MonitorButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_DataBaseButton" Content="Data Base" Width="80" Click="MenuStrip_DataBaseButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_HelpButton" Content="About" Width="80" Click="MenuStrip_HelpButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" Padding="0,1,1,1" BorderThickness="1,0,2,0"/>
</StackPanel>
</DockPanel>
</Grid>
</Window>

Initialization of 'System.Windows.Controls.Button' threw an exception

I am creating a WPF on which, i have 2 threads. One is the main, and the other one(called PillTimeOutChecker) check some requirements in the main form. If the requirements meet, a new form through the PilleCheckerThread show up in a new thread. The problem is that i am getting this error: Initialization of 'System.Windows.Controls.Button' threw an exception in the initialization of the new form.
This is the method in the main thread, that call the PillCheckerThread:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Thread PillChecker = new Thread(new ThreadStart(PillCheckerThread));
PillChecker.SetApartmentState(ApartmentState.STA);
PillChecker.IsBackground = true;
PillChecker.Name = "PillTimeOutChecker";
PillChecker.Start();
}
This is the content of the PillCheckerThread method:
private void PillCheckerThread()
{
foreach (DataGridObject item in PillList.Items)
{
if(item.DoIt)
{
//Show PillWarning window
Thread PillWarningWindow = new Thread(new ThreadStart(() =>
{
PillWarningWindow pl = new PillWarningWindow(item.PillName, item.AlertTime);
pl.Show();
System.Windows.Threading.Dispatcher.Run();
}));
PillWarningWindow.SetApartmentState(ApartmentState.STA);
PillWarningWindow.IsBackground = true;
PillWarningWindow.Start();
}
}
}
This is the content of the PillWarningWindow:
public partial class PillWarningWindow : Window
{
public PillWarningWindow(string PillName, string CurrentTime)
{
InitializeComponent();
PillNameLbl.Content = PillName;
TimeLbl.Content = CurrentTime;
}
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
This is the xaml of the PillWarningWindow:
<Window x:Class="MedicalReminder.PillWarningWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MedicalReminder"
mc:Ignorable="d" Height="300" Width="713.414" ShowInTaskbar="False" Topmost="True" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None" Background="Transparent" AllowsTransparency="True">
<Border BorderBrush="Black" CornerRadius="20" Background="DarkCyan">
<Grid>
<Button x:Name="CloseBtn" Content="OK" HorizontalAlignment="Left" Margin="262,239,0,0" VerticalAlignment="Top" Width="179" Click="CloseBtn_Click"/>
<Label x:Name="label" Content="Psssttt !! It's time to take your pill: " HorizontalAlignment="Left" Margin="89,93,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
<Label x:Name="PillNameLbl" Content="PillName" HorizontalAlignment="Left" Margin="395,93,0,0" VerticalAlignment="Top" FontSize="18" FontWeight="Bold"/>
<Label x:Name="label2" Content="It's exactly " HorizontalAlignment="Left" Margin="89,132,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
<Label x:Name="TimeLbl" Content="12:00" HorizontalAlignment="Left" Margin="195,133,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="17" Width="56"/>
<Label x:Name="label3" Content="you forgot it ??" HorizontalAlignment="Left" Margin="256,132,0,0" VerticalAlignment="Top" FontWeight="Bold" FontSize="18"/>
</Grid>
</Border>
With a breakpoint at the constructor of the PillWarningWindow i found out that the error start at the InitializeComponent method. Any help is appreciated. Thanks.
If you want to access windows propety you should use Dispatchers.
Because of another thread cannot acces window directly. You can use the Dispatcher when you want to run an operation that will be executed on the UI thread.
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => PillNameLbl.Content = PillName;
TimeLbl.Content = CurrentTime));
If debugger stops at InitializeComponent method, I'd say there is probably something wrong with your XAML code (which despite of being full of bad practices, doesn't seem to be incorrect). Are you sure your controls don't have style resources defined in any other place? I have had the same error before and it was caused by defining styles in a wrong order.
Try to launch your window directly at the application start instead of launching it from another thread, just to test if it's OK. If it works, then the problem is in the thread management.

Right clicking a button inflates AppBar instead of firing right click event

So I have a button in my AppBar that adds buttons to a stackpanel that is located in a grid on the page.
I assigned a RightTapped event to the new buttons.
However, when I right click a new button, instead of firing the method I assigned to the RightTapped event, the program inflates the AppBar.
I tried to set IsRightTapEnabled="False" one every item but the new buttons, but that didn't help the issue.
I'm stuck and I need help.
Here is my code behind:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
int index = 0;
private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
index++;
string ButtonName = "Button" + index;
Button dummyButton = new Button
{
Name = ButtonName,
Content = ButtonName,
};
StackPanel1.Children.Add(dummyButton);
dummyButton.RightTapped += new RightTappedEventHandler(DummyButton_RightTapped);
}
private void Button0_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
MenuFlyout myFlyout = new MenuFlyout();
MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "Right Clicked" };
myFlyout.Items.Add(firstItem);
myFlyout.ShowAt(sender as FrameworkElement);
}
private void DummyButton_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
//var dialog = new MessageDialog("Right clicked");
//await dialog.ShowAsync();
MenuFlyout myFlyout = new MenuFlyout();
MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "Right Clicked" };
myFlyout.Items.Add(firstItem);
myFlyout.ShowAt(sender as FrameworkElement);
}
}
Here is my XAML code:
<Page
x:Class="Soundboard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Soundboard"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
IsRightTapEnabled="False">
<Page.TopAppBar >
<AppBar IsSticky="True" IsRightTapEnabled="False" >
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<AppBarButton Label="Add Sound" Icon="OpenFile" Click="AppBarButton_Click" ></AppBarButton>
</StackPanel>
</AppBar>
</Page.TopAppBar>
<Grid Background="#FF004D40" Name="myGrid" IsRightTapEnabled="False">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<StackPanel Name="StackPanel1" Grid.Row="0" Orientation="Horizontal" IsRightTapEnabled="False">
<Button Content="Button0" Name ="Button0" RightTapped="Button0_RightTapped"></Button>
</StackPanel>
</Grid>
The official does not recommend using the AppBar in UWP. The following section references Official AppBar instructions.
You should use the AppBar only when you are upgrading a Universal Windows 8 app that uses the AppBar, and need to minimize changes. For new apps in Windows 10, we recommend using the CommandBar control instead.
Usage
Add CommandBar to <Page.TopAppBar> just like following code.
<Page.TopAppBar>
<CommandBar IsSticky="True">
<AppBarButton
Click="AppBarButton_Click"
Icon="OpenFile"
Label="Add Sound" />
</CommandBar>
</Page.TopAppBar>

'MouseEventArgs' does not contain a definition for 'GetPosition'

Im sure this is a super easy one but I am working on a C# UWP app and am trying to make a drag-able user control but in my mouse event I'm getting the following error:
CS1061 'MouseEventArgs' does not contain a definition for 'GetPosition' and no extension method 'GetPosition' accepting a first argument of type 'MouseEventArgs' could be found (are you missing a using directive or an assembly reference?)
I found this example I am using on stack (Dragging a WPF user control) and have used mouse down events before for dragging items between list boxes in winforms but didn't have this issue.
Here is my code:
<UserControl
x:Class="HopHaus.TimerControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HopHaus"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400" Width="120" Height="60">
<Grid Margin="0,0,0,167" Width="120">
<Rectangle Fill="#FF404040" HorizontalAlignment="Left" Height="60" Margin="1,0,-1,-133" Stroke="Black" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="timersetBox" Margin="-1,-2,1,-59" TextWrapping="Wrap" Text="00" VerticalAlignment="Top" Height="60" BorderBrush="Transparent" FontFamily="Fonts/DIGITAL.TTF#Digital" Foreground="#FF72FB00" FontSize="50" Background="Transparent" TextAlignment="Right" AcceptsReturn="True" SelectionHighlightColor="#000078D7" Width="120"/>
<Border x:Name="dragBrdr" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="59" Margin="2,0,0,-59" VerticalAlignment="Top" Width="118"/>
</Grid>
</UserControl>
And:
public sealed partial class TimerControl : UserControl
{
Point currentPoint;
Point anchorPoint;
bool isInDrag;
public TimerControl()
{
this.InitializeComponent();
}
private TranslateTransform transform = new TranslateTransform();
private void root_MouseMove(object sender, MouseEventArgs e)
{
if (isInDrag)
{
var element = sender as FrameworkElement;
currentPoint = e.GetPosition(null);
transform.X += currentPoint.X - anchorPoint.X;
transform.Y += (currentPoint.Y - anchorPoint.Y);
this.RenderTransform = transform;
anchorPoint = currentPoint;
}
}
}
I am using both using System.Windows.Input & using Windows.Devices.Input
Thanks a bunch in advance for any help provide.
To have better support for touch and inking there is an abstraction over the mouse events. This is called pointer. So in you you have a PointerMoved event
in xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
PointerMoved="Grid_PointerMoved">
</Grid>
and in code
private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
{
var point = e.GetCurrentPoint(null);
}
but am still unsure how to take my var point and transform it into a new position of my user control on my MainPage
As #Dave Smits said you need a Pointer event handle. More details about handle pointer input please reference this document. I think what you confused is that this code var point = e.GetCurrentPoint(null); return PointerPoint object instead Point structure what you needed for transform. In that case, you can get the Point structure by PointerPoint.Position property. Updated code as follows:
<UserControl
...
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400"
Width="120" Height="60" PointerMoved="Grid_PointerMoved" CanDrag="True">
<Grid Margin="0,0,0,167" Width="120" >
<Rectangle Fill="#FF404040" HorizontalAlignment="Left" Height="60" Margin="1,0,-1,-133" Stroke="Black" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="timersetBox" Margin="-1,-2,1,-59" TextWrapping="Wrap" Text="00" VerticalAlignment="Top" Height="60" BorderBrush="Transparent" FontFamily="Fonts/DIGITAL.TTF#Digital" Foreground="#FF72FB00" FontSize="50" Background="Transparent" TextAlignment="Right" AcceptsReturn="True" SelectionHighlightColor="#000078D7" Width="120"/>
<Border x:Name="dragBrdr" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="59" Margin="2,0,0,-59" VerticalAlignment="Top" Width="118"/>
</Grid>
</UserControl>
Code behind
Point currentPoint;
Point anchorPoint;
bool isInDrag;
private TranslateTransform transform = new TranslateTransform();
private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
{
anchorPoint = new Point(300, 200);
isInDrag = true;
if (isInDrag)
{
var element = sender as FrameworkElement;
PointerPoint currentPointpointer = e.GetCurrentPoint(null);
currentPoint = currentPointpointer.Position;
transform.X += currentPoint.X - anchorPoint.X;
transform.Y += (currentPoint.Y - anchorPoint.Y);
this.RenderTransform = transform;
anchorPoint = currentPoint;
}
}
Additionally, for transform from one point to another I recommend you to use PointAnimation.

I'm making a torch app in Win Phone 8 but i cant turn off the led, how can i do that?

i have read another post in other to make a torch App for mi Nokia Lumia 820, i successfully turn on the led but when i try to turn it off ... i can't, i use this code in order to turn it on.
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
// ShowWhiteScreenInsteadOfCameraTorch();
}
Can you help me in order to turn the flash off?
Thanks.
Here is a full solution I have just finished for a Shaker Torch/Flash light for Windows Phone 8. Remember to set Camera and Microphone device caps in WMAppManifest.xml. Shake to turn on/off. It uses the ShakeGestures library for capturing a shake.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using ShakeGestures;
using Windows.Phone.Media.Capture;
namespace ShakerTorch
{
public partial class MainPage : PhoneApplicationPage
{
#region Initialisation
private AudioVideoCaptureDevice _captureDevice;
private bool _flashOn;
private const CameraSensorLocation _sensorLocation = CameraSensorLocation.Back;
public MainPage()
{
InitializeComponent();
ShakeGesturesHelper.Instance.ShakeGesture += OnShake;
ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 5;
ShakeGesturesHelper.Instance.Active = true;
InitialiseCaptureDevice();
}
#endregion
private async void InitialiseCaptureDevice()
{
_captureDevice = await GetCaptureDevice();
}
private void OnShake(object sender, ShakeGestureEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
switch (e.ShakeType)
{
case ShakeType.X:
{
_shakeStatusTextBlock.Text = string.Format("Left and right ({0})", e.ShakeType);
_shakeStatusTextBlock.Foreground = new SolidColorBrush(Colors.Red);
break;
}
case ShakeType.Y:
{
_shakeStatusTextBlock.Text = string.Format("Forward and backwards ({0})", e.ShakeType);
_shakeStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);
break;
}
case ShakeType.Z:
{
_shakeStatusTextBlock.Text = string.Format("Up and down ({0})", e.ShakeType);
_shakeStatusTextBlock.Foreground = new SolidColorBrush(Colors.Blue);
break;
}
}
ToggleFlash();
});
}
private void ToggleFlash()
{
try
{
IReadOnlyList<object> supportedCameraModes =
AudioVideoCaptureDevice.GetSupportedPropertyValues(_sensorLocation,
KnownCameraAudioVideoProperties.VideoTorchMode);
//ToDo Don't like this line. Simplify....
if (supportedCameraModes.ToList().Contains((UInt32) VideoTorchMode.On))
{
if (!_flashOn)
{
_captureDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
_captureDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(_sensorLocation,
KnownCameraAudioVideoProperties
.VideoTorchPower)
.Max);
_contentGrid.Background = new SolidColorBrush(Colors.White);
_flashOn = true;
}
else
{
_captureDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
_contentGrid.Background = null;
_flashOn = false;
}
}
}
catch (Exception ex)
{
_shakeStatusTextBlock.Text = "The flash cannot be controlled on this device.";
}
}
private async Task<AudioVideoCaptureDevice> GetCaptureDevice()
{
AudioVideoCaptureDevice captureDevice =
await
AudioVideoCaptureDevice.OpenAsync(_sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(_sensorLocation)
.First());
return captureDevice;
}
}
}
And the Xaml...
<phone:PhoneApplicationPage
x:Class="ShakerTorch.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="_layoutRootGrid" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- LOCALIZATION NOTE:
To localize the displayed strings copy their values to appropriately named
keys in the app's neutral language resource file (AppResources.resx) then
replace the hard-coded text value between the attributes' quotation marks
with the binding clause whose path points to that string name.
For example:
Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"
This binding points to the template's string resource named "ApplicationTitle".
Adding supported languages in the Project Properties tab will create a
new resx file per language that can carry the translated values of your
UI strings. The binding in these examples will cause the value of the
attributes to be drawn from the .resx file that matches the
CurrentUICulture of the app at run time.
-->
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="_titleStackPanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="_titleTextBlock" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock x:Name="_pageNameTextBlock" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="_contentGrid" Grid.Row="1" Margin="12,0,12,0">
<TextBlock x:Name="_shakeStatusTextBlock" Text="Shake me..." FontSize="36" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<!--Uncomment to see an alignment grid to help ensure your controls are
aligned on common boundaries. The image has a top margin of -32px to
account for the System Tray. Set this to 0 (or remove the margin altogether)
if the System Tray is hidden.
Before shipping remove this XAML and the image itself.-->
<!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
</Grid>
</phone:PhoneApplicationPage>

Categories

Resources