DispatcherTimer does not fire - c#

I just got started in Windows Store App development and I just wanted a very simple application: Pretty much a progres bar that fills up from left to right, but even this task is apparently not achievalbe for me.
I have the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace TimeLoader
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private DispatcherTimer refreshTimer;
public MainPage()
{
this.InitializeComponent();
}
void refreshTimer_Tick(object sender, object e)
{
TimePassedBar.Value += 5;
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
TimePassedBar.Value = 50;
new DispatcherTimer();
this.refreshTimer = new DispatcherTimer();
this.refreshTimer.Interval = new TimeSpan(0, 0, 0, 100);
this.refreshTimer.Tick += refreshTimer_Tick;
this.refreshTimer.Start();
}
}
}
<Page
x:Class="TimeLoader.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TimeLoader"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="Page_Loaded">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<ProgressBar Grid.Row="0" Grid.Column="0" Height="150" Value="75" VerticalAlignment="Center" Name="TimePassedBar"/>
</Grid>
</Page>
Now the same Setup works pretty fine when I do it in WPF but the Tick Event never fires when I start this code built as a Windows store app. Is there something Special I have to pay Attention to when building Windows Store Apps? I have looked high and low and sadly have found nothing on this matter.

Your code was working fine. You just didn't wait long enough to notice. :)
private void Page_Loaded(object sender, RoutedEventArgs e)
{
TimePassedBar.Value = 50;
this.refreshTimer = new DispatcherTimer();
this.refreshTimer.Interval = TimeSpan.FromMilliseconds(100);
this.refreshTimer.Tick += refreshTimer_Tick;
this.refreshTimer.Start();
}
You are setting the TimeSpan as 100 seconds. You need to use the five-parameter overload to get milliseconds. But IMHO it's easier and more readable to just use the FromMilliseconds() method (as above).
Also, you don't need to create a DispatcherTimer object twice, especially when you're going to ignore the first one completely. :)

Related

Why does the button keep going out of bounds? (WPF Application)

I'm quite new to C# so expect faulty/lengthy code for no good reason.
So i was playing around with WPF Applications as i wanted to know how to make a button move when hovered over it- Which i managed to do but now it goes out of bounds?
XAML code:
<Window x:Class="Opdracht7.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:Opdracht7"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="klikmij" Content="Click me!" MouseEnter="onMouseEnter" Click="onMouseClick" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="-0.989,-0.519" Height="33" Width="68"/>
</Grid>
</Window>
C# code dump:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
namespace Opdracht7
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void onMouseEnter(object sender, MouseEventArgs e)
{
Random rnd1 = new Random();
int value1 = rnd1.Next(0, 250);
int value2 = rnd1.Next(0, 250);
int value3 = rnd1.Next(0, 250);
int value4 = rnd1.Next(0, 250);
Debug.WriteLine(value1);
Debug.WriteLine(value2);
Debug.WriteLine(value3);
Debug.WriteLine(value4);
klikmij.Margin = new Thickness(value1,value2, value3, value4);
}
private void onMouseClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Congratulations! You won nothing!");
}
public MainWindow()
{
InitializeComponent();
}
}
}
I set random range from 0 to 250, because when i adjust it to the window's actual height 'n width it goes out of bounds even faster.
For some strange reason when it goes over 230-ish (could be lower) the button is gone until you enlargen the window size.
Did i overlook a vital piece 'o code?
EDIT:
https://gyazo.com/342b20fdbbcef2a4834ab95c37aaf30e <- gif of it happening
EDIT 2:
https://gyazo.com/f04e1d64f9880cd01aa53f9169954377 <- gif of resizing window
After playing a bit in the designer with different values, it looks like in Grid margins take precedence, and the button gets smaller to accomodate. In case when it disappears, it's calculated height just becomes 0.
Set width and height for the button manually, then change just the left and top margin, while setting rest to 0:
<Grid>
<Button Margin="250,250,0,0" Width="100" Height="100">TEST</Button>
</Grid>
Play with values in designer first to see what's happening when.
Better, do not use an element's Margin for layout. For absolute positioning, use a Canvas:
<Grid>
<Canvas>
<Button x:Name="klikmij" Content="Click me!"
MouseEnter="onMouseEnter" Click="onMouseClick"
Height="33" Width="68"/>
</Canvas>
</Grid>
with thic code behind:
private readonly Random rnd = new Random();
private void onMouseEnter(object sender, MouseEventArgs e)
{
Canvas.SetLeft(klikmij, rnd.Next(0, 250));
Canvas.SetTop(klikmij, rnd.Next(0, 250));
}

C# ProgressBar not showing progress in media player

