//加入DShow库 #include <DShow.h> #pragma comment(lib,"strmiids.lib") #pragma comment(lib,"quartz.lib") //定义自定义消息 #define CM_COMPLETE WM_USER+1 //定义变量 public: afx_msg void OnBnClickedPlayer(); afx_msg void OnBnClickedBrowser(); CEdit m_strFileName; CStatic m_Panel; IGraphBuilder *pGraph; IVideoWindow *pViewWnd; IMediaControl *pControl; IMediaEventEx *pEvent; BEGIN_MESSAGE_MAP(CmyplayerDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_MESSAGE_VOID(CM_COMPLETE,OnNotifyComplete)//映射自定义消息 //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_PLAYER, &CmyplayerDlg::OnBnClickedPlayer) ON_BN_CLICKED(IDC_BROWSER, &CmyplayerDlg::OnBnClickedBrowser) END_MESSAGE_MAP() //播放 void CmyplayerDlg::OnBnClickedPlayer() { CoInitialize(NULL); ICaptureGraphBuilder2 *pBuilder; 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); CString strFileName; m_strFileName.GetWindowText(strFileName); pGraph->RenderFile(strFileName,NULL); pGraph->QueryInterface(IID_IVideoWindow,(void**)&pViewWnd); pGraph->QueryInterface(IID_IMediaControl,(void**)&pControl); pGraph->QueryInterface(IID_IMediaEventEx,(void**)&pEvent); if(pViewWnd) { pViewWnd->put_Owner((OAHWND)m_Panel.m_hWnd); pViewWnd->put_Left(1); pViewWnd->put_Top(1); CRect rt; m_Panel.GetClientRect(&rt); pViewWnd->put_Width(rt.Width()); pViewWnd->put_Height(rt.Height()); long style; pViewWnd->get_WindowStyle(&style); style = style & WS_CHILD; pViewWnd->put_WindowStyle(style); } pEvent->SetNotifyWindow((OAHWND)m_hWnd,CM_COMPLETE,0); pControl->Run(); CoUninitialize(); } //处理“播放完成”事件 void CmyplayerDlg::OnNotifyComplete(WPARAM wParam,LPARAM lParam) { if(pEvent) { long eventcode,param1,param2; while(SUCCEEDED(pEvent->GetEvent(&eventcode,¶m1,¶m2,0))) { pEvent->FreeEventParams(eventcode,param1,param2); if(EC_COMPLETE == eventcode) { pControl->Stop(); pControl->Release(); pEvent->Release(); pViewWnd->put_Visible(FALSE); pViewWnd->Release(); pGraph->Release(); m_Panel.ShowWindow(SW_HIDE); m_Panel.ShowWindow(SW_SHOW); MessageBox(L"播放完成",L"提示"); } } } } //选择一个视频或音频文件进行播放 void CmyplayerDlg::OnBnClickedBrowser() { CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,L"All File(*.*)|*.*"); if(IDOK == dlg.DoModal()) { CString strFileName; strFileName = dlg.GetPathName(); m_strFileName.SetWindowText(strFileName); } } 运行效果: