atelier:mitsuba

i love UI/UX, Blend, XAML, Behavior, P5, oF, Web, Tangible Bits and Physical computing. なにかあればお気軽にご連絡ください。atelier@c-mitsuba.com

Webcamを叩く

Windowsでぱっとカメラを起動するソフトがなかったので、ぱぱっとOOBで組みました。

起動して、左下の光ちゃんスタイルのボタンをクリックするとカメラが起動します。


以下ソース

MainPage.xaml

<UserControl 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"
	x:Class="SilverlightApplication1.MainPage"
	Width="640" Height="480">

	<Grid x:Name="LayoutRoot" Background="White">
		<Rectangle x:Name="cam" Fill="#FFF4F4F5" />
		<Button x:Name="button" Content="Button" HorizontalAlignment="Right" Height="165" Style="{StaticResource ButtonStyle1}" VerticalAlignment="Bottom" Width="134" Click="Button_Click"/>
	</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
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 SilverlightApplication1
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			// 変数を初期化するときに必要となります
			InitializeComponent();
		}

		private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: ここにイベント ハンドラーのコードを追加します。
			if (!CaptureDeviceConfiguration.AllowedDeviceAccess) {
				if (!CaptureDeviceConfiguration.RequestDeviceAccess()) {
				return;
				}
			}
			StartCapture();
		}
		
		private void StartCapture() {
			CaptureSource source = new CaptureSource();
			source.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
			VideoBrush video = new VideoBrush();
			video.SetSource(source);
			cam.Fill = video;
			try {
				source.Start();
			} catch (InvalidOperationException) {
				MessageBox.Show("キャプチャーを開始できませんでした。");
			}
		}
	}
}


App.xaml

<Application
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	x:Class="SilverlightApplication1.App">
	<Application.Resources>
		<!-- アプリケーション レベルでスコープされたリソースは、ここで定義する必要があります。 -->
		<Style x:Key="ButtonStyle1" TargetType="Button">
			<Setter Property="Template">
				<Setter.Value>
					<ControlTemplate TargetType="Button">
						<Grid>
							<Image Source="/光.png" Stretch="Fill"/>
							<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content=""/>
						</Grid>
					</ControlTemplate>
				</Setter.Value>
			</Setter>
		</Style>
	</Application.Resources>
</Application>