Logo
PREGNANCY
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
 
 
Windows 7

Visual Basic 2010 : Manipulating Documents and Media - Viewing Images & Playing Media

7/6/2011 11:34:53 AM
Windows Presentation Foundation offers native controls for working with media contents and for manipulating documents. This last topic is also important because documents are one of the most common requirements in modern applications, and WPF provides a way for creating and managing documents that can be dynamically arranged to offer a better user experience.

Viewing Images

You use the System.Windows.Controls.Image control to show images. The Visual Studio 2010 designer provides some improvements to help you manage more images than in the past editions. To see how the control works, create a new WPF project and name it as DocumentsAndMedia. When ready, drag an Image control from the toolbox onto the new Window; then set its dimensions as you like. To view an image, you need to set the Source property that basically points to an Uri. Open the Properties window by pressing F4 and then click the button for the Source property. At this point you can select one or more images to add as resources to your project, as shown in Figure 1. When you add your images at this point, simply select the one you want to be shown inside the Image control. When you click OK, Visual Studio generates a subfolder in the project main folder, naming the new folder as Images and setting the build action for added images as Resource.

Figure 1. Adding images to the project.

Visual Studio also automatically sets the Source property for you, taking advantage of the packed Uri, as demonstrated by the following line of XAML code:

<Image Source="/DocumentsAndMedia;component/Images/IMG006.jpg"
Stretch="Fill" Name="Image1" />

The Stretch property enables establishing how pictures will be tiled inside the Image control. Fill, which is the default value, dynamically adapts the picture to fill the entire Image control, but when you resize the control you may lose the original aspect ratio. If you instead use Uniform you can keep the aspect ratio and dynamically adapt the picture; while setting UniformToFill the picture will work like Uniform except that it will clip the source image so that the layout will be based on the ImageStretch property with None, the source image will be shown in its original size. Figure 2 shows how the image looks with Stretch set as Fill. control size. If you instead assign the

Figure 2. Showing images with the Image control.

You can also assign the Source property at runtime from Visual Basic code so that you can provide users the ability of selecting different pictures. Differently from the XAML code, in VB you need to create first an instance of the BitmapImage class and assign some of its properties as follows:

Private Sub LoadPicture(ByVal fileName As String)

Dim img As New BitmapImage
With img
.BeginInit()
.BaseUri = New Uri("MyPicture.jpg")
.EndInit()
End With

Image1.Source = img
End Sub

Basically you invoke BeginInit to start editing; then you set BaseUri pointing to the desired file and finally invoke EndInit to finish editing. When you perform these steps, you can assign the new instance to the Image.Source property.

Playing Media

Windows Presentation Foundation enables easily reproducing media files, such as audio and videos, through the System.Windows.Controls.MediaElement control. This basically enables reproducing, among others, all media contents supported by the Windows Media Player application, thus .Wmv, .Wma, .Avi, and .Mp3 files. This section shows you how to build a simple media player using MediaElement and Visual Basic 2010. Now add a new Window to an existing project setting this as the main window. The goal of the next example is to implement a media player and buttons for controlling media reproduction. Code in Listing 1 declares the user interface.

Listing 1. Defining the User Interface for a Simple Media Player
<Window x:Class="PlayingMedia"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PlayingMedia" Height="300" Width="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<MediaElement Name="Media1" Grid.Row="0" LoadedBehavior="Manual"
Volume="{Binding ElementName=VolumeSlider, Path=Value}"
MediaFailed="Media1_MediaFailed"
MediaEnded="Media1_MediaEnded"/>

<StackPanel Orientation="Horizontal" Grid.Row="1">
<Button Name="PlayButton" Width="70" Height="40"
Margin="5" Click="PlayButton_Click"
Content="Play"/>

<Button Name="PauseButton" Width="70" Height="40"
Margin="5" Click="PauseButton_Click"
Content="Pause"/>

<Button Name="StopButton" Width="70" Height="40"
Margin="5" Click="StopButton_Click"
Content="Stop"/>

