Click here to Skip to main content
13,146,739 members (92,672 online)
Click here to Skip to main content
Add your own
alternative version


331 bookmarked
Posted 17 Nov 2011

WPF: Webcam Control

, 6 May 2016
Rate this:
Please Sign up or sign in to vote.
A WPF UserControl for displaying and recording video from a webcam



Webcam is a WPF user control that uses the Expression Encoder SDK to enable easy display of webcam video in a WPF application.


The user control has the following features,

  • Displays webcam video,
  • Enables saving of webcam video (in .wmv format),
  • Enables saving of video snapshots.




WPF_WebcamControl/Property.pngVideoFileFormatGets the format in which webcam videos will be saved. This is a dependency property of type String.
WPF_WebcamControl/Property.pngSnapshotFormatGets or sets the format used when saving snapshots of webcam preview. This is a dependency property of type ImageFormat.
WPF_WebcamControl/Property.pngVideoDeviceGets or sets the webcam to be used. This is a dependency property of type Microsoft.Expression.Encoder.Devices.EncoderDevice.
WPF_WebcamControl/Property.pngAudioDeviceGets or sets the microphone to be used. This is a dependency property of type Microsoft.Expression.Encoder.Devices.EncoderDevice
WPF_WebcamControl/Property.pngVideoNameGets or sets the name of the video file – which should not include the file extension. This is a dependency property of type String.
WPF_WebcamControl/Property.pngVideoDirectoryGets or sets the folder where the webcam video will be saved. This is a dependency property of type String.
WPF_WebcamControl/Property.pngImageDirectoryGets or sets the folder where video snapshots will be saved. This is a dependency property of type String.
WPF_WebcamControl/Property.pngBitrateGets or sets the bitrate. This is a dependency property of type Integer. (The default value is 2000).
WPF_WebcamControl/Property.pngFrameRateGets or sets the frame rate, in frames per second. This is a dependency property of type Integer. (The default value is 15).
WPF_WebcamControl/Property.pngFrameSizeGets or sets the size of the video profile. This is a dependency property of type System.Drawing.Size. (The default value is 320x240).
WPF_WebcamControl/Property.pngIsRecordingGets a value indicating whether video recording is taking place. This is a dependency property of type Boolean.


WPF_WebcamControl/Method.pngStartPreviewStarts the display of webcam preview. (Throws a Microsoft.Expression.Encoder.SystemErrorException if a specified device is already in use by another application)
WPF_WebcamControl/Method.pngStopPreviewStops the display of webcam preview. (Stops recording of webcam video)
WPF_WebcamControl/Method.pngStartRecordingStarts the recording of webcam preview to a video file. (Throws a DirectoryNotFoundException if the directory specified in the VideoDirectory property does not exist or if the property is not set).
WPF_WebcamControl/Method.pngStopRecordingStops the recording of webcam preview.
WPF_WebcamControl/Method.pngTakeSnapshotSaves a snapshot of webcam preview. (Throws a DirectoryNotFoundException if the directory specified in the ImageDirectory property does not exist or if the property is not set).


The following example shows how to use the user control. The example contains a Webcam control, two ComboBoxes for displaying video and audio devices, and several buttons for calling the various methods of the user control.

