在C#中正确处理网络摄像头

时间:2012-05-01 12:54:38

标签: c# winapi webcam

我在C#中看到过很多用于Webcam的库。但是有两个普遍的问题:

  1. 他们使用剪贴板,这也消除了用户使用剪贴板的能力。
  2. 无法检测网络摄像头是否已连接,但“拍摄测试照片”除外,因为网络摄像头会闪烁,这会刺激用户。
  3. 有没有办法解决这两个问题中的任何一个?

    到目前为止,这是我的班级:

    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);
        }
    }
    

1 个答案:

答案 0 :(得分:2)

VfW capture API非常有限,但允许您enumerate devicesconnect to specific onescapture the data into a memory buffer

然而,它已经很老了,并且在10年前被WDM和DirectShow淘汰了,也可以在C#中使用。

我手边没有代码,但您创建了一个过滤器图表,添加了网络摄像头设备并告诉它渲染图钉。