1、新建一個Windows窗體應用程序,在Form1窗體上添加一個PictureBox控件、一個ComboBox控件,命名爲PictureBox一、cbCapture,還有兩個Button控件,Text分別爲切換和攝像頭屬性,Name分別爲btnStart和btnConfig,其界面以下:ide
2、在該項目下的「引用」處右擊選擇「添加引用」,添加 AForge.Video.dll 和 AForge.Video.DirectShow.dll 兩個程序集this
3、雙擊兩個Button按鈕以及觸發窗體的Load和Closing事件,代碼以下:spa
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using AForge.Video.DirectShow; 10 using AForge.Video; 11 using System.Diagnostics; 12 13 namespace Aforge調用攝像頭 14 { 15 public partial class Form1 : Form 16 { 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void Form1_Load(object sender, EventArgs e) 23 { 24 try 25 { 26 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);//枚舉全部的視頻輸入設備 27 if (videoDevices.Count == 0) 28 throw new ApplicationException(); 29 foreach (FilterInfo device in videoDevices) 30 { 31 cbCapture.Items.Add(device.Name);//把全部的視頻設備添加到下拉框中 32 } 33 cbCapture.SelectedIndex = 0; 34 videoSource = new VideoCaptureDevice(videoDevices[cbCapture.SelectedIndex].MonikerString);//攝像頭的名稱 35 videoSource.DesiredFrameSize = new Size(500, 300);//設置大小 36 videoSource.DesiredFrameRate = 1;//設置幀率 37 videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame); 38 videoSource.Start(); 39 } 40 catch (Exception ex) 41 { 42 MessageBox.Show(ex.Message); 43 } 44 } 45 private FilterInfoCollection videoDevices; 46 private VideoCaptureDevice videoSource; 47 private void btnStart_Click(object sender, EventArgs e) 48 { 49 videoSource.Stop(); 50 videoSource = new VideoCaptureDevice(videoDevices[cbCapture.SelectedIndex].MonikerString);//攝像頭的名稱 51 videoSource.DesiredFrameSize = new Size(500, 300);//設置大小 52 videoSource.DesiredFrameRate = 1;//設置幀率 53 videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame); 54 videoSource.Start(); 55 } 56 private void video_NewFrame(object sender, NewFrameEventArgs eventArgs) 57 { 58 Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone(); 59 pictureBox1.Image = bitmap; 60 } 61 62 private void btnConfig_Click(object sender, EventArgs e) 63 { 64 if ((videoSource != null) && (videoSource is VideoCaptureDevice)) 65 { 66 try 67 { 68 ((VideoCaptureDevice)videoSource).DisplayPropertyPage(this.Handle); 69 } 70 catch (NotSupportedException ex) 71 { 72 MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 73 } 74 } 75 } 76 77 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 78 { 79 Process p = Process.GetCurrentProcess(); 80 if (p.HasExited == false) 81 { 82 p.Kill(); 83 } 84 } 85 } 86 }
注意:若是在關閉窗體是不把這個進程給結束掉,那麼下次再次調用的時候就會出現程序正在運行中的錯誤或者在窗體加載時不能調用處攝像頭;此外,攝像頭必須是無驅的code
4、效果圖orm