<Window x:Class="MainWindow"




    Title="WPF Webcam" Height="495" Width="353">
        <DataTemplate x:Key="DevicesListTemplate">
            <TextBlock Text="{Binding Name}"/>
            <RowDefinition Height="207"/>
        <cam:Webcam Name="WebcamCtrl" Margin="10" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

        <StackPanel Margin="0,5,0,0" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Row="1">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Height="22">
                <TextBlock Height="22" Width="78" HorizontalAlignment="Left" VerticalAlignment="Top"

                           Text="Video Device" TextAlignment="Left" FlowDirection="LeftToRight" />
                <ComboBox Height="22" Width="210" HorizontalAlignment="Left" VerticalAlignment="Top"

                          x:Name="VideoDevicesComboBox" ItemTemplate="{StaticResource DevicesListTemplate}"/>

            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Height="23" Margin="0,10,0,0">
                <TextBlock Height="22" Width="78" HorizontalAlignment="Left" VerticalAlignment="Top"

                           Text="Audio Device" TextAlignment="Left" FlowDirection="LeftToRight"/>
                <ComboBox HorizontalAlignment="Left" Height="23" Width="210" VerticalAlignment="Bottom"

                          x:Name="AudioDevicesComboBox" ItemTemplate="{StaticResource DevicesListTemplate}"/>

        <Grid Margin="0,0,0,20" HorizontalAlignment="Center" VerticalAlignment="Bottom" Grid.Row="1">
            <Button Content="Start Recording" Height="24" Width="115" Margin="0,40,0,0" HorizontalAlignment="Left" 

                    VerticalAlignment="Top" x:Name="StartRecordingButton" Click="StartRecordingButton_Click"/>
            <Button Content="Stop Recording" Height="24" Width="112" Margin="0,40,0,0" HorizontalAlignment="Right" 

                    VerticalAlignment="Top" x:Name="StopRecordingButton" Click="StopRecordingButton_Click"/>
            <Button Content="Stop Capture" Height="24" Width="112" HorizontalAlignment="Right" 

                    VerticalAlignment="Top" x:Name="StopCaptureButton" Click="StopCaptureButton_Click"/>
            <Button Content="Start Capture" Height="24" Width="115" HorizontalAlignment="Left" 

                    VerticalAlignment="Top" x:Name="StartCaptureButton" Click="StartCaptureButton_Click"/>
            <Button Content="Take Snapshot" Height="24" Width="120" Margin="60,78,60,0" HorizontalAlignment="Center" 

                    VerticalAlignment="Top" x:Name="TakeSnapshotButton" Click="TakeSnapshotButton_Click"/>
using System.Windows;
using System.Windows.Data;
using Microsoft.Expression.Encoder.Devices;
using WebcamControl;
using System.IO;

namespace WPF_Webcam_CS
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        public MainWindow()
            Binding binding_1 = new Binding("SelectedValue");
            binding_1.Source = VideoDevicesComboBox;
            WebcamCtrl.SetBinding(Webcam.VideoDeviceProperty, binding_1);

            Binding binding_2 = new Binding("SelectedValue");
            binding_2.Source = AudioDevicesComboBox;
            WebcamCtrl.SetBinding(Webcam.AudioDeviceProperty, binding_2);

            // Create directory for saving video files
            string videoPath = @"C:\VideoClips";

            if (! Directory.Exists(videoPath))
            // Create directory for saving image files
            string imagePath = @"C:\WebcamSnapshots";

            if (! Directory.Exists(imagePath))

            // Set some properties of the Webcam control
            WebcamCtrl.VideoDirectory = videoPath;
            WebcamCtrl.ImageDirectory = imagePath;
            WebcamCtrl.FrameRate = 30;
            WebcamCtrl.FrameSize = new System.Drawing.Size(640, 480);

            // Find available a/v devices
            var vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video);
            var audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio);
            VideoDevicesComboBox.ItemsSource = vidDevices;
            AudioDevicesComboBox.ItemsSource = audDevices;
            VideoDevicesComboBox.SelectedIndex = 0;
            AudioDevicesComboBox.SelectedIndex = 0;

        private void StartCaptureButton_Click(object sender, RoutedEventArgs e)
                // Display webcam video
            catch (Microsoft.Expression.Encoder.SystemErrorException ex)
                MessageBox.Show("Device is in use by another application");

        private void StopCaptureButton_Click(object sender, RoutedEventArgs e)
            // Stop the display of webcam video.

        private void StartRecordingButton_Click(object sender, RoutedEventArgs e)
            // Start recording of webcam video to harddisk.

        private void StopRecordingButton_Click(object sender, RoutedEventArgs e)
            // Stop recording of webcam video to harddisk.

        private void TakeSnapshotButton_Click(object sender, RoutedEventArgs e)
            // Take snapshot of webcam video.
Imports Microsoft.Expression.Encoder.Devices
Imports WebcamControl
Imports System.IO
Imports System.Drawing

Class MainWindow

    Public Sub New()
        ' This call is required by the designer.

        ' Add any initialization after the InitializeComponent() call.

        Dim binding_1 As New Binding("SelectedValue")
        binding_1.Source = VideoDevicesComboBox
        WebcamCtrl.SetBinding(Webcam.VideoDeviceProperty, binding_1)

        Dim binding_2 As New Binding("SelectedValue")
        binding_2.Source = AudioDevicesComboBox
        WebcamCtrl.SetBinding(Webcam.AudioDeviceProperty, binding_2)

        ' Create directory for saving video files
        Dim videoPath As String = "C:\VideoClips"

        If Not Directory.Exists(videoPath) Then
        End If
        ' Create directory for saving image files
        Dim imagePath As String = "C:\WebcamSnapshots"

        If Not Directory.Exists(imagePath) Then
        End If

        ' Set some properties of the Webcam control
        WebcamCtrl.VideoDirectory = videoPath
        WebcamCtrl.ImageDirectory = imagePath
        WebcamCtrl.FrameRate = 30
        WebcamCtrl.FrameSize = New Size(640, 480)

        ' Find available a/v devices
        Dim videoDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video)
        Dim audioDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio)
        VideoDevicesComboBox.ItemsSource = videoDevices
        AudioDevicesComboBox.ItemsSource = audioDevices
        VideoDevicesComboBox.SelectedIndex = 0
        AudioDevicesComboBox.SelectedIndex = 0
    End Sub

    Private Sub StartCaptureButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        ' Display webcam video
        Catch ex As Microsoft.Expression.Encoder.SystemErrorException
            MessageBox.Show("Device is in use by another application")
        End Try
    End Sub

    Private Sub StopCaptureButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        ' Stop the display of webcam video
    End Sub

    Private Sub StartRecordingButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        ' Start recording of webcam video
    End Sub

    Private Sub StopRecordingButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        ' Stop recording of webcam video
    End Sub

    Private Sub TakeSnapshotButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        ' Take snapshot of webcam video
    End Sub
End Class

In the code sample the audio and video devices are listed using the EncoderDevices.FindDevices() method. The EncoderDevices class is found in the Microsoft.Expression.Encoder.Devices namespace, so when using the webcam user control in your project ensure that you have installed Expression Encoder and added a reference to Microsoft.Expression.Encoder.dll. You can do this by right-clicking your project, selecting Add Reference from the context menu, and selecting Microsoft.Expression.Encoder in the Assemblies > Extensions section of the Reference Manager dialog box.

NB: When using Microsoft.Expression.Encoder.dll and WebcamControl.dll in your project ensure that the project build platform is set to x86.


The following is the XAML markup for the user control,

<UserControl x:Class="Webcam" 






             MinHeight="100" MinWidth="100"

        <WindowsFormsHost Name="WinFormsHost" Margin="0" Background="{x:Null}">
            <wf:Panel x:Name="WebcamPanel"/>

To display video from a webcam the user control makes use of the LiveJob class, which is in the Microsoft.Expression.Encoder.Live namespace. LiveJob expose routines for encoding video and audio from a live source such as a webcam. The webcam video is displayed in a WinForms Panel which is hosted in a WindowsFormsHost.

''' <summary>
''' Displays webcam video.
''' </summary>
Public Sub StartPreview()
        If _videoDevice IsNot Nothing Then

            Job = New LiveJob
            Dim frameDuration As Long = CLng(FrameRate * Math.Pow(10, 7))

            deviceSource = Job.AddDeviceSource(_videoDevice, _audioDevice)
            deviceSource.PickBestVideoFormat(FrameSize, frameDuration)
            deviceSource.PreviewWindow = New PreviewWindow(New HandleRef(WebcamPanel, WebcamPanel.Handle))

            Job.OutputFormat.VideoProfile = New AdvancedVC1VideoProfile With {.Size = FrameSize,
                    .FrameRate = FrameRate, .Bitrate = New ConstantBitrate(Bitrate)}


            isPreviewing = True
        End If
    Catch ex As SystemErrorException
        Throw New SystemErrorException
    Catch ex As FeatureNotAvailableException
    End Try
End Sub

The LiveJob object is used to save webcam videos using the LiveJob.StartEncoding() method.

''' <summary>
''' Starts the recording of webcam images to a video file.
''' </summary>
Public Sub StartRecording()
    If VideoDirectory = String.Empty Then
        Throw New DirectoryNotFoundException("Video directory has not been specified")
        Exit Sub
    ElseIf Not Directory.Exists(VideoDirectory) Then
        Throw New DirectoryNotFoundException("The specified video directory does not exist")
        Exit Sub
    End If

    If Job IsNot Nothing AndAlso isPreviewing Then
        Dim filePath As String

        If String.IsNullOrEmpty(VideoName) Then
            filePath = Path.Combine(VideoDirectory, "Webcam " & TimeStamp() & ".wmv")
            filePath = Path.Combine(VideoDirectory, VideoName & ".wmv")
        End If

        Dim archiveFormat As New FileArchivePublishFormat(filePath)

        If Job.PublishFormats.Count > 0 Then
        End If


        SetValue(IsRecordingPropertyKey, True)
    End If
