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中的函數,函數語法及結構如下。 14 (1)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 返回值:視頻捕捉窗口句柄。 26 (2)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 }