前言
本文主要是讲在MFC中使用消息队列,并在消息中捕获系统USB插入、卸载U盘的事件。
正文
一、MFC中使用消息队列
1.1 声明
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
1.2 实现
LRESULT CTestDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
return CDialog::WindowProc(message,wParam,lParam);
}
{
return CDialog::WindowProc(message,wParam,lParam);
}
本示例是继承CDialog。
二、捕获U盘插入、卸载事件
LRESULT CTestDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
//WM_DEVICECHANGE,系统硬件改变发出的系统消息
case WM_DEVICECHANGE:
{
PDEV_BROADCAST_HDR lpdb=(PDEV_BROADCAST_HDR)lParam;
switch(wParam)
{
case WM_DEVICECHANGE:
break;
case DBT_DEVICEARRIVAL://DBT_DEVICEARRIVAL,设备检测结束,并且可以使用
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)//逻辑卷
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
switch(lpdbv->dbcv_flags)
{
case 0: //U盘
{
CString decDriver;
decDriver = FirstDriveFromMask(lpdbv ->dbcv_unitmask);
TRACE1("检测到U盘:[%s]插入!\n",decDriver.GetBuffer(0));
}
break;
case DBTF_MEDIA: //光盘
TRACE1("检测到光盘:[%c]插入!\n",FirstDriveFromMask(lpdbv ->dbcv_unitmask));
break;
}
}
}
break;
case DBT_DEVICEREMOVECOMPLETE://DBT_DEVICEREMOVECOMPLETE,设备卸载或者拔出
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)//逻辑卷
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
switch(lpdbv->dbcv_flags)
{
case 0: //U盘
{
CString decDriver;
decDriver = FirstDriveFromMask(lpdbv ->dbcv_unitmask);
TRACE1("检测到U盘:[%s]拔出!\n",decDriver.GetBuffer(0));
}
break;
case DBTF_MEDIA: //光盘
break;
}
}
}
break;
}
}
break;
}
return CDialog::WindowProc(message,wParam,lParam);
}
{
switch (message)
{
//WM_DEVICECHANGE,系统硬件改变发出的系统消息
case WM_DEVICECHANGE:
{
PDEV_BROADCAST_HDR lpdb=(PDEV_BROADCAST_HDR)lParam;
switch(wParam)
{
case WM_DEVICECHANGE:
break;
case DBT_DEVICEARRIVAL://DBT_DEVICEARRIVAL,设备检测结束,并且可以使用
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)//逻辑卷
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
switch(lpdbv->dbcv_flags)
{
case 0: //U盘
{
CString decDriver;
decDriver = FirstDriveFromMask(lpdbv ->dbcv_unitmask);
TRACE1("检测到U盘:[%s]插入!\n",decDriver.GetBuffer(0));
}
break;
case DBTF_MEDIA: //光盘
TRACE1("检测到光盘:[%c]插入!\n",FirstDriveFromMask(lpdbv ->dbcv_unitmask));
break;
}
}
}
break;
case DBT_DEVICEREMOVECOMPLETE://DBT_DEVICEREMOVECOMPLETE,设备卸载或者拔出
{
if(lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)//逻辑卷
{
PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
switch(lpdbv->dbcv_flags)
{
case 0: //U盘
{
CString decDriver;
decDriver = FirstDriveFromMask(lpdbv ->dbcv_unitmask);
TRACE1("检测到U盘:[%s]拔出!\n",decDriver.GetBuffer(0));
}
break;
case DBTF_MEDIA: //光盘
break;
}
}
}
break;
}
}
break;
}
return CDialog::WindowProc(message,wParam,lParam);
}
三、效果图
四、文章修改
4.1 2010-5-7 MFC中使用不要使用SetWindowLong方式来获取消息队列,否则会出现无法关闭窗口的问题。
4.2 2013-2-17 感谢网友提醒,CString getBuffer后应调用ReleaseBuffer结束语
继续恶补基础...