18

I need to capture video from a webcam. Are there any classes in C#/.NET that can help me with this. I am only interested in real time data.

And are there any good C#/.NET books that I can study to gain deep knowledge on the language and the platform?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
olive
  • 2,983
  • 5
  • 21
  • 20
  • Welcome to StackOverflow. I recommend you register for an account so you can keep track of your questions consistently. This is an excellent question, but you ask two questions here. Can you make the second question a new question? I think that you can actually find the answer you want here: [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) but I would not hesitate to ask if that cannot help you. It should be able to. – jcolebrand Feb 10 '11 at 04:13
  • 1
    I would recomend you to split your questions in two parts: the webcam part and the books part. – Dmitrii Lobanov Feb 10 '11 at 04:48
  • 1
    @drachenstern: Doubt he'll find the answer to his C# question in a book about C++. I suppose it's possible, though. – Cody Gray - on strike Feb 10 '11 at 05:05
  • @CodyGray You're right I grabbed the wrong stinking link from what I meant :\ ... and you're only 50 minutes late for me to correct it in the 5 minute window ;) [What are the best C# .NET books](http://stackoverflow.com/questions/477748/what-are-the-best-c-net-books) – jcolebrand Feb 10 '11 at 05:09
  • This is duplicate of many other questions about webcam, for example: http://stackoverflow.com/questions/233455/webcam-usage-in-c I don't know how to report this properly, sorry. – greenoldman Feb 10 '11 at 06:17
  • @Macias ~ Click the flag button and you'll get an option that shows "doesn't belong here" then "exact duplicate" – jcolebrand Feb 10 '11 at 21:18

4 Answers4

13

This is what I use. You need a first class to iterate your devices:

public class DeviceManager
{
    [DllImport("avicap32.dll")]
    protected static extern bool capGetDriverDescriptionA(short wDriverIndex,
        [MarshalAs(UnmanagedType.VBByRefStr)]ref String lpszName,
       int cbName, [MarshalAs(UnmanagedType.VBByRefStr)] ref String lpszVer, int cbVer);

    static ArrayList devices = new ArrayList();

    public static TCamDevice[] GetAllDevices()
    {
        String dName = "".PadRight(100);
        String dVersion = "".PadRight(100);

        for (short i = 0; i < 10; i++)
        {
            if (capGetDriverDescriptionA(i, ref dName, 100, ref dVersion, 100))
            {
                TCamDevice d = new TCamDevice(i);
                d.Name = dName.Trim();
                d.Version = dVersion.Trim();

                devices.Add(d);
            }
        }

        return (TCamDevice[])devices.ToArray(typeof(TCamDevice));
    }

    public static TCamDevice GetDevice(int deviceIndex)
    {
        return (TCamDevice)devices[deviceIndex];
    }
}

ANd this one to control the cam.

public class TCamDevice
{
     private const short WM_CAP = 0x400;
    private const int WM_CAP_DRIVER_CONNECT = 0x40a;
    private const int WM_CAP_DRIVER_DISCONNECT = 0x40b;
    private const int WM_CAP_EDIT_COPY = 0x41e;
    private const int WM_CAP_SET_PREVIEW = 0x432;
    private const int WM_CAP_SET_OVERLAY = 0x433;
    private const int WM_CAP_SET_PREVIEWRATE = 0x434;
    private const int WM_CAP_SET_SCALE = 0x435;
    private const int WS_CHILD = 0x40000000;
    private const int WS_VISIBLE = 0x10000000;

    [DllImport("avicap32.dll")]
    protected static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)] ref string lpszWindowName,
        int dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int nID);

    [DllImport("user32", EntryPoint = "SendMessageA")]
    protected static extern int SendMessage(int hwnd, int wMsg, int wParam, [MarshalAs(UnmanagedType.AsAny)] object lParam);

    [DllImport("user32")]
    protected static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);

    [DllImport("user32")]
    protected static extern bool DestroyWindow(int hwnd);

    int index;
    int deviceHandle;

    public TCamDevice(int index)
    {
        this.index = index;
    }

    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    private string _version;

    public string Version
    {
        get { return _version; }
        set { _version = value; }
    }

    public override string ToString()
    {
        return this.Name;
    }
    /// <summary>
    /// To Initialize the device
    /// </summary>
    /// <param name="windowHeight">Height of the Window</param>
    /// <param name="windowWidth">Width of the Window</param>
    /// <param name="handle">The Control Handle to attach the device</param>
    public void Init(int windowHeight, int windowWidth, int handle)
    {
        string deviceIndex = Convert.ToString(this.index);
        deviceHandle = capCreateCaptureWindowA(ref deviceIndex, WS_VISIBLE | WS_CHILD, 0, 0, windowWidth, windowHeight, handle, 0);

        if (SendMessage(deviceHandle, WM_CAP_DRIVER_CONNECT, this.index, 0) > 0)
        {
            SendMessage(deviceHandle, WM_CAP_SET_SCALE, -1, 0);
            SendMessage(deviceHandle, WM_CAP_SET_PREVIEWRATE, 0x42, 0);
            SendMessage(deviceHandle, WM_CAP_SET_PREVIEW, -1, 0);

            SetWindowPos(deviceHandle, 1, 0, 0, windowWidth, windowHeight, 6);
        }
    }

    /// <summary>
    /// Shows the webcam preview in the control
    /// </summary>
    /// <param name="windowsControl">Control to attach the webcam preview</param>
    public void ShowWindow(global::System.Windows.Forms.Control windowsControl)
    {
        Init(windowsControl.Height, windowsControl.Width, windowsControl.Handle.ToInt32());                        
    }

    /// <summary>
    /// Stop the webcam and destroy the handle
    /// </summary>
    public void Stop()
    {
        SendMessage(deviceHandle, WM_CAP_DRIVER_DISCONNECT, this.index, 0);

        DestroyWindow(deviceHandle);
    }
}