everyone. I've encountered a problem while developing my test media player in C#. I think I put all the code, but when I open file, it starts playing but progress bar isn't moving. Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media;
using Windows.Storage;
using Windows.Storage.Pickers;
using System.Threading;
using System.Windows;
namespace App1
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
TimeSpan _position;
private async void Open_Click(object sender, RoutedEventArgs e)
{
var openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var stream = await file.OpenAsync(FileAccessMode.Read);
videoMediaElement.SetSource(stream, file.ContentType);
}
}
private void Play_Click(object sender, RoutedEventArgs e)
{
if(videoMediaElement.PlaybackRate != 1 )
{
videoMediaElement.DefaultPlaybackRate = 1;
}
videoMediaElement.Play();
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
videoMediaElement.Stop();
}
private void ProgressBar_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
}
private void timer_Tick(object sender, object e)
{
if (videoMediaElement.Source != null && videoMediaElement.NaturalDuration.HasTimeSpan)
{
ProgressBar.Minimum = 0;
ProgressBar.Maximum = videoMediaElement.NaturalDuration.TimeSpan.TotalSeconds;
ProgressBar.Value = videoMediaElement.Position.TotalSeconds;
}
}
private void videoMediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
_position = videoMediaElement.NaturalDuration.TimeSpan;
ProgressBar.Minimum = 0;
ProgressBar.Maximum = _position.TotalSeconds;
}
}
}
and XAML:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="Open" Content="Open" HorizontalAlignment="Left" Margin="60,564,0,0" VerticalAlignment="Top" Width="299" Click="Open_Click"/>
<Button x:Name="Play" Content="Play" HorizontalAlignment="Left" Margin="393,564,0,0" VerticalAlignment="Top" Width="299" Click="Play_Click"/>
<Button x:Name="Stop" Content="Stop" HorizontalAlignment="Left" Margin="737,564,0,0" VerticalAlignment="Top" Width="299" Click="Stop_Click"/>
<ProgressBar x:Name="ProgressBar"
HorizontalAlignment="Left" Height="16" Margin="60,665,0,0" VerticalAlignment="Top" Width="1185" ValueChanged="ProgressBar_ValueChanged"/>
<Slider x:Name="slider" HorizontalAlignment="Left" Margin="1082,557,0,0" VerticalAlignment="Top" Width="163"/>
<MediaElement x:Name="videoMediaElement" HorizontalAlignment="Left" Height="491.884" Margin="4.22,58.023,0,0" VerticalAlignment="Top" Width="1270.501" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" MediaOpened="videoMediaElement_MediaOpened">
<MediaElement.RenderTransform>
<CompositeTransform Rotation="0.111"/>
</MediaElement.RenderTransform>
</MediaElement>
</Grid>
PLZ HELP!! I wasted 2 days and I found no real solution on google. Thank you!
Well I looked at your code and found your problem. It appears that SetSource() method doesn't really set mediaelement's source. I have no idea why. Maybe someone here will help you with that. There are several things that I can point out.
You start filling this progressbar before the movie starts. Which is a problem. You could initialize your timer not in MainPage constructor but in your Play_Click event or in this case where your movie starts automatically in you Open_Click event.
As I mentioned since the source is always null the progressbar will never fill. Fortunately there is a way to check if video element is currently running. Replace this:
if (videoMediaElement.Source != null && videoMediaElement.NaturalDuration.HasTimeSpan)
With This:
if (videoMediaElement.CurrentState == MediaElementState.Playing)
Hope this helps.

WPF - Webbrowser - getElementById

In a WPF application, I have a webbrowser called WebBrowser1. This refers to an HTML page which contains a TextArea to which users can input text.
<html>
<body>
<textarea class="myStudentInput" id="myStudentInput1">
Text to be copied
</textarea>
</body>
</html>
I wish to get this text and potentially also set this text.
I have tried something similar to the javascript way of writing it:
document.getElementById("myStudentOutput1").innerHTML;
such as
HtmlElement textArea = webBrowser1.Document.All["myStudentInput1"];
dynamic textArea = WebBrowser1.Document.GetElementsByID("myStudentInput1").InnerText;
but it doesn't work.
The following solution in Visual Studio 2015 WPF Application works for me.
First, add a reference to the Microsoft HTML COM Library. This is on the COM tab, when you do an "Add Reference" in your project.
Then add the code:
<Window x:Class="WpfApplication3.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:WpfApplication3"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="800">
<Grid>
<WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Left" Height="480" Margin="10,10,0,0" VerticalAlignment="Top" Width="770" Source="E:\Others\Dropbox\Programming\Questions.html"/>
<Button x:Name="mySetQuestionButton" Content="Set Question" HorizontalAlignment="Left" Margin="200,520,0,0" VerticalAlignment="Top" Width="75" Click="mySetQuestion"/>
<Button x:Name="myGetAnswerButton" Content="Get Answer" HorizontalAlignment="Left" Margin="350,520,0,0" VerticalAlignment="Top" Width="75" Click="myGetAnswer"/>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="600,520,0,0" TextWrapping="Wrap" Text="Hello2" VerticalAlignment="Top"/>
</Grid>
</Window>
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void mySetQuestion(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myQuestion1");
textArea.innerHTML = "What is 1+1?";
}
private void myGetAnswer(object sender, EventArgs e)
{
mshtml.HTMLDocument document = (mshtml.HTMLDocument)WebBrowser1.Document;
mshtml.IHTMLElement textArea = document.getElementById("myStudentInput1");
textBlock.Text = textArea.innerHTML;
}
}
}
but it doesn't work.
I have no idea what that could possibly mean. All you can get is a code snippet that does work:
public partial class Form1 : Form {
private WebBrowser webBrowser1;
private Button button1;
public Form1() {
button1 = new Button { Text = "Test" };
button1.Click += button1_Click;
this.Controls.Add(button1);
webBrowser1 = new WebBrowser { Dock = DockStyle.Fill };
webBrowser1.DocumentText = #"<html><body><textarea class=""myStudentInput"" id=""myStudentInput1"">Text to be copied</textarea></body></html>";
this.Controls.Add(webBrowser1);
}
private void button1_Click(object sender, EventArgs e) {
var elem = webBrowser1.Document.GetElementById("myStudentInput1");
MessageBox.Show(elem.InnerText);
}
}
Which produces:

