MediaElement Class Is Not Play the Media file in WPF Application - wpf

MainWindow.Xaml
<MediaElement Margin="10,10,10,0 " Name="McMediaElement" Width="450" Height="250" LoadedBehavior="Manual" Stretch="Fill"
MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" UnloadedBehavior="Stop" />
<Label Grid.Column="1" Grid.Row="1" Height="28" Margin="82,0,99,3.52"
Name="FileNameLabel" VerticalAlignment="Bottom" Background="LightGreen">
</Label>
<Button Height="23" Name="BrowseButton" Width="113" Grid.Column="1" HorizontalAlignment="Right"
Margin="0,0,182,7.04" Grid.Row="1" VerticalAlignment="Bottom" Grid.ColumnSpan="2"
FontWeight="Bold" Click="BrowseButtonClick">
Browse a Media
</Button>
When Click BrowseButton Its get the file from open Dialog box and it put into the Lable control as FileNameLabel
private void BrowseButtonClick(object sender, RoutedEventArgs e)
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "Media files (*.wmv)|*.wmv|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
FileNameLabel.Content = selectedFileName;
McMediaElement.Source = new Uri(selectedFileName);
McMediaElement.UpdateLayout();
McMediaElement.Play();
}
}
private void Element_MediaOpened(object sender, EventArgs e)
{
timelineSlider.Maximum = McMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
}
// When the media playback is finished. Stop() the media to seek to media start.
private void Element_MediaEnded(object sender, EventArgs e)
{
McMediaElement.Stop();
}
its does not play the media file.so Plaese Suggest what the problem in code.

Related

c# wpf Dialog will close the owner window

i have a window that is acting like a Dialog with two buttons and a textbox, so its an input dialog, the problem is when i press the buttons, or close the dialog window in any way the main window that i used to create this dialog will get closed too! (exit code = 0) and another thing is that it will work OK in vs debugging but when i run the app without vs debugging that owner window get closed and in my case that window is the Main app window so the whole application will shutdown! what am i doing wrong?
XAML:
<Window x:Class="Server.Forms.Dialogs.PokeDialog"
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:Server.Forms.Dialogs"
mc:Ignorable="d"
Title="Poke" MinHeight="120" MinWidth="225"
ResizeMode="CanResizeWithGrip"
SizeToContent="WidthAndHeight"
x:Name="windowPoke"
Loaded="windowPoke_Loaded">
<StackPanel VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Margin="25">
<Label Content="Poke Reason:"
Padding="0"/>
<TextBox x:Name="textboxPokeReason"
Margin="0 5"/>
<DockPanel>
<Button x:Name="btnOk"
Click="btnOk_Click"
IsDefault="True"
Content="OK"
MinWidth="100"
Margin="0 0 5 0"/>
<Button x:Name="btnCancel"
Click="btnCancel_Click"
IsCancel="True"
Content="Cancel"
MinWidth="100"/>
</DockPanel>
</StackPanel>
C#:
public partial class PokeDialog : Window
{
public string PokeReason
{
get { return textboxPokeReason.Text; }
}
public PokeDialog()
{
InitializeComponent();
}
private void windowPoke_Loaded(object sender, RoutedEventArgs e)
{
textboxPokeReason.Focus();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
the way i used dialog:
private void btnPokeClient_Click(object sender, RoutedEventArgs e)
{
var dialog = new PokeDialog();
if (dialog.ShowDialog() == true)
{
MessageBox.Show("TRUE - input text:" + dialog.PokeReason);
}
else MessageBox.Show("FALSE");
}
i can see the messageboxes too, but after closing this message boxes the whole app will get closed

How to display an image with openfiledialog and label wpf

im creating a program to display any image with openfiledialog and a label(this one to display the image) i also added a textbox to show the image path
private void button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
textBox.Text = filename;
Ima = new Image();
Ima.Source = new BitmapImage(new Uri(#dlg.FileName));
label.Content = Ima;
}
heres the xaml code of the label:
<Label x:Name="label1" HorizontalAlignment="Left" Height="78" Margin="107,180,0,0" VerticalAlignment="Top" Width="344"/>
The problem with this is that when i choose the image i want to display, the label doesn't show it.
Xaml File
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Name="servicePhoto" Height="100" Width="100" Stretch="Fill" />
<Button Height="40" HorizontalAlignment="Left" Name="btnLoad" VerticalAlignment="Center" Width="200" Click="ServiceImage_Click">Choose Image</Button>
</StackPanel>
.cs File
private void ServiceImage_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
servicePhoto.Source = new BitmapImage(new Uri(op.FileName));
}
}

Timer for camera feature in UWP

I am currently development a UWP application and I have a camera feature in my program. However I wish to implement timers for the feature.
I wish to allow the user to select their preferred timing at the side, and click on the "Take a picture" button and on the camera screen it will show a timer and the event under the onclick for the "take a picture" button will be delayed according to the user's selection.
Here is my code from .xaml:
<CaptureElement Name="PreviewControl" Margin="566,77,166,50"/>
<Button x:Name="PhotoButton" Content="Take a picture!" HorizontalAlignment="Left" Margin="990,678,0,-91" VerticalAlignment="Top" Click="PhotoButton_Click" Height="45" Width="313" Background="White" Foreground="Black"/>
//Timer buttons
<Button x:Name="Timer_3sec" Content="3 seconds" HorizontalAlignment="Left" Margin="138,125,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
<Button x:Name="Timer_5sec" Content="5 seconds" HorizontalAlignment="Left" Margin="138,234,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
<Button x:Name="Timer_7sec" Content="7 seconds" HorizontalAlignment="Left" Margin="138,337,0,0" VerticalAlignment="Top" Height="66" Width="262" Background="White" Foreground="Black"/>
Codes from xaml.cs:
private async void PhotoButton_Click(object sender, RoutedEventArgs e)
{
await TakePhotoAsync();
}
private async Task TakePhotoAsync()
{
var stream = new InMemoryRandomAccessStream();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
Debug.WriteLine("Photo saved!");
await Helpers.MessageDialogHelpers.ShowNoActionMessageBox("Your photo has been taken!", "");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
Create a field in your code behind:
private int _seconds;
Set appropriate time in button handler:
private void Timer_3sec_Click(object sender, RoutedEventArgs e)
{
_seconds = 3;
}
Add the delay to photo button handler:
private async void PhotoButton_Click(object sender, RoutedEventArgs e)
{
await Task.Delay(TimeSpan.FromSeconds(_seconds));
await TakePhotoAsync();
}
This should be enough. If you will notice that your code behind is getting to complex because you are adding all the logic there try to read about MVVM.

unable to run video in WPF

I try to implement a video in WPF. The video is visible in Visual Studio (so I think the path is correct) but isn't visible (I also hear nothing) while I run the program. I have 1 MediaElement to implement the video and 3 Buttons (Play, Pause, Mute) below. The Build-Property of the video is "Resource".
XAML-Code:
<StackPanel HorizontalAlignment="Center" Width="340" Height="300" Margin="281,63,0,0" VerticalAlignment="Center">
<MediaElement Name="myMedia" Source="testvideo.wmv" LoadedBehavior="Manual" Width="320" Height="240" />
<StackPanel Orientation="Horizontal" Margin="0, 10, 0, 0">
<Button Content="Play" Margin="0, 0, 10, 0" Padding="5" Click="mediaPlay"/>
<Button Content="Pause" Margin="0, 0, 10, 0" Padding="5" Click="mediaPause"/>
<Button x:Name="muteButt" Content="Mute" Padding="5" Click="mediaMute"/>
</StackPanel>
</StackPanel>
Code Behind:
public MainWindow()
{
InitializeComponent();
myMedia.Volume = 100;
myMedia.Play();
myMedia.Position = new TimeSpan(0, 0, 5); // first frame 5 seconds
}
void mediaPlay(Object sender, EventArgs e)
{
myMedia.Play();
}
void mediaPause(Object sender, EventArgs e)
{
myMedia.Pause();
}
void mediaMute(Object sender, EventArgs e)
{
if (myMedia.Volume == 100)
{
myMedia.Volume = 0;
muteButt.Content = "Listen";
}
else
{
myMedia.Volume = 100;
muteButt.Content = "Mute";
}
}
I found my problem:
I had to set the property "Source" of the MediaElement in the code behind again. I don't know why, but now it works!

ContextMenu MenuItems adding continuously on Click event

on click event ,I have return adding of menu items to contextmenu.but on clicking more than once it keeps adding the menu items to the contextmenu. Here the below code am using for it.
<StackPanel Grid.Row="13" Orientation="Horizontal" FlowDirection="LeftToRight">
<Button Name="btnMobile" Content="Home" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0 0 20 0" Width="70"></Button>
<!--<extToolkit:DropDownButton x:Name="ddBtnMobile" VerticalAlignment="Top" Width="30" HorizontalAlignment="Right" Margin="0 0 30 0" Height="20"/>-->
<Button HorizontalAlignment="Left" Name="ddBtnMobile" Width="30" Click="OnddBtnMobileClick" Margin="0,0,0,5" >
<Button.Content>
<Path x:Name="btnArrow3" Margin="4" VerticalAlignment="Center" Width="10" Fill="#FF527DB5" Stretch="Uniform" HorizontalAlignment="Right" Data="F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z "/>
</Button.Content>
<Button.ContextMenu>
<ContextMenu Name="cMenu">
</ContextMenu>
</Button.ContextMenu>
</Button>
</StackPanel>
code am using is below
private void OnddBtnMobileClick(object sender, RoutedEventArgs e)
{
mnItem = new MenuItem();
mnItem.Header ="B1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header ="A1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header="B 2";
cMenu.Items.Add(mnItem);
cMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
}
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
RoutedEventArgs args = e as RoutedEventArgs;
MenuItem item = args.OriginalSource as MenuItem;
string header = item.Header.ToString();
if (header == "Business")
{
btnMobile.Content = header;
}
else if (header == "Assistant")
{
btnMobile.Content = header;
}
}
how to solve my issue.. Is there any better way of writing the above logic. i.e., adding menu items of context menu at run time.
add a boolean data member which will check if the sub menu's were already added
private void OnddBtnMobileClick(object sender, RoutedEventArgs e)
{
if(alreadyAdded == true)
return;
alreadyAdded = true;
mnItem = new MenuItem();
mnItem.Header ="B1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header ="A1";
cMenu.Items.Add(mnItem);
mnItem = new MenuItem();
mnItem.Header="B 2";
cMenu.Items.Add(mnItem);
cMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
}
Add the following code in the button click event's starting.
cMenu = new cMenu();
Thats you need to create a new instance.
Thanks,

Resources