C# AForge 关闭摄像头

来源:互联网 发布:n9软件网 编辑:程序博客网 时间:2024/06/06 05:01

问题描述见下面图

用AForge 写程序,在做界面时发现打开程序后打开界面能连接摄像头,然后关闭再打开就一直连接状态,是因为关闭时没有关闭摄像头,只关闭了界面。


 VideoCaptureDevice videoSource;

只需在关闭时加入 videoSource.Stop();即可解决该问题

  private void FrmGetPic_FormClosing(object sender, EventArgs e)
        {
            if (videoDevices == null || videoDevices.Count == 0)
            {
                return;
            }
            videoSource.Stop();

        }

第一次打开


第二次打开


类中定义:

FilterInfoCollection videoDevices;
        VideoCaptureDevice videoSource;

 private void FrmGetPic_Load(object sender, EventArgs e)
        {

  try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                //  MessageBox.Show(videoDevices.Count.ToString());
                if (videoDevices.Count == 0)
                    throw new ApplicationException();


                foreach (FilterInfo device in videoDevices)
                {
                    this.cb_SPDriver.Items.Add(device.Name);
                }


                cb_SPDriver.SelectedIndex = 0;
               // CameraConn();
              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.cb_SPDriver.Items.Add("未找到驱动设备");
                videoDevices = null;
            }

}


    private void CameraConn()
        {
            //VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
            //videoSource.DesiredFrameSize = new Size(320, 240);
            //videoSource.DesiredFrameRate = 1;

            //videPlayer.VideoSource = videoSource;
            //videPlayer.Start();
            if (videoDevices == null || videoDevices.Count == 0) return;


            videoSourcePlayer1.SignalToStop();
            videoSourcePlayer1.WaitForStop();


            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            selectedDeviceIndex = cb_SPDriver.SelectedIndex;
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);//连接摄像头。
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            videoSourcePlayer1.VideoSource = videoSource;
            // set NewFrame event handler
            videoSourcePlayer1.Start();


        }