WPF C# Media Element Show first image of video - c#

i have a .mov file that i want to play using MediaElement of WPF , i can play and pause with no worries as i use MediaState.Manual , but i want to show the first image or frame of the video when i load it , the source is set in code behind , i tried MediaElement.ScrubbingEnabled = true both code behind and xaml but it still doesn't show.
Here is my code ( xaml side ) :
<DockPanel Height="386" HorizontalAlignment="Center" Name="dockPanel1" VerticalAlignment="Top" Width="731">
<MediaElement Name="McMediaElement" LoadedBehavior="Manual" UnloadedBehavior="Manual" Stretch="Fill" MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" OpacityMask="#FF040410" Height="386" IsVisibleChanged="SingAlong_IsVisibleChanged" ScrubbingEnabled="True"></MediaElement>
</DockPanel>
Code behind ( xaml.cs) :
private void PlayAudio()
{
McMediaElement.LoadedBehavior = MediaState.Manual;
McMediaElement.Source = new Uri("../../SingAlong/GrassHopper and Ants/ants2.mov", UriKind.RelativeOrAbsolute);
McMediaElement.ScrubbingEnabled = true;
McMediaElement.Play();
}
private void button1_Click_1(object sender, RoutedEventArgs e) // Play button
{
if (McMediaElement.Source != null)
{
McMediaElement.Play();
}
else
PlayAudio();
}
private void button2_Click(object sender, RoutedEventArgs e) // Pause button
{
McMediaElement.Pause();
}

From what I can gather, you are loading your video (setting the Source) only when you click button1, yet you want the first frame to show before this happens. To accomplish this, you will have to load your video in another method, preferably when your Page or Window loads. Then you can do the following:
McMediaElement.ScrubbingEnabled = true;
McMediaElement.Play();
McMediaElement.Pause();

Related

Drag & Drop from explorer to wpf element

Everything seems to be simple and there are quite a few tutorials, but I cannot transfer data (in my case, an image) to a wpf window element. I was able to implement the transfer of an image from one element to another. But when I capture an image (for example, a desktop), when I transfer it to the desired element, the transfer option does not even appear, only a crossed-out circle and does not work out more than one event associated with drop (as if AllowDrop = false)
My code:
XAML
<Image x:Name="mainContent" Grid.Column="1" Stretch="Fill" AllowDrop="True" Drop="MainContent_Drop" />
C#
private void SpImageLeft_MouseDown(object sender, MouseButtonEventArgs e)
{
Image image = sender as Image;
DragDrop.DoDragDrop(image, image, DragDropEffects.Copy);
}
private void MainContent_Drop(object sender, DragEventArgs e)
{
Image image = (Image)e.Data.GetData(typeof(Image));
mainContent.Source = image.Source;
}
I understand that when I take an image from explorer it will be different there, something like this, but it still does not even show that you can add an image
private void MainContent_Drop(object sender, DragEventArgs e)
{
string[] arr = (string[])e.Data.GetData(DataFormats.FileDrop);
mainContent.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(arr[0]);
}
The following worked for me as a Drop event handler for an Image control:
private void OnMainImageDrop(object sender, DragEventArgs e)
{
if (sender is Image image && e.Data.GetDataPresent(DataFormats.FileDrop))
{
if (e.Data.GetData(DataFormats.FileDrop) is string[] filePaths)
{
image.Source.Freeze();
string filePath = filePaths[0];
var uriSource = new Uri(filePath);
var imageSource = new BitmapImage(uriSource);
image.Source = imageSource;
}
}
}
I used a placeholder image to make sure the image had a size and served as a mouse hover surface.
XAML:
<Image x:Name="MainImage" Grid.Row="1"
Source="Images/DotNetLogo.png"
Stretch="Uniform"
AllowDrop="True" Drop="OnMainImageDrop"/>

Flyout causing the app to crash [Windows 10] C# XAML

