Use Silverlight 4’s support for video capture devices.
To set this up, you need to first ask the user for permission to use the web cam. If granted, you can assign the device to a CaptureSource object and then assign that object to a VideoBrush. The VideoBrush can then be used as the Fill brush for the destination control (a Rectangle in this case).
This technique is demonstrated in Listings 1 and 2.
Listing 2. MainPage.xaml
<UserControl x:Class="WebCam.MainPage" 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" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White"> <Rectangle x:Name="videoRect" Fill="Bisque" Width="640" Height="480" VerticalAlignment="Top" HorizontalAlignment="Left"/> <Button Content="Start Webcam" Name="buttonStartWebcam" Width="98" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Click="buttonStartWebcam_Click" /> </Grid> </UserControl>
|
Listing 2. MainPage.xaml.cs
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes;
namespace WebCam { public partial class MainPage : UserControl { CaptureSource _captureSource = null;
public MainPage() { InitializeComponent();
}
void StartWebcam() { if (_captureSource != null && _captureSource.State != CaptureState.Started) { if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess()) { VideoCaptureDevice device = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); if (device != null) { _captureSource = new CaptureSource(); _captureSource.VideoCaptureDevice = device; _captureSource.Start(); VideoBrush brush = new VideoBrush(); brush.Stretch = Stretch.Uniform; brush.SetSource(_captureSource); videoRect.Fill = brush; } } } } private void buttonStartWebcam_Click(object sender, RoutedEventArgs e) { StartWebcam(); } } }
|