Silverlight 4 web cam permission on load of User Control
I am using Silverlight 4 to access the web cam. Everything works ok when I start the web cam on a button click event, I get the prompt for permission. I would like the web cam to start when User Control loads, but for some reason when I run the same code on the Loaded event, I don't get a prompt when executing the following code:'
Ca开发者_运维问答ptureDeviceConfiguration.RequestDeviceAccess()
Does anyone have a work around for this?
I found a workaround to the problem. I am automatically clicking the button that starts the webcam streaming on the Loaded event of the control.
ButtonAutomationPeer peer = new ButtonAutomationPeer(btnStartWebcam);
IInvokeProvider invokeProv =
peer.GetPattern(PatternInterface.Invoke)
as IInvokeProvider;
invokeProv.Invoke();
This does the job for me because I don't mind having a button on the UI. But I guess you can create a dummy one and hide it if it's necessary.
The security around accessing local devices is very tight. Starting the capture must be preceded by a user action.
Instead of starting the capture from the loaded event, you'll have to move it to a Click event.
Code behind:
public void StartCam()
{
VideoCaptureDevice dev = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
if(CaptureDeviceConfiguration.RequestDeviceAccess() &&
CaptureDeviceConfiguration.AllowedDeviceAccess)
{
CaptureSource capture = new CaptureSource();
capture.VideoCaptureDevice = dev;
VideoBrush videoBrush = new VideoBrush();
videoBrush.SetSource(capture);
capture.Start();
WebCamRectangle.Fill = videoBrush;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
StartCam();
}
Xaml:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="49*" />
<RowDefinition Height="251*" />
</Grid.RowDefinitions>
<Rectangle Name="WebCamRectangle"
Stroke="Black" StrokeThickness="1" Grid.Row="1" />
<Button Content="Start" Height="25" HorizontalAlignment="Left"
Margin="12,12,0,0" Name="button1" VerticalAlignment="Top"
Width="135" Click="button1_Click" />
</Grid>
精彩评论