<Button Name="BrowseButton" Width="40" Height="40"
Margin="5" Content="..."
Click="BrowseButton_Click"/>

<Slider Name="VolumeSlider" Width="80" Margin="5"
Minimum="0" Maximum="1" Value="0.5"
TickFrequency="0.1"
AutoToolTipPlacement="TopLeft"
TickPlacement="BottomRight"
ToolTip="Adjust volume"/>
</StackPanel>
</Grid>
</Window>


The MediaElement control has basically no look, so when you place it onto the user interface, it has a transparent background and border, although you can replace this with your custom background and border. The LoadedBehavior property enables establishing how the media file needs to be reproduced; for example, Play means that the associated video will be automatically played when the control is loaded, whereas Manual means that playing will be started via Visual Basic code at the specified moment. (IntelliSense can help you to choose the most appropriate self-explanatory option.) You associate a media file to the MediaElement assigning the Source property, but this is not mandatory because you can accomplish this later in code. The Volume property enables adjusting reproduction volume, and its range is between 0 and 1. In this example the Volume value is bound to the VolumeSlider.Value property. The control also offers some events such as MediaFailed and MediaEnded that respectively are raised when an error occurs when attempting to open the media file and when the reproduction completes. The MediaElement control also provides some methods for controlling reproduction in code, such as Play, Pause, and Stop. Code in Listing 2 shows how to implement the features and how to allow media selection from disk.

Listing 2. Controlling the MediaElement in Code
Public Class PlayingMedia

Dim sourceMedia As String = String.Empty

Private Sub Media1_MediaEnded(ByVal sender As System.Object,
ByVal e As System.Windows.
RoutedEventArgs)
'Playing completed
End Sub

Private Sub Media1_MediaFailed(ByVal sender As System.Object,
ByVal e As System.Windows.
ExceptionRoutedEventArgs)
MessageBox.Show(e.ErrorException.Message)
End Sub

