bytecode77
bytecode77

Reputation: 14860

Handle Webcam correctly in C#

I've seen lots of libraries for Webcam usage in C#. But there are 2 general problems:

  1. They use the clipboard, which eliminates the user's ability to use the clipboard, too.
  2. There is no way to detect if a webcam is connected except for "shooting a test photo" which could irritate the user as the webcam will flash.

Are there ways to solve any of these two issues?

This is my class so far:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WebcamLibrary
{
    public static class Webcam
    {
        private static IntPtr Handle;

        public static void Start()
        {
            try
            {
                Stop();
                Handle = capCreateCaptureWindowA("WebCap", 0, 0, 0, 320, 240, 0, 0);
                SendMessage(Handle, 1034, 0, 0);
                SendMessage(Handle, 1074, 0, 0);
            }
            catch { }
        }
        public static void Stop()
        {
            try
            {
                SendMessage(Handle, 1035, 0, 0);
                Clipboard.Clear();
            }
            catch { }
        }
        public static Image CaptureFrame()
        {
            try
            {
                SendMessage(Handle, 1084, 0, 0);
                SendMessage(Handle, 1054, 0, 0);
                Image image = (Image)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
                Clipboard.Clear();
                return image;
            }
            catch
            {
                return null;
            }
        }

        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
        [DllImport("avicap32.dll")]
        private static extern IntPtr capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);
    }
}

Upvotes: 1

Views: 2438

Answers (1)

Deanna
Deanna

Reputation: 24293

The VfW capture API is very limited but does allow you to enumerate devices, connect to specific ones, and capture the data into a memory buffer.

It is however, very old, and was obsoleted ~10 years ago by WDM and DirectShow that can also be used from C#.

I don't have code to hand but you create a filter graph, add the webcam device and tell it to render the pin.

Upvotes: 3

Related Questions