End Sub

A snapshot of a webcam video is actually just a snapshot of the WinForms Panel,

''' <summary>
''' Takes a snapshot of an webcam image.
''' The size of the image will be equal to the size of the control.
''' </summary>
Public Sub TakeSnapshot()
    Dim imgDir As String = CType(GetValue(ImageDirectoryProperty), String)

    If (imgDir = String.Empty) Then
        Throw New DirectoryNotFoundException("Image directory has not been specified")
        Exit Sub
    ElseIf (Not Directory.Exists(imgDir)) Then
        Throw New DirectoryNotFoundException("The specified image directory does not exist")
        Exit Sub
    End If

    If (job IsNot Nothing AndAlso isPreviewing) Then
        Dim panelWidth As Integer = WebcamPanel.Width
        Dim panelHeight As Integer = WebcamPanel.Height
        Dim imgFormat As ImageFormat = CType(GetValue(SnapshotFormatProperty), ImageFormat)
        Dim filePath As String = Path.Combine(imgDir, "Snapshot " & TimeStamp() & "." & imgFormat.ToString)
        Dim pnt As Point = WebcamPanel.PointToScreen(New Point(WebcamPanel.ClientRectangle.X, WebcamPanel.ClientRectangle.Y))

        Using bmp As New Bitmap(panelWidth, panelHeight)
            Using grx As Graphics = Graphics.FromImage(bmp)
                grx.CopyFromScreen(pnt, Point.Empty, New Size(panelWidth, panelHeight))
            End Using
            bmp.Save(filePath, imgFormat)
        End Using
    End If
End Sub

If you want to take a look at the rest of the code for the usercontrol check out the user control library project in the source download.


I hope you found this article useful. In case of any queries you can leave a comment and I'll do my best to answer.


  • 18th Nov, 2011: Initial post
  • 19th Nov, 2011: Updated code
  • 31st Mar, 2012: Added snapshot feature.
  • 17th Nov, 2012: Added FrameRate and FrameSize properties.
  • 30th Oct, 2013: v3.0
  • 24th July, 2014: v3.1,
    • Webcam preview now resizes with control,
    • StartCapture() renamed to StartPreview(),
    • StopCapture() renamed to StopPreview().
  • 6th May, 2016: Added Bitrate and VideoName properties.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Meshack Musundi
Software Developer
Kenya Kenya
Meshack is a software developer with a passion for WPF.


  • CodeProject MVP 2013

  • CodeProject MVP 2012

You may also be interested in...


Comments and Discussions

GeneralRe: Saving captured image to SQL Pin
Meshack Musundi25-Sep-12 18:43
mvpMeshack Musundi25-Sep-12 18:43 
QuestionDevice is in use by another application Pin
Espiritu27-Aug-12 2:01
memberEspiritu27-Aug-12 2:01 
AnswerRe: Device is in use by another application Pin
Meshack Musundi28-Aug-12 21:15
mvpMeshack Musundi28-Aug-12 21:15 
AnswerRe: Device is in use by another application Pin
g3rdi25-Sep-12 7:55
memberg3rdi25-Sep-12 7:55 
Could have something to do with a bitmap open file process .. if you are displaying the image. I was running into this problem too. I ended up just adding to the images to my DB and then pulling them from there but check this out for a solution maybe[^]
AnswerRe: Device is in use by another application Pin
Vince Chen61122-Oct-12 3:25
memberVince Chen61122-Oct-12 3:25 
GeneralMy vote of 5 Pin
Christian Amado24-Aug-12 16:49
memberChristian Amado24-Aug-12 16:49 
GeneralRe: My vote of 5 Pin
Meshack Musundi25-Aug-12 7:05
mvpMeshack Musundi25-Aug-12 7:05 
Questionhaving a bit of a problem with webCamCtrl.StopCapture(); Pin
g3rdi23-Aug-12 11:15
memberg3rdi23-Aug-12 11:15 
AnswerRe: having a bit of a problem with webCamCtrl.StopCapture(); Pin
Meshack Musundi23-Aug-12 23:43
mvpMeshack Musundi23-Aug-12 23:43 
GeneralRe: having a bit of a problem with webCamCtrl.StopCapture(); Pin
g3rdi25-Aug-12 6:10
memberg3rdi25-Aug-12 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 6 May 2016
Article Copyright 2011 by Meshack Musundi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid