Use Window Activated and Deactivated event to control a media file
<Window x:Class="CustomMediaPlayerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Custom Media Player"
Activated="window_Activated"
Deactivated="window_Deactivated"
Closing="window_Closing">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="_Exit" Click="exitMenu_Click" />
</MenuItem>
</Menu>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" HorizontalAlignment="Center">
<Button Name="playButton" Click="playButton_Click">Play</Button>
<Button Name="clickButton" Click="stopButton_Click">Stop</Button>
</StackPanel>
<MediaElement Stretch="Fill" Name="mediaElement" LoadedBehavior="Manual" Source="numbers.wmv" />
</DockPanel>
</Window>
//File:Window.xaml.vb
Imports System
Imports System.ComponentModel
Imports System.Windows
Public Partial Class CustomMediaPlayerWindow
Inherits Window
Public Sub New()
InitializeComponent()
End Sub
Private isMediaElementPlaying As Boolean
Private Sub playButton_Click(sender As Object, e As RoutedEventArgs)
Me.mediaElement.Play()
Me.isMediaElementPlaying = True
End Sub
Private Sub stopButton_Click(sender As Object, e As RoutedEventArgs)
Me.mediaElement.[Stop]()
Me.isMediaElementPlaying = False
End Sub
Private Sub window_Activated(sender As Object, e As EventArgs)
If Me.isMediaElementPlaying Then
Me.mediaElement.Play()
End If
End Sub
Private Sub window_Deactivated(sender As Object, e As EventArgs)
If Me.isMediaElementPlaying Then
Me.mediaElement.Pause()
End If
End Sub
Private Sub exitMenu_Click(sender As Object, e As RoutedEventArgs)
Me.Close()
End Sub
Private Sub window_Closing(sender As Object, e As CancelEventArgs)
If Me.isMediaElementPlaying Then
e.Cancel = True
End If
End Sub
End Class
Related examples in the same category