Question

All I am trying to display camera captured frames in WPF. I already can display image. But can't figure out the event handling method? In WinForm it is Application.Idle but what should I use in WPF? I have seen this thread already ..I couldn't make it .

Was it helpful?

Solution

Why can't you use Timer.Elapsed event?

Just remember that Elapsed callback occurs in Worker Thread, that makes impossible update of UI. So you should use SynchronizationContext to direct UI update actions to proper thread.

    private SynchronizationContext _context = SynchronizationContext.Current;

    void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                this._context.Send(o => 
                    {
                        using (var stream = new MemoryStream())
                        {
                            // My way to display frame 
                            frame.Bitmap.Save(stream, ImageFormat.Bmp);

                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = new MemoryStream(stream.ToArray());
                            bitmap.EndInit();

                            webcam.Source = bitmap;
                        }

                    }, 
                    null);
            }
        }
    }

Alternatively, as all UI tasks go through Dispatcher, you could react on DispatcherInactive event:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //...
        this.Dispatcher.Hooks.DispatcherInactive += new EventHandler(Hooks_DispatcherInactive);
    }

    void Hooks_DispatcherInactive(object sender, EventArgs e)
    {
        using (Image<Bgr, byte> frame = capture.QueryFrame())
        {
            if (frame != null)
            {
                using (var stream = new MemoryStream())
                {
                    // My way to display frame 
                    frame.Bitmap.Save(stream, ImageFormat.Bmp);

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = new MemoryStream(stream.ToArray());
                    bitmap.EndInit();

                    webcam.Source = bitmap;
                };
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top