1 安装摄像头驱动
2 引用DirectShow库,包含DirectShow头文件
#pragma comment(lib,"Strmiids.lib")
#pragma comment(lib,"quartz.lib")
#include "dshow.h"
3 初始化com环境
::CoInitialize(NULL);
4 定义一个过滤器引脚查询函数,并实现之
定义
IPin *findpin(IBaseFilter *pFilter,PIN_DIRECTION dir);
实现,假定工程为MFC Dialog Based类型,主对话框类为VDlg
IPin *VDlg::findpin(IBaseFilter *pFilter,PIN_DIRECTION dir)
{
IEnumPins *pEnumPins=NULL;
IPin *pRetPin=NULL;
PIN_DIRECTION pDir;
pFilter->EnumPins(&pEnumPins);
while(pEnumPins->Next(1,&pRetPin,NULL)==S_OK)
{
pRectPin->QueryDirection(&pDir);
if(pDir==dir)
{
return pRetPin;
}
}
return 0;
}
5 预览实现
void VDlg::vPreview()
{
ICaptureGraphBuilder *pBuilder=NULL;
::CoCreateInstance(CLSID_CaptureGraphBuilder2,NULL,CLSCTX_INPROC_SERVER,IID_ICaptureGraphBuilder2,(void **)&pBuilder);
::CoCreateInstance(CLSID_FilterGraph,NULL,CLSCTX_INPROC_SERVER,IID_IGraphBuilder,(void **)&pGraph);
pBuilder->SetFiltergraph(pGraph);
ICreateDevEnum *pDevEnum=NULL;
IEnumMoniker *pClsEnum=NULL;
::CoCreateInstance(CLSID_SystemDeviceEnum,NULL,CLSCTX_INPROC,IID_ICreateDevEnum,(void **)&pDevEnum);
pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pClsEnum,0);
if(pClsEnum->Next(1,&pMoniker,NULL)==S_OK)
{
pMoniker->BindToObject(0,0,IID_IBaseFilter,(void **)&pSrc);
pMoniker->Release();
}
pClsEnum->Release();
pGraph->AddFilter(pSrc,L"AVI");
::CoCreateInstance(CLSID_VideoRenderer,NULL,CLSCTX_ALL,IID_IBaseFilter,(void **)&pPreview);
if(pPreview)
{
pGraph->AddFilter(pPreview,L"PREVIEW");
IPin *pPinOut,*pPinIn;
pPinOut=findpin(pSrc,PINDIR_OUTPUT);
pPinIn=findpin(pPreview,PINDIR_INPUT);
pGraph->ConnectDirect(pPinOut,pPinIn,0);
IVideoWindow *pWnd=NULL;
pPreview->QueryInterface(IID_IVideowindow,(void **)&pWnd);
if(pWnd)
{
long ws;
pWnd->put_Owner((long)m_hWnd);
pWnd->get_WindowStyle(&ws);
ws=ws &~ WS_CAPTION;
ws=ws &~WS_DLGFRAME;
ws=ws & WS_CHILD;
pWnd->put_WindowStyle(ws);
CRect rc;
this->GetClientRect(rc);
pWnd->put_Lef(5);
pWnd->put_Top(5);
pWnd->put_Width(rc.Width()-5);
pWnd->put_Height(rc.Height()-5);
}
pMediaCtrl->Run();
}
}