The ShowWindow takes your PictureBox as parameter.

Burcephal
  • 445
  • 4
  • 9
  • i am using the same way as u r doing but i found that the webcam is not invoked always.if i reboot my system the webcam will invoke when i press start button but if i stop and again press start then video is not displayed. the values of SendMessage(deviceHandle, WM_CAP_DRIVER_CONNECT, this.index, 0 comes to be zero and no video is displayed. someone suggested me to changr the value of handle/this.index every time but this also didnot worked out – Swati Mar 25 '11 at 11:39
  • i also could not find how to save this video obtained in mp4 format.Please help – Swati Mar 25 '11 at 11:40
  • Then I try to call DeviceManager.GetAllDevices() it throw "System.EntryPointNotFoundException: "Не удается найти точку входа "CapGetDriverDescriptionA" в DLL "avicap32.dll"."" What I do incorrect? – EgoPingvina Jun 29 '17 at 15:28
  • I got green color in my picture box ! nothing else in windows 7. My camera turns on, but just green color shows. :-( – CodeMan Jun 07 '20 at 06:43
6

I would recommend you to use 3rd party library. It would be the best solution instead of inventing your own bicycle. Here, I used AForge.Net. Though it has some problems concerning performance, but I tweaked the library myself when performance became a critical issue for me. The AForge.Net code is open source and you can tweak it to your needs.

As for books you definitely should look at Jeffrey Richter's "CLR via C#" and John Skeet's "C# in Depth".

Dmitrii Lobanov
  • 4,897
  • 1
  • 33
  • 50
0

You can use Microsoft Expression Encoder 4 SP2. This is a great library that you can add to your project and get live preview, snapshots, and video recording. More details are included a sample project by Massimo Conti: How to use a web cam in C# with .NET Framework 4.0 and Microsoft Expression Encoder 4

Ehsan88
  • 3,569
  • 5
  • 29
  • 52
-1

Use WebCam_Capture.dll for capturing Photos and videos. Here is Link here is source code for that LINK

Bhaskar Singh
  • 410
  • 6
  • 15