Private Sub PlayButton_Click(ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
If String.IsNullOrEmpty(Me.sourceMedia) = False Then
Me.Media1.Play()
End If
End Sub

Private Sub PauseButton_Click(ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
If String.IsNullOrEmpty(Me.sourceMedia) = False Then
Me.Media1.Pause()
End If
End Sub

Private Sub StopButton_Click(ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
If String.IsNullOrEmpty(Me.sourceMedia) = False Then
Me.Media1.Stop()
End If
End Sub

Private Sub BrowseButton_Click(ByVal sender As System.Object,
ByVal e As System.Windows.RoutedEventArgs)
Dim dialog As New Microsoft.Win32.OpenFileDialog

With dialog
.Title = "Select a media file"
.Filter = "Avi & Wmv|*.avi;*.wmv|Audio|*.wma;*.mp3|All files|*.*"
If .ShowDialog = True Then
Me.sourceMedia = .FileName
Me.Media1.Source = New Uri(sourceMedia,
UriKind.RelativeOrAbsolute)
End If
End With
End Sub
End Class


Notice how the MediaFailed event handler shows an error message in case an exception is thrown and how the media file is assigned under the form of an Uri to the MediaElement.Source property. This also means that you can assign an Uri such as a Web address to play a media content stored on a website. At this point you can run the application, click the Browse button to select your media content and click Play. Figure 3 shows the application playing a video.

Figure 3. The sample application playing a video.

The MediaElement control also offers a Position property (of type TimeSpan) that provides the ability to seek the desired position within the media content.

Other -----------------
- Automating the Windows 7 Installation : Deploying Unattended Installations (part 4) - Microsoft Assessment and Planning Toolkit
- Automating the Windows 7 Installation : Deploying Unattended Installations (part 3) - Installing the WDS Server Components
- Automating the Windows 7 Installation : Deploying Unattended Installations (part 2) - Using Windows System Image Manager to Create Answer Files
- Automating the Windows 7 Installation : Deploying Unattended Installations (part 1)
- Microsoft Visio 2010 : Understanding Organization Charts & Building an Organization Chart by Hand
- Microsoft Visio 2010 : Creating Swimlane Diagrams
- Microsoft Excel 2010 : Editing Chart Data
- Microsoft Excel 2010 : Changing the Chart Background & Enhancing a Chart
- Microsoft Excel 2010 : Formatting Chart Text & Formatting Line and Bar Charts
- Visual Studio 2010 : Building the Windows Container (part 3) - Creating a Multiple Document Interface
- Visual Studio 2010 : Building the Windows Container (part 2) - Adding menus and toolbars
- Visual Studio 2010 : Building the Windows Container (part 1) - Setting common form properties & Creating dialog boxes
- Microsoft Visio 2010 : Adding Labels to Flowcharts & Understanding Swimlane Diagrams
- Microsoft Visio 2010 : Selecting a Flowchart Type & Creating Flowcharts
- Automating the Windows 7 Installation : Choosing Automated Deployment Options (part 3) - An Overview of the System Preparation Tool and Disk Imaging
- Automating the Windows 7 Installation : Choosing Automated Deployment Options (part 2)
- Automating the Windows 7 Installation : Choosing Automated Deployment Options (part 1) - An Overview of the Microsoft Deployment Toolkit 2010
- Advanced .NET Framework with VB 2010 : Coding Attributes - Reflecting Attributes
- Advanced .NET Framework with VB 2010 : Coding Attributes - Coding Custom Attributes
- Advanced .NET Framework with VB 2010 : Coding Attributes - Applying Attributes
 
 
Most view of day
- Windows Server 2012 Group Policies and Policy Management : GPO Administrative Tasks - Creating and Linking WMI Filters to GPOs
- Microsoft Dynamics GP 2010 : Maintaining Dynamics GP - Preventing entry of wrong dates by Closing Periods
- Windows Server 2012 Group Policies and Policy Management : Understanding Group Policy (part 1) - GPO Storage and Replication
- Deploying Applications Using Group Policy and SCCM 2007 : Deploying Applications Using SCCM 2007 (part 1)
- SQL Server 2008 R2 : Managing Workloads with the Resource Governor - Modifying Your Resource Governor Configuration
- Maintaining Security : Authorizing Administrative Actions, Restricting Access to Web Content
- Adobe Dreamweaver CS5 : Using Java Applets
- Administering an Exchange Server 2013 Environment (part 6) - Introduction to Role Based Access Control
- Integrating SharePoint 2013 with the Office Applications (part 3) - Microsoft Excel
- Microsoft Exchange Server 2007 : Hub Transport Server Policy Compliance Features (part 3) - Journaling
Top 10
- Windows Phone 8 : Configuring Mailbox Settings (part 5) - Configuring Automatic Replies
- Windows Phone 8 : Configuring Mailbox Settings (part 4) - Lightening the Display,Changing the Mailbox Sync Settings
- Windows Phone 8 : Configuring Mailbox Settings (part 3) - Message Signatures, Blind CCing Yourself
- Windows Phone 8 : Configuring Mailbox Settings (part 2) - Unlinking Mailboxes, Conversation View
- Windows Phone 8 : Configuring Mailbox Settings (part 1) - Linking Mailboxes
- Managing Windows Server 2012 Systems : Configuring Roles, Role Services, and Features (part 6) - Tracking installed roles, role services, and features
- Managing Windows Server 2012 Systems : Configuring Roles, Role Services, and Features (part 5) - Installing components at the prompt
- Managing Windows Server 2012 Systems : Configuring Roles, Role Services, and Features (part 4) - Managing server binaries
- Managing Windows Server 2012 Systems : Configuring Roles, Role Services, and Features (part 3) - Adding server roles and features
- Managing Windows Server 2012 Systems : Configuring Roles, Role Services, and Features (part 2) - Installing components with Server Manager - Viewing configured roles and role services
 
 
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro