日期:2014-05-17  浏览次数:20838 次

一个摄像头使用实例,第四部分(主方法)
//web camera class
  public class WebCamera
  {
  showVideo.BITMAPINFO bitmapinfo = new showVideo.BITMAPINFO();

  // Constructur
  public WebCamera(IntPtr handle, int width, int height)
  {
  mControlPtr = handle;
  mWidth = width;
  mHeight = height;
  bitmapinfo.bmiHeader.biSize = showVideo.SizeOf(bitmapinfo.bmiHeader);
  bitmapinfo.bmiHeader.biWidth = width;
  bitmapinfo.bmiHeader.biHeight = height;
  bitmapinfo.bmiHeader.biPlanes = 1;
  bitmapinfo.bmiHeader.biBitCount = 24;
  }

  // delegate for frame callback
  public delegate void RecievedFrameEventHandler(byte[] data);
  public event RecievedFrameEventHandler RecievedFrame;

  private IntPtr lwndC; // Holds the unmanaged handle of the control
  private IntPtr mControlPtr; // Holds the managed pointer of the control
  private int mWidth;
  private int mHeight;

  private showVideo.FrameEventHandler mFrameEventHandler; // Delegate instance for the frame callback - must keep alive! gc should NOT collect it

  // Close the web camera
  public void CloseWebcam()
  {
  this.capDriverDisconnect(this.lwndC);
  }

  // start the web camera
  public void StartWebCam()
  {
  byte[] lpszName = new byte[100];
  byte[] lpszVer = new byte[100];

  int DriverCount = 0;
  if (showVideo.capGetDriverDescriptionA(0, lpszName, 100, lpszVer, 100) )
  {
  DriverCount++;
  }
  if (DriverCount == 0)
  {
  MessageBox.Show("未发现视频设备");
  return;
  }
  this.lwndC = showVideo.capCreateCaptureWindowA(lpszName, showVideo.WS_VISIBLE + showVideo.WS_CHILD, 0, 0, mWidth, mHeight, mControlPtr, 0);

  if (this.capDriverConnect(this.lwndC, 0))
  {
  this.capPreviewRate(this.lwndC, 66);
  this.capPreview(this.lwndC, true);

  this.capSetVideoFormat(this.lwndC, ref bitmapinfo, showVideo.SizeOf(bitmapinfo));
  this.mFrameEventHandler = new showVideo.FrameEventHandler(FrameCallBack);
  this.capSetCallbackOnFrame(this.lwndC, this.mFrameEventHandler);

  //设置每帧结束后调用的回调函数
  showVideo.SetWindowPos(this.lwndC, 0, 0, 0, mWidth, mHeight, 6);
  }
  else
  {
  // MessageBox.Show("捕获连接卡失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }

  }
  // private functions
  private bool capDriverConnect(IntPtr lwnd, short i)
  {
  return showVideo.SendMessage(lwnd, showVideo.WM_CAP_DRIVER_CONNECT, i, 0);
  }

  private bool capDriverDisconnect(IntPtr lwnd)
  {
  return showVideo.SendMessage(lwnd, showVideo.WM_CAP_DRIVER_DISCONNECT, 0, 0);
  }

  private bool capPreview(IntPtr lwnd, bool f)
  {
&n