Tuesday, January 4, 2011

Accessing the Web Camera from a C# Windows Application.

In this application I will show how we can access the Web Camera on a Computer via a C# application.

To access the Web Camera, or other Video Capture Devices we need to use the avicap32.dll file.



I have developed a class called WebCamera to encapsulate the details of accessing the Camera. The details of the available devices will be displayed in a ListBox from which the user can select a device to use.


Here it is WebCamera.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WebCamProject
{
    class WebCamera
    {
        private const int 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 bool capGetDriverDescriptionA(int wDriverIndex, [MarshalAs(UnmanagedType.VBByRefStr)]ref String ldevicename, int namelength, [MarshalAs(UnmanagedType.VBByRefStr)] ref String deviceversion, int versionlength);
        [DllImport("avicap32.dll")]
        protected static extern int capCreateCaptureWindowA([MarshalAs(UnmanagedType.VBByRefStr)] ref string windowname,
            int style, int x, int y, int width, int height, int parent, int id);

        [DllImport("user32", EntryPoint = "SendMessageA")]
        protected static extern int SendMessage(int hwnd, int window, int x, [MarshalAs(UnmanagedType.AsAny)] object y);

        int deviceHandle;


        public static void LoadAllDevices(ListBox lstDevices)
        {
            String devicename = "".PadRight(100);
            String deviceversion = "".PadRight(100);
            lstDevices.Items.Clear();
            for (int i = 0; i <= 10; i++)
            {
                bool isDeviceReady = capGetDriverDescriptionA(i, ref devicename, 100, ref deviceversion, 100);
                if (!isDeviceReady)
                    continue;
                {
                    WebCamera d = new WebCamera(devicename, deviceversion);


                    lstDevices.Items.Add(d);
                }
            }


        }


        public  System.Drawing.Image GetImage()
        {
            IDataObject data;
            System.Drawing.Image snapshot;

            SendMessage(deviceHandle, WM_CAP_EDIT_COPY, 0, 0);

            data = Clipboard.GetDataObject();
            if (data.GetDataPresent(typeof(System.Drawing.Bitmap)))
            {
                snapshot = (System.Drawing.Image)data.GetData(typeof(System.Drawing.Bitmap));
                return snapshot;
            }
            return null;
        }

        string devicename, deviceversion;

        public WebCamera(string devicename,string deviceversion)
        {
            this.devicename = devicename;
            this.deviceversion = deviceversion;
           
        }

  

        public override string ToString()
        {
            return "Device Name = " + this.devicename + " , Device Version = " + this.deviceversion;
        }
      
        public void StartWebCam(int height, int width, int handle,int deviceno)
        {
            string deviceIndex = "" + deviceno;
            deviceHandle = capCreateCaptureWindowA(ref deviceIndex, WS_VISIBLE | WS_CHILD, 0, 0, width, height, handle, 0);

            if (SendMessage(deviceHandle, WM_CAP_DRIVER_CONNECT, deviceno , 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);
            }
        }
      
             public void DisplayWebCam(PictureBox  pic,int deviceno)
        {
            StartWebCam (pic.Height, pic.Width,(int) pic.Handle,deviceno );
        }

     
        public void StopWebCam(int deviceno)
        {
            SendMessage(deviceHandle, WM_CAP_DRIVER_DISCONNECT, deviceno , 0);
        }
       
    }
}



We have got a windows form Form1 in which there are two pictureboxes. On to display the live Web Camera, and the other to store a snap shot.


Here is Form1.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WebCamProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
             WebCamera.LoadAllDevices(lstDevices);
        }
        WebCamera d;
        private void button1_Click(object sender, EventArgs e)
        {
            if (lstDevices.SelectedIndex < 0)
            {
                MessageBox.Show(this, "Please select a device");
                return;
            }
            d =(WebCamera )lstDevices.SelectedItem;
          
            d.DisplayWebCam (picWebCam,lstDevices .SelectedIndex );
        }

        private void button2_Click(object sender, EventArgs e)
        {
            d.StopWebCam(lstDevices .SelectedIndex );
        }

        private void button3_Click(object sender, EventArgs e)
        {
            picSnap.Image = d.GetImage();
        }
    }
}



Form1.Designer.cs