I want the program to show the attached Flyout when user Holding the control (on the mobile) or when the user Right-click the control (on PC).
Here is my XAML :
<DataTemplate x:DataType="data:Cards" x:Key="card">
<StackPanel x:Name="cardstack" Holding="cardstack_Holding" KeyDown="cardstack_KeyDown" >
<StackPanel Background="Blue" Height="100" />
<FlyoutBase.AttachedFlyout>
<MenuFlyout x:Name="optionpass">
<MenuFlyoutItem x:Name="delete" Text="Delete" Click="delete_Click"/>
</MenuFlyout>
</FlyoutBase.AttachedFlyout>
</StackPanel>
</DataTemplate>
and this is my C# :
private void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
{
FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
}
private void cardstack_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.RightButton)
{
FlyoutBase.ShowAttachedFlyout(sender as FrameworkElement);
}
}
When I tap and Hold the Stackpanel on the mobile simulator, the Holding event works, but when I Right-click on my PC, it crashes! It says that "There are no attached Flyout!". I do not know what is wrong.
"Have you tried RightTapped event? Is it working?"
Yes and No :(
I just found out the solution to solve my problem.
Turns out you have to name the MenuFlyout like my one is x:Name = "option_menu", and the Flyoutbase.AttachedFlyout cannot be in the DataTemplate, means you have to put it anywhere else except in the DataTemplate, so that the .cs file can find the name of the MenuFlyout.
Here is my C# :
public void cardstack_Holding(object sender, HoldingRoutedEventArgs e)
{
option_menu.ShowAt(sender as FrameworkElement);
e.Handled = true;
}
private void cardstack_PointerPressed(object sender, PointerRoutedEventArgs e)
{
Pointer pointr = e.Pointer;
if (pointr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
{
Windows.UI.Input.PointerPoint pointrd = e.GetCurrentPoint(sender as UIElement);
if (pointrd.Properties.IsRightButtonPressed)
{
option_menu.ShowAt(sender as FrameworkElement);
}
}
e.Handled = true;
}
Notice that before this I use ShowAttachedFlyout, now I use option_menu.ShowAt.
KeyDown event somehow did not work with my app, so I used PointerPressed instead.
Hope this helps. (0w0)/

collect score from mouse click event in c# silverlight

Ok I am new to silverlight in c# and I am building a game where balloons float around the screen and you get points for clicking one.
I so far have 5 balloons moving randomly around and I wish to have a mouse click even for all of them.
so far for a mouse click I have
C#
private void redballoon_click(object sender, MouseButtonEventArgs e)
{
// +1 to score array
}
XAML
<Image Height="53" HorizontalAlignment="Left" Margin="0,0,0,0" Name="red" Stretch="Fill" VerticalAlignment="Top" Width="48" Source="red.png" MouseLeftButtonDown="redballoon_click" Canvas.Left="194" Canvas.Top="161" RenderTransformOrigin="0.938,0.536" />
I would like some way of collecting the score for each click but I am very new and could do with some help.
Put a field in your class to track how many clicks, it will look something like this:
public class Window
{
private int _clicks = 0;
private void redballoon_click(object sender, MouseButtonEventArgs e)
{
_clicks++;
}
}

How to navigate to other page with button in WPF

I have a second .xaml page set up under the name Page2.xaml and I want to make it so that when my button is clicked, the user is taken to Page2.xaml
I have this for my button inside of my Page1.xaml:
<Grid>
<Button x:Name="localModeBtn"
Style="{StaticResource MainButtonStyle}"
Content="local mode"
Click="localModeBtn_Click" />
</Grid>
And for the button event handler:
private void localModeBtn_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("Page2.xaml", UriKind.Relative);
this.NavigationService.Navigate(uri);
}
Upon clicking the button I receive an error that says "Cannot locate resource page2.xaml"
The thing is that Page2.xaml is in the same folder as Pag1.xaml so I can't see where I've gone wrong?
Solution to my own question:
I feel a bit silly providing a solution to my own question but thanks to Jasti's link I was able to sort my code out. As he had only posted a comment, I can't mark it as an answer, so here is the solution.
I changed the NavigationWindow to a Window and inserted:
<DockPanel>
<Frame x:Name="_NavigationFrame" NavigationUIVisibility="Hidden" />
</DockPanel>
And within the constructor of the MainWindow.xaml.cs I added:
_NavigationFrame.Navigate(new Page1());
Then the last step was to adjust the button event handler to:
this.NavigationService.Navigate(new Uri("Pages/Page2.xaml", UriKind.Relative));
You should use this, this worked for me:
var Page2= new Page2(); //create your new form.
Page2.Show(); //show the new form.
this.Close(); //only if you want to close the current form.
There is a variable type of a page with the page.xaml right name in your solution.
after that, you should use its methods to do it functionally.
Use any container and bind the content to any property in your viewmodel or codebehind.
After that you just have to update the property by setting a new page and call the PropertyChanged-event (see INotifyPropertyChanged interface). This will update the content of your container and you can display anything you want.
In case you want a separate window
NavigationWindow navWIN = new NavigationWindow();
navWIN.Content = new pageWFbchAdmin();
navWIN.Show();
//winBchAdmin.ShowDialog();
You don't need any C# code for this, just do it in XML:
<Button Content="local mode"
Command="NavigationCommands.GoToPage"
CommandParameter="/Page2.xaml"/>
(Reformatted code not tested)
private void Navigate_Click(object sender, RoutedEventArgs e)//By Prince Jain
{
this.NavigationService.Navigate(new Uri("Page3.xaml", UriKind.Relative));
}
My solution was adding a frame in the main window MainWindow.xaml
<Frame Name="Main" Content="" Margin="127,0,0,0" Background="#FFFFEDED" />
For navigation:
1- Navigating from the main windows on button click:
private void Button_Click(object sender, RoutedEventArgs e)
{
// navigate to pages/projects.xaml inside the main frame
Main.Content = new MyProject.Pages.Projects();
}
2- In case of navigation from the page inside a frame ex Projects.xaml
// declare a extension method in a static class (its your choice if you want to reuse)
// name the class PageExtensions (you can choose any name)
namespace MyProject
{
public static class PageExtensions
{
public static void NavigateTo(this Page page, string path)
{
Frame pageFrame = null;
DependencyObject currParent = VisualTreeHelper.GetParent(page);
while (currParent != null && pageFrame == null)
{
pageFrame = currParent as Frame;
currParent = VisualTreeHelper.GetParent(currParent);
}
if (pageFrame != null)
{
pageFrame.Source = new Uri(path, UriKind.Relative);
}
}
}
}
// to navigate from 'pages/projects.xaml' to another page
// heres how to call the extension on button click
this.NavigateTo("NewProject.xaml");
In addition, you can add another extension method that expects another Page object, in case you want to pass parameters to the constructor
// overloading NavigateTo
public static void NavigateTo(this Page page, Page anotherPage)
{
Frame pageFrame = null;
DependencyObject currParent = VisualTreeHelper.GetParent(page);
while (currParent != null && pageFrame == null)
{
pageFrame = currParent as Frame;
currParent = VisualTreeHelper.GetParent(currParent);
}
// Change the page of the frame.
if (pageFrame != null)
{
pageFrame.Navigate(anotherPage);
}
}
// usage
this.NavigateTo(new Pages.EditProject(id));
First of all, you'll need a frame in your window to hold the pages, so in my MainWindow.xaml I'll add a frame like this:
<Frame x:name="mainFrame"/>
Then We'll add an event listener to our navigation button in our MainWindow.xaml like this:
<Button
x:Name="navBtn"
Content="LIVE VIEW"
Click="NavBtn_Click">
</Button>
Now after we've set our window xaml up, we'll go to MainWindow.xaml.cs and write our code:
//this function should be automatically generated
private void NavBtn_Click(object sender, RoutedEventArgs e)
{
//we'll write this line, which opens our page
mainFrame.Content = new YourPage();
}
and that's it your navigation is ready!
In View (.xaml file):
<StackPanel>
<TextBlock>Outside area of frame</TextBlock>
<StackPanel Height="20" Width="400" VerticalAlignment="Top" Orientation="Horizontal">
<Button Content="Page 1" Width="200" Click="Button_Click"/>
<Button Content="Page 2" Width="200" Click="Button_Click_1"/>
</StackPanel>
<Frame Name="Main" Height="300" Width="700" Background="LightGray">
</Frame>
</StackPanel>
In code behind (.xaml.cs file):
private void Button_Click(object sender, RoutedEventArgs e)
{
Main.Content = new Page1();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Main.Content = new Page2();
}
Thesse two buttons will now help you to navigate between pages named Page1 and Page2. (Please take care of namespaces if the pages are present in folders or so).

Windows 8 Store App - MediaElement no longer playing Audio

I am trying to play an audio file (.wav) when a toggle button is pressed (and pause when pressed again). I had it working initially, but now I must of messed something up and am looking for help. This is how I'm doing it:
Create MediaElement in XAML
<MediaElement x:Name="myMediaElement" HorizontalAlignment="Center" VerticalAlignment="Center" PosterSource="vuvuzela.png" IsLooping="True" Source="Assets/vuvuzela.wav" Grid.Row="1" AutoPlay="False"/>
Then My ToggleButton is this:
<ToggleButton x:Name="ToggleButton" Content="Activate" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="2" FontSize="32" Style="{StaticResource ToggleButtonStyle1}" Checked="Tog_Checked" Unchecked="Tog_Unchecked"/>
And in my Code-behind, I have the ToggleButton's checked/unchecked handlers:
private void Tog_Checked(object sender, RoutedEventArgs e)
{
myMediaElement.Play();
}
private void Tog_Unchecked(object sender, RoutedEventArgs e)
{
myMediaElement.Pause();
}
Any ideas as to what might be going wrong or how to check it? Thanks!
EDIT: Debugged some more. Looks like the myMediaElement is not getting past the Opening state?
Apparently it was a hardware problem. My computer (MacBook running Bootcamp) was the issue. Finally found that answer in this post --> MediaElement in WinRT / Win8 does not work at all
Thanks for all the help though everyone
Is it important to you that your media element be visual like that?
Try this in your click event instead:
var _Media = new Windows.UI.Xaml.Controls.MediaElement() { AutoPlay = false };
var _Location = Windows.ApplicationModel.Package.Current.InstalledLocation;
var _Folder = await _Location.GetFolderAsync("Assets");
var _File = await _Folder.GetFileAsync("Ding.wav");
var _Stream = await _File.OpenAsync(Windows.Storage.FileAccessMode.Read);
_Media.SetSource(_Stream, _File.ContentType);
_Media.Play();
Have shown code required to play audio file. (code for playing next audio is bonus )
1.Add media element, play/pause/stop buttons to the XAML file.
<MediaElement x:Name="media" Source="Assets/page1/para1.mp3"
Grid.Column="0" Grid.Row="0" AutoPlay="True" />
<Button Click="StopMedia" Grid.Column="0" Grid.Row="1" Content="Stop" />
<Button Click="PauseMedia" Grid.Column="1" Grid.Row="1" Content="Pause" />
<Button Click="PlayMedia" Grid.Column="2" Grid.Row="1" Content="Play" />
2.Add the following code to the code-behind file:
private void StopMedia(object sender, RoutedEventArgs e)
{
media.Stop();
}
private void PauseMedia(object sender, RoutedEventArgs e)
{
media.Pause();
}
private void PlayMedia(object sender, RoutedEventArgs e)
{
media.Source = new Uri(this.BaseUri, "Assets/page1/para1.mp3");
media.Play();
}
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
media.MediaEnded += media_MediaEnded;
}
private void media_MediaEnded(object sender, RoutedEventArgs e)
{
media.Source = new Uri(this.BaseUri, "Assets/page1/para2.mp3");
media.Play();
}

Categories

Resources