1 c# 获取 摄像头 实现录像  
  2 
  3       利用普通的简易摄像头,通过C#语言即可开发成简易视频程序。本实例利用市场上购买的普通摄像头,利用VFW技术,实现单路视频监控系统。运行程序,窗体中将显示舰体摄像头采集的视频信息。如图13.9所示。
  4  技术要点
  5  本实例主要使用了VFW(Video for Windows)技术。VFW 是Microsoft公司为开发Windows平台下的视频应用程序提供的软件工具包,提供了一系列应用程序编程接口(API),用户可以通过这些接口很方便地实现视频捕获、视频编辑及视频播放等通用功能,还可利用回调函数开发比较复杂的视频应用程序。该技术的特点是播放视频时不需要专用的硬件设备,而且应用灵活,可以满足视频应用程序开发的需要。Windows操作系统自身就携带了VFW技术,系统安装时,会自动安装VFW的相关组件。
  6 VFW技术主要由六个功能模块组成,下面进行简单说明。
  7      AVICAP32.DLL:包含执行视频捕获的函数,给AVI文件的I/O处理和视频,音频设备驱动程序提供一个高级接口。
  8      MSVIDEO.DLL:包含一套特殊的DrawDib函数,用来处理程序上的视频操作。
  9     MCIAVI.DRV:包括对VFW的MCI命令解释器的驱动程序。
 10     AVIFILE.DLL:包含由标准多媒体I/O(mmio)函数提供的更高级的命令,用来访问.AVI文件。
 11     ICM:压缩管理器,用于管理的视频压缩/解压缩的编译码器。
 12     ACM:音频压缩管理器,提供与ICM相似的服务,适用于波形音频。
 13 AVICAP32.DLL中的函数和USER32.DLL中的函数,函数语法及结构如下。
 141)capCreateCaptureWindow函数
 15  该函数用于创建一个视频捕捉窗口。语法如下:
 16         [DllImport("avicap32.dll")]
 17          public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
 18 参数说明如下。
 19      lpszWindowName:标识窗口的名称。
 20      dwStyle:标识窗口风格。
 21      x、y:标识窗口的左上角坐标。
 22      nWidth、nHeight:标识窗口的宽度和高度。
 23      hWnd:标识父窗口句柄。
 24      nID:标识窗口ID。
 25      返回值:视频捕捉窗口句柄。
 262)SendMessage函数
 27  用于向Windows系统发送消息机制。
 28 [DllImport("User32.dll")]
 29  private static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
 30 参数说明如下。
 31      hWnd:窗口句柄。
 32      wMsg:将要发送的消息。
 33      wParam、lParam:消息的参数,每个消息都有两个参数,参数设置由发送的消息而定。
 34 
 35  
 36 
 37 Form1窗体中通过调用视频类中的方法来实现相应的功能。
 38 
 39 在【开始录像】按钮的Click事件中添加如下代码:
 40 
 41         private void buttonStart_Click(object sender, EventArgs e)
 42          {
 43              buttonStart.Enabled = false;
 44              buttonStop.Enabled = true;
 45              //btnPz.Enabled = true;
 46              video = new cVideo(picCapture.Handle, picCapture.Width, picCapture.Height);
 47              video.StartWebCam();
 48          }
 49 
 50 在【停止录像】按钮的Click事件中添加如下代码:
 51 
 52         private void buttonStop_Click(object sender, EventArgs e)
 53          {
 54              buttonStart.Enabled = true;
 55              buttonStop.Enabled = false;
 56              buttonPz.Enabled = false;
 57              video.CloseWebcam();
 58          }
 59 
 60 
 61 在【拍照】按钮的Click事件下添加如下代码:
 62 
 63         private void buttonPz_Click(object sender, EventArgs e)
 64          {
 65              video.GrabImage(picCapture.Handle, "d:\\a.bmp");
 66          }
 67 
 68  
 69 
 70 完整代码如下:
 71 
 72 1、Program.cs
 73 
 74  
 75 
 76 using System;
 77  using System.Collections.Generic;
 78  using System.Linq;
 79  using System.Windows.Forms;
 80 
 81 namespace Video1
 82  {
 83      static class Program
 84      {
 85          /// <summary>
 86          /// 应用程序的主入口点。
 87         /// </summary>
 88          [STAThread]
 89          static void Main()
 90          {
 91              Application.EnableVisualStyles();
 92              Application.SetCompatibleTextRenderingDefault(false);
 93              Application.Run(new Form1());
 94          }
 95      }
 96  }
 97 
 98  
 99 
100 2、Form1.cs
101 
102  
103 
104 using System;
105  using System.Collections.Generic;
106  using System.ComponentModel;
107  using System.Data;
108  using System.Drawing;
109  using System.Linq;
110  using System.Text;
111  using System.Windows.Forms;
112 
113 namespace Video1
114  {
115      public partial class Form1 : Form
116      {
117          cVideo video;
118          public Form1()
119          {
120              InitializeComponent();
121          }
122 
123         private void buttonStart_Click(object sender, EventArgs e)
124          {
125              buttonStart.Enabled = false;
126              buttonStop.Enabled = true;
127              //btnPz.Enabled = true;
128              video = new cVideo(picCapture.Handle, picCapture.Width, picCapture.Height);
129              video.StartWebCam();
130          }
131 
132         private void buttonStop_Click(object sender, EventArgs e)
133          {
134              buttonStart.Enabled = true;
135              buttonStop.Enabled = false;
136              buttonPz.Enabled = false;
137              video.CloseWebcam();
138          }
139 
140         private void buttonPz_Click(object sender, EventArgs e)
141          {
142              video.GrabImage(picCapture.Handle, "d:\\a.bmp");
143          }
144      }
145  }
146 
147 
148 3、Form1.Designer.cs
149 
150  
151 
152 namespace Video1
153  {
154      partial class Form1
155      {
156          /// <summary>
157          /// 必需的设计器变量。
158         /// </summary>
159          private System.ComponentModel.IContainer components = null;
160 
161         /// <summary>
162          /// 清理所有正在使用的资源。
163         /// </summary>
164          /// <param>如果应释放托管资源,为 true;否则为 false。</param>
165          protected override void Dispose(bool disposing)
166          {
167              if (disposing && (components != null))
168              {
169                  components.Dispose();
170              }
171              base.Dispose(disposing);
172          }
173 
174         #region Windows 窗体设计器生成的代码
175 
176         /// <summary>
177          /// 设计器支持所需的方法 - 不要
178         /// 使用代码编辑器修改此方法的内容。
179         /// </summary>
180          private void InitializeComponent()
181          {
182              System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
183              this.buttonStart = new System.Windows.Forms.Button();
184              this.buttonStop = new System.Windows.Forms.Button();
185              this.buttonPz = new System.Windows.Forms.Button();
186              this.panelTop = new System.Windows.Forms.Panel();
187              this.picCapture = new System.Windows.Forms.PictureBox();
188              this.panelBottom = new System.Windows.Forms.Panel();
189              this.panelTop.SuspendLayout();
190              ((System.ComponentModel.ISupportInitialize)(this.picCapture)).BeginInit();
191              this.panelBottom.SuspendLayout();
192              this.SuspendLayout();
193              // 
194              // buttonStart
195              // 
196              this.buttonStart.Location = new System.Drawing.Point(39, 3);
197              this.buttonStart.Name = "buttonStart";
198              this.buttonStart.Size = new System.Drawing.Size(88, 36);
199              this.buttonStart.TabIndex = 1;
200              this.buttonStart.Text = "开始录像";
201              this.buttonStart.UseVisualStyleBackColor = true;
202              this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
203              // 
204              // buttonStop
205              // 
206              this.buttonStop.Location = new System.Drawing.Point(181, 3);
207              this.buttonStop.Name = "buttonStop";
208              this.buttonStop.Size = new System.Drawing.Size(80, 36);
209              this.buttonStop.TabIndex = 2;
210              this.buttonStop.Text = "停止录像";
211              this.buttonStop.UseVisualStyleBackColor = true;
212              this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
213              // 
214              // buttonPz
215              // 
216              this.buttonPz.Location = new System.Drawing.Point(313, 3);
217              this.buttonPz.Name = "buttonPz";
218              this.buttonPz.Size = new System.Drawing.Size(77, 36);
219              this.buttonPz.TabIndex = 3;
220              this.buttonPz.Text = "拍  照";
221              this.buttonPz.UseVisualStyleBackColor = true;
222              this.buttonPz.Click += new System.EventHandler(this.buttonPz_Click);
223              // 
224              // panelTop
225              // 
226              this.panelTop.AutoSize = true;
227              this.panelTop.Controls.Add(this.picCapture);
228              this.panelTop.Dock = System.Windows.Forms.DockStyle.Fill;
229              this.panelTop.Location = new System.Drawing.Point(0, 0);
230              this.panelTop.Name = "panelTop";
231              this.panelTop.Size = new System.Drawing.Size(468, 372);
232              this.panelTop.TabIndex = 4;
233              // 
234              // picCapture
235              // 
236              this.picCapture.Dock = System.Windows.Forms.DockStyle.Fill;
237              this.picCapture.InitialImage = ((System.Drawing.Image)(resources.GetObject("picCapture.InitialImage")));
238              this.picCapture.Location = new System.Drawing.Point(0, 0);
239              this.picCapture.Name = "picCapture";
240              this.picCapture.Size = new System.Drawing.Size(468, 372);
241              this.picCapture.TabIndex = 0;
242              this.picCapture.TabStop = false;
243              // 
244              // panelBottom
245              // 
246              this.panelBottom.Controls.Add(this.buttonStart);
247              this.panelBottom.Controls.Add(this.buttonStop);
248              this.panelBottom.Controls.Add(this.buttonPz);
249              this.panelBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
250              this.panelBottom.Location = new System.Drawing.Point(0, 327);
251              this.panelBottom.Name = "panelBottom";
252              this.panelBottom.Size = new System.Drawing.Size(468, 45);
253              this.panelBottom.TabIndex = 5;
254              // 
255              // Form1
256              // 
257              this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
258              this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
259              this.ClientSize = new System.Drawing.Size(468, 372);
260              this.Controls.Add(this.panelBottom);
261              this.Controls.Add(this.panelTop);
262              this.Name = "Form1";
263              this.Text = "Form1";
264              this.panelTop.ResumeLayout(false);
265              ((System.ComponentModel.ISupportInitialize)(this.picCapture)).EndInit();
266              this.panelBottom.ResumeLayout(false);
267              this.ResumeLayout(false);
268              this.PerformLayout();
269 
270         }
271 
272         #endregion
273 
274         private System.Windows.Forms.PictureBox picCapture;
275          private System.Windows.Forms.Button buttonStart;
276          private System.Windows.Forms.Button buttonStop;
277          private System.Windows.Forms.Button buttonPz;
278          private System.Windows.Forms.Panel panelTop;
279          private System.Windows.Forms.Panel panelBottom;
280      }
281  }
282 
283 4、ClassVideoAPI.cs
284 
285  using System;
286  using System.Collections.Generic;
287  using System.Linq;
288  using System.Text;
289  using System.Drawing;
290  using System.Runtime.InteropServices;
291  using System.Threading;
292  using System.Windows.Forms;
293  using System.IO;
294 
295 namespace Video1
296  {
297      public class VideoAPI  //视频API类
298     {
299          //  视频API调用
300         [DllImport("avicap32.dll")]//包含了执行视频捕获的函数,它给AVI文件I/O和视频、音频设备驱动程序提供一个高级接口
301         public static extern IntPtr capCreateCaptureWindow(string lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hwndParent, int nID);
302          [DllImport("AVICAP32.dll", CharSet = CharSet.Unicode)]
303          public static extern bool capGetDriverDescription(int wDriverIndex, StringBuilder lpszName, int cbName, StringBuilder lpszVer, int cbVer);
304          [DllImport("avicap32.dll")]
305          public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
306          [DllImport("avicap32.dll")]
307          public static extern bool capGetDriverDescriptionA(short wDriver, byte[] lpszName, int cbName, byte[] lpszVer, int cbVer);
308          [DllImport("User32.dll")]
309          public static extern bool SendMessage(IntPtr hWnd, int wMsg, bool wParam, int lParam);
310          [DllImport("User32.dll")]
311          public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, int lParam);
312          [DllImport("User32.dll")]
313          public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);
314          [DllImport("User32.dll")]
315          public static extern bool SendMessage(IntPtr hWnd, int wMsg, short wParam, FrameEventHandler lParam);
316          [DllImport("User32.dll")]
317          public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref BITMAPINFO lParam);
318          [DllImport("User32.dll")]
319          public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref CAPDRIVERCAPS lParam);
320          [DllImport("User32.dll")]
321          public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref CAPTUREPARMS lParam);
322          [DllImport("User32.dll")]
323          public static extern bool SendMessage(IntPtr hWnd, int wMsg, int wParam, ref CAPSTATUS lParam);
324          [DllImport("User32.dll")]
325          public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
326          [DllImport("avicap32.dll")]
327          public static extern int capGetVideoFormat(IntPtr hWnd, IntPtr psVideoFormat, int wSize);
328 
329         //  常量
330         // public const int WM_USER = 0x400;
331          public const int WS_CHILD = 0x40000000;
332          public const int WS_VISIBLE = 0x10000000;
333 
334         public const int SWP_NOMOVE = 0x2;
335          public const int SWP_NOZORDER = 0x4;
336          // public const int WM_CAP_DRIVER_CONNECT = WM_USER + 10;
337          //   public const int WM_CAP_DRIVER_DISCONNECT = WM_USER + 11;
338          public const int WM_CAP_SET_CALLBACK_FRAME = WM_USER + 5;
339          //   public const int WM_CAP_SET_PREVIEW = WM_USER + 50;
340          //  public const int WM_CAP_SET_PREVIEWRATE = WM_USER + 52;
341          //  public const int WM_CAP_SET_VIDEOFORMAT = WM_USER + 45;
342          //   public const int WM_CAP_START = WM_USER;
343          public const int WM_CAP_SAVEDIB = WM_CAP_START + 25;
344 
345         public const string avicap32 = "avicap32.dll";
346          public const int WM_USER = 1024;
347          /// <summary>
348          ///WM_CAP_START=WM_USER=1024
349          /// </summary>
350          public const int WM_CAP_START = WM_USER;
351 
352         // start of unicode messages
353          /// <summary>
354          /// 开始   WM_USER + 100=1124
355          /// </summary>
356          public const int WM_CAP_UNICODE_START = WM_USER + 100; //开始   1124
357          /// <summary>
358          /// /获得 CAPSTR EAMPTR   
359          /// WM_CAP_START + 1=1025
360          /// </summary>
361          public const int WM_CAP_GET_CAPSTREAMPTR = (WM_CAP_START + 1); //获得 CAPSTR EAMPTR
362          /// <summary>
363          /// 设置收回错误   WM_CAP_START + 2=1026
364          /// </summary>
365          public const int WM_CAP_SET_CALLBACK_ERROR = (WM_CAP_START + 2); //设置收回错误
366         /// <summary>
367          /// 设置收回状态 WM_CAP_START + 3=1027
368          /// </summary>
369          public const int WM_CAP_SET_CALLBACK_STATUS = (WM_CAP_START + 3); //设置收回状态
370         /// <summary>
371          /// 设置收回出产  WM_CAP_START + 4=1028
372          /// </summary>
373          public const int WM_CAP_SET_CALLBACK_YIELD = (WM_CAP_START + 4); //设置收回出产
374         /// <summary>
375          /// 设置收回结构  WM_CAP_START + 5=1029
376          /// </summary>
377          public const int WM_CAP_SET_CALLBACK_FRame = (WM_CAP_START + 5); //设置收回结构
378         /// <summary>
379          /// 设置收回视频流  WM_CAP_START + 6=1030
380          /// </summary>
381          public const int WM_CAP_SET_CALLBACK_VIDEOSTREAM = (WM_CAP_START + 6); //设置收回视频流
382         /// <summary>
383          /// 设置收回视频波流  WM_CAP_START +7=1031
384          /// </summary>
385          public const int WM_CAP_SET_CALLBACK_WAVESTREAM = (WM_CAP_START + 7); //设置收回视频波流
386         /// <summary>
387          /// 获得使用者数据 WM_CAP_START + 8=1032
388          /// </summary>
389          public const int WM_CAP_GET_USER_DATA = (WM_CAP_START + 8); //获得使用者数据
390         /// <summary>
391          /// 设置使用者数据 WM_CAP_START + 9=1033
392          /// </summary>
393          public const int WM_CAP_SET_USER_DATA = (WM_CAP_START + 9); //设置使用者数据
394         /// <summary>
395          /// 驱动程序连接  WM_CAP_START + 10=1034
396          /// </summary>
397          public const int WM_CAP_DRIVER_CONNECT = (WM_CAP_START + 10); //驱动程序连接
398         /// <summary>
399          /// 断开启动程序连接 WM_CAP_START + 11=1035
400          /// </summary>
401          public const int WM_CAP_DRIVER_DISCONNECT = (WM_CAP_START + 11); //断开启动程序连接
402         /// <summary>
403          /// 获得驱动程序名字 WM_CAP_START + 12=1036
404          /// </summary>
405          public const int WM_CAP_DRIVER_GET_NAME = (WM_CAP_START + 12); //获得驱动程序名字
406         /// <summary>
407          /// 获得驱动程序版本 WM_CAP_START + 13=1037
408          /// </summary>
409          public const int WM_CAP_DRIVER_GET_VERSION = (WM_CAP_START + 13); //获得驱动程序版本
410         /// <summary>
411          /// 获得驱动程序帽子 WM_CAP_START + 14=1038
412          /// </summary>
413          public const int WM_CAP_DRIVER_GET_CAPS = (WM_CAP_START + 14); //获得驱动程序帽子
414         /// <summary>
415          /// 设置捕获文件 WM_CAP_START + 20=1044
416          /// </summary>
417          public const int WM_CAP_FILE_SET_CAPTURE_FILE = (WM_CAP_START + 20); //设置捕获文件
418         /// <summary>
419          /// 获得捕获文件 WM_CAP_START + 21=1045
420          /// </summary>
421          public const int WM_CAP_FILE_GET_CAPTURE_FILE = (WM_CAP_START + 21); //获得捕获文件
422         /// <summary>
423          /// 另存文件为  WM_CAP_START + 23=1047
424          /// </summary>
425          public const int WM_CAP_FILE_SAVEAS = (WM_CAP_START + 23); //另存文件为
426         /// <summary>
427          /// 保存文件    WM_CAP_START + 25=1049
428          /// </summary>
429          public const int WM_CAP_FILE_SAVEDIB = (WM_CAP_START + 25); //保存文件
430 
431         // out of order to save on ifdefs
432          /// <summary>
433          /// 分派文件  WM_CAP_START + 22=1044
434          /// </summary>
435          public const int WM_CAP_FILE_ALLOCATE = (WM_CAP_START + 22); //分派文件
436         /// <summary>
437          /// 设置开始文件  WM_CAP_START + 24=1046
438          /// </summary>
439          public const int WM_CAP_FILE_SET_INFOCHUNK = (WM_CAP_START + 24); //设置开始文件
440         /// <summary>
441          /// 编辑复制   WM_CAP_START + 30=1054
442          /// </summary>
443          public const int WM_CAP_EDIT_COPY = (WM_CAP_START + 30); //编辑复制
444         /// <summary>
445          /// 设置音频格式  WM_CAP_START + 35=1059
446          /// </summary>
447          public const int WM_CAP_SET_AUDIOFORMAT = (WM_CAP_START + 35); //设置音频格式
448         /// <summary>
449          /// 捕获音频格式  WM_CAP_START + 36=1060
450          /// </summary>
451          public const int WM_CAP_GET_AUDIOFORMAT = (WM_CAP_START + 36); //捕获音频格式
452         /// <summary>
453          /// 打开视频格式设置对话框  WM_CAP_START + 41=1065
454          /// </summary>
455          public const int WM_CAP_DLG_VIDEOFORMAT = (WM_CAP_START + 41); //1065 打开视频格式设置对话框
456         /// <summary>
457          /// 打开属性设置对话框,设置对比度、亮度等   WM_CAP_START + 42=1066
458          /// </summary>
459          public const int WM_CAP_DLG_VIDEOSOURCE = (WM_CAP_START + 42); //1066 打开属性设置对话框,设置对比度、亮度等。
460         /// <summary>
461          /// 打开视频显示 WM_CAP_START + 43=1067
462          /// </summary>
463          public const int WM_CAP_DLG_VIDEODISPLAY = (WM_CAP_START + 43); //1067 打开视频显示
464         /// <summary>
465          /// 获得视频格式 WM_CAP_START + 44=1068
466          /// </summary>
467          public const int WM_CAP_GET_VIDEOFORMAT = (WM_CAP_START + 44); //1068 获得视频格式
468         /// <summary>
469          /// 设置视频格式 WM_CAP_START + 45=1069
470          /// </summary>
471          public const int WM_CAP_SET_VIDEOFORMAT = (WM_CAP_START + 45); //1069 设置视频格式
472         /// <summary>
473          /// 打开压缩设置对话框 WM_CAP_START + 46=1070
474          /// </summary>
475          public const int WM_CAP_DLG_VIDEOCOMPRESSION = (WM_CAP_START + 46); //1070 打开压缩设置对话框
476         /// <summary>
477          /// 设置预览 WM_CAP_START + 50=1074
478          /// </summary>
479          public const int WM_CAP_SET_PREVIEW = (WM_CAP_START + 50); //设置预览
480         /// <summary>
481          /// 设置覆盖 WM_CAP_START + 51=1075
482          /// </summary>
483          public const int WM_CAP_SET_OVERLAY = (WM_CAP_START + 51); //设置覆盖
484         /// <summary>
485          /// 设置预览比例 WM_CAP_START + 52=1076
486          /// </summary>
487          public const int WM_CAP_SET_PREVIEWRATE = (WM_CAP_START + 52); //设置预览比例
488         /// <summary>
489          /// 设置刻度 WM_CAP_START + 53=1077
490          /// </summary>
491          public const int WM_CAP_SET_SCALE = (WM_CAP_START + 53); //设置刻度
492         /// <summary> 
493          /// 获得状态 WM_CAP_START + 54=1078
494          /// </summary>
495          public const int WM_CAP_GET_STATUS = (WM_CAP_START + 54); //获得状态
496         /// <summary>
497          /// 设置卷 WM_CAP_START + 55=1079
498          /// </summary>
499          public const int WM_CAP_SET_SCROLL = (WM_CAP_START + 55); //设置卷
500         /// <summary>
501          /// 逮捕结构 WM_CAP_START + 60=1084
502          /// </summary>
503          public const int WM_CAP_GRAB_FRame = (WM_CAP_START + 60); //逮捕结构
504         /// <summary>
505          /// 停止逮捕结构 WM_CAP_START + 61=1085
506          /// </summary>
507          public const int WM_CAP_GRAB_FRame_NOSTOP = (WM_CAP_START + 61); //停止逮捕结构
508         /// <summary>
509          /// 次序 WM_CAP_START + 62=1086
510          /// </summary>
511          public const int WM_CAP_SEQUENCE = (WM_CAP_START + 62); //次序
512         /// <summary>
513          /// 没有文件 WM_CAP_START + 63=1087
514          /// </summary>
515          public const int WM_CAP_SEQUENCE_NOFILE = (WM_CAP_START + 63); //没有文件
516         /// <summary>
517          /// 设置安装次序 WM_CAP_START + 64=1088
518          /// </summary>
519          public const int WM_CAP_SET_SEQUENCE_SETUP = (WM_CAP_START + 64); //设置安装次序
520         /// <summary>
521          /// 获得安装次序 WM_CAP_START + 65=1089
522          /// </summary>
523          public const int WM_CAP_GET_SEQUENCE_SETUP = (WM_CAP_START + 65); //获得安装次序
524         /// <summary>
525          /// 设置媒体控制接口 WM_CAP_START + 66=1090
526          /// </summary>
527          public const int WM_CAP_SET_MCI_DEVICE = (WM_CAP_START + 66); //设置媒体控制接口
528         /// <summary>
529          /// 获得媒体控制接口 WM_CAP_START + 67=1091
530          /// </summary>
531          public const int WM_CAP_GET_MCI_DEVICE = (WM_CAP_START + 67); //获得媒体控制接口 
532         /// <summary>
533          /// 停止 WM_CAP_START + 68=1092
534          /// </summary>
535          public const int WM_CAP_STOP = (WM_CAP_START + 68); //停止
536         /// <summary>
537          /// 异常中断 WM_CAP_START + 69=1093
538          /// </summary>
539          public const int WM_CAP_ABORT = (WM_CAP_START + 69); //异常中断
540         /// <summary>
541          /// 打开单一的结构 WM_CAP_START + 68=1094
542          /// </summary>
543          public const int WM_CAP_SINGLE_FRame_OPEN = (WM_CAP_START + 70); //打开单一的结构
544         /// <summary>
545          /// 关闭单一的结构 WM_CAP_START + 71=1095
546          /// </summary>
547          public const int WM_CAP_SINGLE_FRame_CLOSE = (WM_CAP_START + 71); //关闭单一的结构
548         /// <summary>
549          /// 单一的结构 WM_CAP_START + 72=1096
550          /// </summary>
551          public const int WM_CAP_SINGLE_FRame = (WM_CAP_START + 72); //单一的结构
552         /// <summary>
553          /// 打开视频 WM_CAP_START + 80=1104
554          /// </summary>
555          public const int WM_CAP_PAL_OPEN = (WM_CAP_START + 80); //打开视频
556         /// <summary>
557          /// 保存视频 WM_CAP_START + 81=1105
558          /// </summary>
559          public const int WM_CAP_PAL_SAVE = (WM_CAP_START + 81); //保存视频
560         /// <summary>
561          /// 粘贴视频 WM_CAP_START + 82=1106
562          /// </summary>
563          public const int WM_CAP_PAL_PASTE = (WM_CAP_START + 82); //粘贴视频
564         /// <summary>
565          /// 自动创造 WM_CAP_START + 83=1107
566          /// </summary>
567          public const int WM_CAP_PAL_AUTOCREATE = (WM_CAP_START + 83); //自动创造
568         /// <summary>
569          /// 手动创造 WM_CAP_START + 84=1108
570          /// </summary>
571          public const int WM_CAP_PAL_MANUALCREATE = (WM_CAP_START + 84); //手动创造
572 
573         // Following added post VFW 1.1
574          /// <summary>
575          /// 设置收回的错误 WM_CAP_START + 85=1109
576          /// </summary>
577          public const int WM_CAP_SET_CALLBACK_CAPCONTROL = (WM_CAP_START + 85); // 设置收回的错误
578 
579         public const int WM_CAP_END = WM_CAP_SET_CALLBACK_CAPCONTROL;
580 
581         public delegate void FrameEventHandler(IntPtr lwnd, IntPtr lpVHdr);
582 
583         #region 公共函数
584         //公共函数
585         public static object GetStructure(IntPtr ptr, ValueType structure)
586          {
587              return Marshal.PtrToStructure(ptr, structure.GetType());
588          }
589 
590         public static object GetStructure(int ptr, ValueType structure)
591          {
592              return GetStructure(new IntPtr(ptr), structure);
593          }
594 
595         public static void Copy(IntPtr ptr, byte[] data)
596          {
597              Marshal.Copy(ptr, data, 0, data.Length);
598          }
599 
600         public static void Copy(int ptr, byte[] data)
601          {
602              Copy(new IntPtr(ptr), data);
603          }
604 
605         public static int SizeOf(object structure)
606          {
607              return Marshal.SizeOf(structure);
608          }
609          #endregion 公共函数
610         #region 结构 VIDEOHDR|BITMAPINFOHEADER|BITMAPINFO|CAPTUREPARMS|CAPDRIVERCAPS|CAPSTATUS
611          //========================================================VideoHdr 结构=====================================================================
612          //VideoHdr 结构   定义了视频数据块的头信息,在编写回调函数时常用到其数据成员lpData(指向数据缓存的指针)和dwBufferLength(数据缓存的大小)。     
613          //视频帧到缓存的捕获则需要应用回调函数和相应的数据块结构 VIDEOHDR 
614          [StructLayout(LayoutKind.Sequential)]
615          public struct VIDEOHDR
616          {
617              public IntPtr lpData;              /* 指向数据缓存的指针 */
618              public int dwBufferLength;         /* 数据缓存的大小 */
619              public int dwBytesUsed;            /* Bytes actually used */
620              public int dwTimeCaptured;         /* Milliseconds from start of stream */
621              public int dwUser;                 /* for client\'s use */
622              public int dwFlags;                /* assorted flags (see defines) */
623              public int dwReserved;             /* reserved for driver */
624          }
625          //=======================================================BitmapInfoHeader结构===================================================================
626          //BitmapInfoHeader定义了位图的头部信息
627         [StructLayout(LayoutKind.Sequential)]
628          public struct BITMAPINFOHEADER
629          {
630              public int biSize;
631              public int biWidth;
632              public int biHeight;
633              public short biPlanes;
634              public short biBitCount;
635              public int biCompression;
636              public int biSizeImage;
637              public int biXPelsPerMeter;
638              public int biYPelsPerMeter;
639              public int biClrUsed;
640              public int biClrImportant;
641          }
642          //=========================================================================================================================================
643 
644         //======================================================BitmapInfo结构=====================================================================
645          //BitmapInfo   位图信息
646         [StructLayout(LayoutKind.Sequential)]
647          public struct BITMAPINFO
648          {
649              public BITMAPINFOHEADER bmiHeader;
650              public int bmiColors;
651          }
652 
653         //=====================================================CAPTUREPARMS结构======================================================================
654          //CAPTUREPARMS 包含控制视频流捕获过程的参数,如捕获帧频、指定键盘或鼠标键以终止捕获、捕获时间限制等; 
655         [StructLayout(LayoutKind.Sequential)]
656          public struct CAPTUREPARMS
657          {
658              public int dwRequestMicroSecPerFrame;             // 期望的桢播放率,以毫秒为单位,默认为66667,相当于15桢每秒。
659             public bool fMakeUserHitOKToCapture;             // Show "Hit OK to cap" dlg?开始捕获标志位,如果值为真,则在开始捕获前要产生一个询问对话框,默认为假。
660             public uint wPercentDropForError;               //所允许的最大丢桢百分比,可以从0变化到100,默认值为10。
661             public bool fYield;                     /*另起线程标志位,如果为真,则程序重新启动一个线程用于视频流的捕获,默认值是假。
662                                                      但是如果你是为了真,你必须要在程序中处理一些潜在的操作,因为当视频捕获时,其他操作并没有被屏蔽。*/
663              public int dwIndexSize;                       // 在AVI文件中所允许的最大数目的索引项(32K)
664              public uint wChunkGranularity;               // AVI文件的逻辑尺寸,以字节为单位。如果值是0,则说明该尺寸渐增 在 Win32程序中无用。(2K)
665              public bool fUsingDOSMemory;                // Use DOS buffers?
666              public uint wNumVideoRequested;            // 所被允许分配的最大视频缓存
667             public bool fCaptureAudio;                // 音频标志位,如果音频流正在捕获,则该值为真。
668             public uint wNumAudioRequested;          // 最大数量的音频缓存,默认值为10。
669             public uint vKeyAbort;                  // 终止流捕获的虚拟键盘码,默认值为VK_ESCAPE
670              [MarshalAs(UnmanagedType.Bool)]
671              public bool fAbortLeftMouse;           // 终止鼠标左键标志位,如果该值为真,则在流捕获过程中如果点击鼠标左键则该捕获终止,默认值为真。
672             public bool fAbortRightMouse;                 // Abort on right mouse?
673              public bool fLimitEnabled;                   // 捕获操作时间限制,如果为真,则时间到了以后捕获操作终止,默认为假
674             public uint wTimeLimit;                     // 具体终止时间,只有 fLimitEnabled是真时.该位才有效
675             public bool fMCIControl;                   // Use MCI video source?
676              public bool fStepMCIDevice;               // Step MCI device?MCI 设备标志。
677             public int dwMCIStartTime;               // Time to start in MS
678              public int dwMCIStopTime;               // Time to stop in MS
679              public bool fStepCaptureAt2x;          // Perform spatial averaging 2x
680              public int wStepCaptureAverageFrames; // 当基于平均采样来创建桢时,桢的采样时间,典型值是5
681              public int dwAudioBufferSize;        // 音频缓存的尺寸,如果用默认值0,缓存尺寸是最大0.5秒,或10k字节。
682             public int fDisableWriteCache;      // Attempt to disable write cache
683              public int AVStreamMaster;         //音视频同步标志。
684         }
685          //=========================================================================================================================================
686 
687         //=================================================CAPDRIVERCAPS结构=======================================================================
688          //CAPDRIVERCAPS定义了捕获驱动器的能力,如有无视频叠加能力、有无控制视频源、视频格式的对话框等; 
689         [StructLayout(LayoutKind.Sequential)]
690          public struct CAPDRIVERCAPS
691          {
692              [MarshalAs(UnmanagedType.U2)]
693              public UInt16 wDeviceIndex;         //捕获驱动器的索引值,该值可以由0到9变化。
694             [MarshalAs(UnmanagedType.Bool)]
695              public bool fHasOverlay;            // 视频叠加标志,如果设备支持视频叠加这该位是真。
696             [MarshalAs(UnmanagedType.Bool)]
697              public bool fHasDlgVideoSource;     //视频资源对话框标志位,如果设备支持视频选择、控制对话框,该值为真。
698             [MarshalAs(UnmanagedType.Bool)]
699              public bool fHasDlgVideoFormat;     //视频格式对话框标志位,如果设备支持对视频格式对话框的选择,该位真。
700             [MarshalAs(UnmanagedType.Bool)]
701              public bool fHasDlgVideoDisplay;    //视频展示对话框标志位,如果设备支持对视频捕获缓存区的重新播放,该位是真。
702             [MarshalAs(UnmanagedType.Bool)]
703              public bool fCaptureInitialized;    //捕获安装标志位,如果捕获驱动器已经成功连接,该值为真。
704             //[MarshalAs(UnmanagedType.Bool)]
705              public bool fDriverSuppliesPalettes; //驱动器调色板标志位,如果驱动器能创建调色板,则该位是真。
706             [MarshalAs(UnmanagedType.I4)]
707              public int hVideoIn;
708              [MarshalAs(UnmanagedType.I4)]
709              public int hVideoOut;
710              [MarshalAs(UnmanagedType.I4)]
711              public int hVideoExtIn;
712              [MarshalAs(UnmanagedType.I4)]
713              public int hVideoExtOut;
714          }
715          //=========================================================================================================================================
716 
717 
718          //=====================================================CAPSTATUS结构========================================================================
719          //CAPSTATUS定义了捕获窗口的当前状态,如图像的宽、高等;
720         [StructLayout(LayoutKind.Sequential)]
721          public struct CAPSTATUS
722          {
723              public int uiImageWidth;                         //图像宽度
724             public int uiImageHeight;                       //图像高度
725             public bool fLiveWindow;                       //活动窗口标记,如果窗口正以预览的方式展示图像,那么该值为真
726             public bool fOverlayWindow;                   //叠加窗口标志位,如果正在使用硬件叠加,则该位是真。
727             public bool fScale;                          //输入所放标志位,如果窗口是正在缩放视频到客户区,那么该位是真。当使用硬件叠加时,改位无效。
728             public Point ptScroll;                      //被展示在窗口客户区左上角的那个象素的x、y坐标偏移量。
729             public bool fUsingDefaultPalette;          //默认调色板标志位,如果捕获窗口正在使用当前默认调色板,该值为真
730             public bool fAudioHardware;               // 音频硬件标志位,如果系统已经安装了音频硬件,该值为真。
731             public bool fCapFileExists;              //捕获文件标志位,如果一个捕获文件已经被创建,该值为真
732             public int dwCurrentVideoFrame;         // 当前或最近流捕获过程中,所处理的桢的数目。包括丢弃的桢。
733             public int dwCurrentVideoFramesDropped;//当前流捕获过程中丢弃的桢的数目。
734             public int dwCurrentWaveSamples;      // # of wave samples cap\'td
735              public int dwCurrentTimeElapsedMS;   // 从当前流捕获开始计算,程序所用的时间,以毫秒为单位。
736             public IntPtr hPalCurrent;          // 当前剪切板的句柄。
737             public bool fCapturingNow;         // 捕获标志位,当捕获是正在进行时,改位是真
738             public int dwReturn;              // 错误返回值,当你的应用程序不支持错误回调函数时可以应用改位
739             public int wNumVideoAllocated;   // 被分配的视频缓存的数目。
740             public int wNumAudioAllocated;  // 被分配的音频缓存的数目。
741         }
742          //=========================================================================================================================================
743 
744 
745          #endregion 结构 VIDEOHDR|BITMAPINFOHEADER|BITMAPINFO|CAPTUREPARMS|CAPDRIVERCAPS|CAPSTATUS
746 
747     }
748      public class cVideo     //视频类
749     {
750          public bool flag = true;
751          private IntPtr lwndC;       //保存无符号句柄
752         private IntPtr mControlPtr; //保存管理指示器
753         private int mWidth;
754          private int mHeight;
755          public delegate void RecievedFrameEventHandler(byte[] data);
756          public event RecievedFrameEventHandler RecievedFrame;
757 
758         public VideoAPI.CAPTUREPARMS Capparms;
759          private VideoAPI.FrameEventHandler mFrameEventHandler;
760          public VideoAPI.CAPDRIVERCAPS CapDriverCAPS;//捕获驱动器的能力,如有无视频叠加能力、有无控制视频源、视频格式的对话框等;
761         public VideoAPI.CAPSTATUS CapStatus;//该结构用于保存视频设备捕获窗口的当前状态,如图像的宽、高等
762         string strFileName;
763          public cVideo(IntPtr handle, int width, int height)
764          {
765              CapDriverCAPS = new VideoAPI.CAPDRIVERCAPS();//捕获驱动器的能力,如有无视频叠加能力、有无控制视频源、视频格式的对话框等;
766             CapStatus = new VideoAPI.CAPSTATUS();//该结构用于保存视频设备捕获窗口的当前状态,如图像的宽、高等
767             mControlPtr = handle; //显示视频控件的句柄
768             mWidth = width;      //视频宽度
769             mHeight = height;    //视频高度
770         }
771          /// <summary>
772          /// 打开视频设备
773         /// </summary>
774          public bool StartWebCam()
775          {
776              //byte[] lpszName = new byte[100];
777              //byte[] lpszVer = new byte[100];
778              //VideoAPI.capGetDriverDescriptionA(0, lpszName, 100, lpszVer, 100);
779              //this.lwndC = VideoAPI.capCreateCaptureWindowA(lpszName, VideoAPI.WS_CHILD | VideoAPI.WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0);
780              //if (VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_DRIVER_CONNECT, 0, 0))
781              //{
782              //    VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SET_PREVIEWRATE, 100, 0);
783              //    VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SET_PREVIEW, true, 0);
784              //    return true;
785              //}
786              //else
787              //{
788              //    return false;
789              //}
790              this.lwndC = VideoAPI.capCreateCaptureWindow("", VideoAPI.WS_CHILD | VideoAPI.WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0);//AVICap类的捕捉窗口
791             VideoAPI.FrameEventHandler FrameEventHandler = new VideoAPI.FrameEventHandler(FrameCallback);
792              VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_CALLBACK_ERROR, 0, 0);//注册错误回调函数
793             VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_CALLBACK_STATUS, 0, 0);//注册状态回调函数 
794             VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0);//注册视频流回调函数
795             VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_CALLBACK_FRAME, 0, FrameEventHandler);//注册帧回调函数
796 
797             //if (!CapDriverCAPS.fCaptureInitialized)//判断当前设备是否被其他设备连接已经连接
798             //{
799 
800             if (VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_DRIVER_CONNECT, 0, 0))
801              {
802                  //-----------------------------------------------------------------------
803                 VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_DRIVER_GET_CAPS, VideoAPI.SizeOf(CapDriverCAPS), ref CapDriverCAPS);//获得当前视频 CAPDRIVERCAPS定义了捕获驱动器的能力,如有无视频叠加能力、有无控制视频源、视频格式的对话框等;
804                 VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_GET_STATUS, VideoAPI.SizeOf(CapStatus), ref CapStatus);//获得当前视频流的尺寸 存入CapStatus结构
805 
806                 VideoAPI.BITMAPINFO bitmapInfo = new VideoAPI.BITMAPINFO();//设置视频格式 (height and width in pixels, bits per frame). 
807                  bitmapInfo.bmiHeader = new VideoAPI.BITMAPINFOHEADER();
808                  bitmapInfo.bmiHeader.biSize = VideoAPI.SizeOf(bitmapInfo.bmiHeader);
809                  bitmapInfo.bmiHeader.biWidth = mWidth;
810                  bitmapInfo.bmiHeader.biHeight = mHeight;
811                  bitmapInfo.bmiHeader.biPlanes = 1;
812                  bitmapInfo.bmiHeader.biBitCount = 24;
813                  VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_PREVIEWRATE, 40, 0);//设置在PREVIEW模式下设定视频窗口的刷新率 设置每40毫秒显示一帧,即显示帧速为每秒25帧
814                 VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_SCALE, 1, 0);//打开预览视频的缩放比例
815                 VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_VIDEOFORMAT, VideoAPI.SizeOf(bitmapInfo), ref bitmapInfo);
816 
817                 this.mFrameEventHandler = new VideoAPI.FrameEventHandler(FrameCallback);
818                  this.capSetCallbackOnFrame(this.lwndC, this.mFrameEventHandler);
819 
820 
821                  VideoAPI.CAPTUREPARMS captureparms = new VideoAPI.CAPTUREPARMS();
822                  VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_GET_SEQUENCE_SETUP, VideoAPI.SizeOf(captureparms), ref captureparms);
823                  if (CapDriverCAPS.fHasOverlay)
824                  {
825                      VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_OVERLAY, 1, 0);//启用叠加 注:据说启用此项可以加快渲染速度    
826                  }
827                  VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_PREVIEW, 1, 0);//设置显示图像启动预览模式 PREVIEW
828                  VideoAPI.SetWindowPos(this.lwndC, 0, 0, 0, mWidth, mHeight, VideoAPI.SWP_NOZORDER | VideoAPI.SWP_NOMOVE);//使捕获窗口与进来的视频流尺寸保持一致
829                 return true;
830              }
831              else
832              {
833 
834                 flag = false;
835                  return false;
836              }
837          }
838          public void get()
839          {
840              VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_GET_SEQUENCE_SETUP, VideoAPI.SizeOf(Capparms), ref Capparms);
841          }
842          public void set()
843          {
844              VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_SEQUENCE_SETUP, VideoAPI.SizeOf(Capparms), ref Capparms);
845          }
846          private bool capSetCallbackOnFrame(IntPtr lwnd, VideoAPI.FrameEventHandler lpProc)
847          {
848              return VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SET_CALLBACK_FRAME, 0, lpProc);
849          }
850          /// <summary>
851          /// 关闭视频设备
852         /// </summary>
853          public void CloseWebcam()
854          {
855              VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_DRIVER_DISCONNECT, 0, 0);
856          }
857          ///   <summary>   
858          ///   拍照
859         ///   </summary>   
860          ///   <param  >要保存bmp文件的路径</param>   
861          public void GrabImage(IntPtr hWndC, string path)
862          {
863              IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
864              VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
865          }
866          public void StarKinescope(string path)
867          {
868              strFileName = path;
869              string dir = path.Remove(path.LastIndexOf("//"));
870              if (!File.Exists(dir))
871              {
872                  Directory.CreateDirectory(dir);
873              }
874              int hBmp = Marshal.StringToHGlobalAnsi(path).ToInt32();
875              bool b = VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_FILE_SET_CAPTURE_FILE, 0, hBmp);
876              b = VideoAPI.SendMessage(this.lwndC, VideoAPI.WM_CAP_SEQUENCE, 0, 0);
877          }
878          /// <summary>
879          /// 停止录像
880         /// </summary>
881          public void StopKinescope()
882          {
883              VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_STOP, 0, 0);
884          }
885          private void FrameCallback(IntPtr lwnd, IntPtr lpvhdr)
886          {
887              VideoAPI.VIDEOHDR videoHeader = new VideoAPI.VIDEOHDR();
888              byte[] VideoData;
889              videoHeader = (VideoAPI.VIDEOHDR)VideoAPI.GetStructure(lpvhdr, videoHeader);
890              VideoData = new byte[videoHeader.dwBytesUsed];
891              VideoAPI.Copy(videoHeader.lpData, VideoData);
892              if (this.RecievedFrame != null)
893                  this.RecievedFrame(VideoData);
894          }               
895        }
896 
897 }

 

posted on
2018-08-22 17:10 
无网不进 
阅读(5244
评论(2
编辑 
收藏 
举报

版权声明:本文为hbtmwangjin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hbtmwangjin/articles/9518933.html