#include <dshow.h>
#include <atlbase.h>
#include <stdio.h>
CComQIPtr m_pVW;
CComQIPtr m_pMC;
CComQIPtr m_pME;
CComPtr m_pGraph;
CComPtr m_pCapture;
DWORD m_dwGraphRegister;
bool bInit(HWND hWnd)
{
HRESULT hr;
//获得接口
hr=CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,IID_IGraphBuilder,
(void **) &m_pGraph);
if (FAILED(hr))
return false;
hr=CoCreateInstance (CLSID_CaptureGraphBuilder2 , NULL, CLSCTX_INPROC,
IID_ICaptureGraphBuilder2, (void **) &m_pCapture);
if (FAILED(hr))
return false;
m_pMC=m_pGraph;
m_pVW=m_pGraph;
m_pME=m_pGraph;
//取得消息
m_pME->SetNotifyWindow((OAHWND)(m_hWnd=hWnd), WM_GRAPHNOTIFY, 0);
//将过滤和捕获进行连接
m_pCapture->SetFiltergraph(m_pGraph);
//设备联接
//枚举设备
CComPtr pCde=NULL;
CComPtr pEm=NULL;
hr=CoCreateInstance (CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
IID_ICreateDevEnum, (void **) &pCde);
if (FAILED(hr))
return false;
pCde->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
if(pEm==NULL)
return false;
CComPtr pM=NULL;
ULONG cFetched;
CComPtr pBf=NULL;
if(pEm->Next(1,&pM,&cFetched)==S_OK)
{
pM->BindToObject(0,0,IID_IBaseFilter, (void**)&pBf);
pM.Release();
}
else
{
return false;
}
//将设备添加到graph
hr = m_pGraph->AddFilter(pBf, L"Video Capture");
if (FAILED(hr))
return false;
//连接一个源插口
hr=m_pCapture->RenderStream(&PIN_CATEGORY_PREVIEW,&MEDIATYPE_Video,pBf,
NULL, NULL);
if (FAILED(hr))
return false;
pBf.Release();
//设定视频窗口
//设定视频窗口为主窗口的一个子窗口
hr=m_pVW->put_Owner((OAHWND)hWnd);
if (FAILED(hr))
return false;
//设定窗口样式
m_pVW->put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN);
if (FAILED(hr))
return false;
//设定窗口大小
CRect rectClient;
GetClientRect(hWnd,rectClient);
m_pVW->SetWindowPosition(0, 0, 320, 240);
//设定可视
hr=m_pVW->put_Visible(OATRUE);
if (FAILED(hr))
return false;
//将对象加入到运行对象列表中
CComPtr pROT;
GetRunningObjectTable(0,&pROT);
WCHAR c[128];
wsprintfW(c, L"FilterGraph %08x pid %08x/0", (DWORD_PTR)m_pGraph.p,
GetCurrentProcessId());
hr = CreateItemMoniker(L"!",c,&pM);
if (FAILED(hr))
return false;
hr = pROT->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE,m_pGraph,pM,
&m_dwGraphRegister);
pM.Release();
return false;
}