Best way to handle UI performance issues in Windows Phone 8.1

I seem to have a sluggish UI when trying to scroll any large TextBlocks...
What's the best way to go about this in WP 8.1?
Here's an example I made to illustrate the issue, notice when the app is ran the framerate drops horribly.
I've already looked up BackgroundWorker and it doesn't seem to exist in WP 8.1.
MainPage.xaml
<Page
x:Class="HTTPRequest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HTTPRequest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<ScrollViewer x:Name="scroll" Margin="10,13,0,10" Width="380" MaxZoomFactor="4" VerticalScrollMode="Enabled" HorizontalScrollMode="Disabled" IsTapEnabled="False">
<TextBlock x:Name="RSSData" TextWrapping="Wrap" Text="Loading..." FontSize="22" VerticalAlignment="Top"/>
</ScrollViewer>
<ProgressBar x:Name="prog" Height="16" Margin="101,310,101,0" VerticalAlignment="Top" IsIndeterminate="True"/>
</Grid>
</Page>
MainPage.xaml.cs
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace HTTPRequest
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
Main();
}
private async void Main()
{
string results = await DownloadXMLDocument();
prog.Visibility = Visibility.Collapsed;
RSSData.Text = results;
}
public async Task<string> DownloadXMLDocument()
{
string URLString = "http://www.packtpub.com/rss.xml";
Uri uri = new Uri(URLString);
XmlDocument xmlDocument = await XmlDocument.LoadFromUriAsync(uri);
return xmlDocument.GetXml();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
There is a known issue with large quantities of text in a single TextBox. Instead try using the RichTextBox and see if your performance improves. Sorry you had a problem.
Best of luck!

Media element not playing audio in windows store app

I want to play mp3 audio in my app but nothing is happening
my code is this
XAML:
<Page
x:Class="SunnahForKids.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SunnahForKids"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="Black">
<StackPanel Width="900" Height="700" HorizontalAlignment="Center">
<MediaElement HorizontalAlignment="Left" Name="a" AutoPlay="False" Source="azan.mp3" Height="100" Margin="451,299,0,0" VerticalAlignment="Top" Width="100" Volume="100"/>
<Button Content="Button" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,676,0" Height="189" Click="Button_Click"/>
</StackPanel>
</Grid>
</Page>
And here is my .cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Media.SpeechSynthesis;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SunnahForKids
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
a.Play();
}
}
}
and I am struggling with it for 2 days need help . I also followed this link MediaElement in WinRT / Win8 does not work at all
to update my driver but it is up to date.Display driver in Intel R(Q35) express chipset family ( Microsoft Corporation WDDM-1.0) please get me out of here..
I tried your code and the code works, so something strange is going on. I would try to listen for the events mentioned in the link (example further down for devs looking for code example).
Check your event log on the computer (Windows => Applications), if you've missed updates for windows, and check that that mp3 will otherwise play.
Listen for the MediaFailed event (recommend that you do in the docs) and see if you can grab some information there.Code from msdn:
private void videoMediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
// Check the event arguments => e
// get HRESULT from event args
string hr = GetHresultFromErrorMessage(e);
// Handle media failed event appropriately
}
private string GetHresultFromErrorMessage(ExceptionRoutedEventArgs e)
{
String hr = String.Empty;
String token = "HRESULT - ";
const int hrLength = 10; // eg "0xFFFFFFFF"
int tokenPos = e.ErrorMessage.IndexOf(token, StringComparison.Ordinal);
if (tokenPos != -1)
{
hr = e.ErrorMessage.Substring(tokenPos + token.Length, hrLength);
}
return hr;
}

Categories

Resources