简单实用的摄像头操作代码 如果你的电脑上装了一个摄像头,那么,你一定想在自己编写的程序中也能用上,可为软件增色不少。下面就介绍一段非常简单实用的代码。 这段代码要到两个API函数: 1.创建捕获窗口的函数,成功则返回这个窗口的句柄,否则返回NULL: * Declare Function capCreateCaptureWindow Lib "avicap32.dll" Alias "capCreateCaptureWindowA" ( _ ByVal lpszWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, _ ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal nID As Long) As Long 参数说明: 参数1:定义窗口标题 参数2:定义窗口样式,使用常数: WS_CHILD: 视频窗口是子窗口,位于应用程序主窗口内。否则是独立的窗口 WS_VISIBLE: 视频窗口可见 WS_Caption: 视频窗口有标题栏 WS_ThickFrame:视频窗口有边框 参数3、4:窗口左上角的坐标 参数5、6:窗口的宽、高度 参数7:父窗口句柄 参数8:窗口标识号 2.传送消息(操作命令)的函数: * Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long 这个函数用得较多,就不详细介绍了。 新建一个工程,为窗体添加四个菜单项,名称和标题相同,分别为:开始、停止、拍照、视频。 代码如下: Option Explicit * Declare Function capCreateCaptureWindow Lib "avicap32.dll" Alias "capCreateCaptureWindowA" (ByVal lpszWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal nID As Long) As Long * Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long * Const WS_CHILD = &H40000000 * Const WS_VISIBLE = &H10000000 * Const WM_CAP_START = &H400 * Const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10 * Const WM_CAP_SET_PREVIEW = WM_CAP_START + 50 * Const WM_CAP_SET_SCALE = WM_CAP_START + 53 * Const WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52 * Const WM_CAP_EDIT_COPY = WM_CAP_START + 30 * Const WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11 * Const WM_CAP_SEQUENCE = WM_CAP_START + 62 Dim vHandle As Long * Sub 开始_Click() vHandle = capCreateCaptureWindow("Video", WS_CHILD + WS_VISIBLE, 0, 0, ScaleWidth / 15, ScaleHeight / 15, hwnd, 1) SendMessage vHandle, WM_CAP_DRIVER_CONNECT, 0, 0 ''连接捕获设备 SendMessage vHandle, WM_CAP_SET_PREVIEW, 1, 0 ''打开预览模式 SendMessage vHandle, WM_CAP_SET_SCALE, 1, 0 ''设置自动缩放(图像大小自动适应容器大小) SendMessage vHandle, WM_CAP_SET_PREVIEWRATE, 66, 0 ''设置帧速率为66毫秒一帧 End Sub * Sub 拍照_Click() Dim pic As StdPicture Clipboard.Clear SendMessage vHandle, WM_CAP_EDIT_COPY, 0, 0 ''复制图像到剪贴板 Set pic = Clipboard.GetData SavePicture pic, "d:\100.bmp" End Sub * Sub 停止_Click() SendMessage vHandle, WM_CAP_DRIVER_DISCONNECT, 0, 0 ''断开连接 End Sub * Sub 视频_Click() SendMessage vHandle, WM_CAP_SEQUENCE, 0, 0 ''开始捕获视频 End Sub 说明: 1.点击拍照菜单项后,剪贴板上的图像可粘贴到别的程序窗口去。 2.点击视频菜单项后,开始录像,按【ESC】键停止并自动保存到系统盘根目录下,文件名为:CAPTURE.AVI
|