namespace WebCamProject
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.lstDevices = new System.Windows.Forms.ListBox();
            this.picWebCam = new System.Windows.Forms.PictureBox();
            this.button2 = new System.Windows.Forms.Button();
            this.picSnap = new System.Windows.Forms.PictureBox();
            this.button3 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.picWebCam)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.picSnap)).BeginInit();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(71, 411);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Start";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // lstDevices
            //
            this.lstDevices.FormattingEnabled = true;
            this.lstDevices.Location = new System.Drawing.Point(12, 12);
            this.lstDevices.Name = "lstDevices";
            this.lstDevices.Size = new System.Drawing.Size(505, 173);
            this.lstDevices.TabIndex = 1;
            //
            // picWebCam
            //
            this.picWebCam.Location = new System.Drawing.Point(628, 28);
            this.picWebCam.Name = "picWebCam";
            this.picWebCam.Size = new System.Drawing.Size(359, 226);
            this.picWebCam.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picWebCam.TabIndex = 2;
            this.picWebCam.TabStop = false;
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(513, 411);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 3;
            this.button2.Text = "Stop";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // picSnap
            //
            this.picSnap.Location = new System.Drawing.Point(628, 272);
            this.picSnap.Name = "picSnap";
            this.picSnap.Size = new System.Drawing.Size(359, 226);
            this.picSnap.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picSnap.TabIndex = 2;
            this.picSnap.TabStop = false;
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(234, 410);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(135, 23);
            this.button3.TabIndex = 4;
            this.button3.Text = "Take Picture";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1202, 522);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.picSnap);
            this.Controls.Add(this.picWebCam);
            this.Controls.Add(this.lstDevices);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.picWebCam)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.picSnap)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.ListBox lstDevices;
        private System.Windows.Forms.PictureBox picWebCam;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.PictureBox picSnap;
        private System.Windows.Forms.Button button3;
    }
}



Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WebCamProject
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}



If somebody wants the complete program, give me your mail id.

In a future POST we shall do a complete Video/Audio capture.

31 comments:

  1. sir its great how we can use it or impliment it

    ReplyDelete
  2. sir please get me the complete program i want to use it in one of my project my mail id is kantsurya99@gmail.com plz sir it will be very beneficial for me .

    ReplyDelete
  3. sir please get me the complete program.

    chan85samar@gmail.com

    ReplyDelete
  4. Very Nice Article.Thank you Very Much.
    Sir,I need this complete program.
    Please Email me at :ugalekiran88@gmail.com

    Thank you.

    ReplyDelete
  5. sir please get me the complete program.

    ma020203@stust.edu.tw

    Thank you.

    ReplyDelete
  6. Sir could you please send me the complete program
    john0ya@gmail.com

    Thankyou

    ReplyDelete
  7. Sir this article is really helpful.but i want the entire code please help me out.my emailid is:

    sanjeevnighwan@gmail.com

    ReplyDelete
  8. very interesting code , Could you please send me program at email id : ganeshkkhairnar@gmail.com

    ReplyDelete
  9. hi sir can u please mail me at
    sudhakar@gmail.com

    ReplyDelete
  10. very good article and nicely put through... Thanks for your sharing....

    ReplyDelete
  11. please send me complete code at wajihazafar82@gmail.com

    ReplyDelete
  12. Please send me the complete code
    My id is debajit.g03@gmail.com

    ReplyDelete
  13. Please send me the complete code
    My id is priyank.patel00762@gmail.com

    ReplyDelete
  14. Please send me at kamranniazi1982@gmail.com

    ReplyDelete
  15. Can you please Please send me the complete code.
    sachinchabra01@gmail.com

    ReplyDelete
  16. Sir Pls Send The Project To Karthick.pml@gmail.com Pls help me to complete my project

    ReplyDelete
  17. sir please get me the complete program
    i want to use it in one of my project
    my mail id is itazo0729@gmail.com
    thank you ~

    ReplyDelete
  18. Sir please send me the complete code, my id is adhikaripushkar015@yahoo.com

    ReplyDelete
  19. sandipkordiya@gmail.com plz sir send me this code

    ReplyDelete
  20. alif.mmu@gmail.com plz sir send me this code

    ReplyDelete
  21. It works fine, thanks!

    ReplyDelete
  22. please send this code to my mail id ganeshrameshg@gmail.com

    ReplyDelete
  23. kindly sir send me on my id mmkamran@yahoo.com

    ReplyDelete
  24. can you send this code please?

    ahmetselimkahraman@msn.com

    thank you.

    ReplyDelete
  25. Hello sir,
    can you guide me how we can use web cam in web application without using flash player please guide me, my email id is avistar89@gmail.com

    ReplyDelete
  26. Sir old give me complete program.

    ReplyDelete
  27. can u pls provide me the solution ? polattt@gmail.com

    ReplyDelete