#include <windows.h>
#include <setupapi.h>
#include <shlwapi.h>
#pragma comment(lib, "setupapi.lib")
#pragma comment(lib, "shlwapi.lib") // device information set(我把它译为设备信息集)
#pragma comment(lib, "Rpcrt4.lib")
BOOL StopDevice(BOOL bStatus)
{
LPTSTR HardwareId=_T("{4d36e96c-e325-11ce-bfc1-08002be10318}") ;
DWORD NewState ;
DWORD i,err ;
BOOL Found=FALSE ;
HDEVINFO hDevInfo ;
SP_DEVINFO_DATA spDevInfoData ;
if(bStatus)
{
NewState=DICS_DISABLE ;
//禁用
}
else
{
NewState=DICS_ENABLE ;
//启用
}
//访问系统的硬件库
hDevInfo=SetupDiGetClassDevs(NULL,_T("PCI"),NULL,DIGCF_ALLCLASSES|DIGCF_PRESENT);
if(hDevInfo==INVALID_HANDLE_VALUE)
{
printf("访问系统硬件出错!\n");
return FALSE ;
}
//枚举硬件,获得需要的接口
spDevInfoData.cbSize=sizeof(SP_DEVINFO_DATA);
BOOL flagEnum;
for(i=0;flagEnum = SetupDiEnumDeviceInfo(hDevInfo,i,&spDevInfoData);i++)
{
DWORD DataT ;
TCHAR buffer[100]={0};
DWORD buffersize=0 ;
//获得硬件的属性值
buffersize = sizeof(buffer);
while(!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&spDevInfoData,
SPDRP_SERVICE/*SPDRP_CLASSGUID*/,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
DWORD a = GetLastError();
if(GetLastError()==ERROR_INVALID_DATA)
{
//不存在HardwareID. Continue.
break ;
}
else if(GetLastError()==ERROR_INSUFFICIENT_BUFFER)
{
//buffer size不对.
if(buffer)
LocalFree(buffer);
// buffer=(char*)LocalAlloc(LPTR,buffersize);
}
else
{
//未知错误
goto cleanup_DeviceInfo ;
}
}
if(GetLastError()==ERROR_INVALID_DATA)
continue ;
if(NULL == buffer)
{
// LocalFree(buffer);
continue ;
}
if(!_tcscmp(_T("3xHybrid")/*HardwareId*/,buffer))
{
printf("找到指定设备\n");
_tprintf(buffer);
SP_PROPCHANGE_PARAMS spPropChangeParams ;
spPropChangeParams.ClassInstallHeader.cbSize=sizeof(SP_CLASSINSTALL_HEADER);
spPropChangeParams.ClassInstallHeader.InstallFunction=DIF_PROPERTYCHANGE ;
spPropChangeParams.Scope=DICS_FLAG_GLOBAL ;
spPropChangeParams.StateChange=NewState ;
//禁用:DICS_DISABLE,DICS_ENABLE启用
//
if(!SetupDiSetClassInstallParams(hDevInfo,&spDevInfoData,(SP_CLASSINSTALL_HEADER*)&spPropChangeParams,sizeof(spPropChangeParams)))
{
DWORD errorcode=GetLastError();
goto cleanup_DeviceInfo;
}
if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,hDevInfo,&spDevInfoData))
{
DWORD errorcode=GetLastError();
goto cleanup_DeviceInfo;
}
switch(NewState)
{
case DICS_DISABLE :
printf("禁用设备成功!\n");
break ;
case DICS_ENABLE :
printf("启动设备成功!\n");
break ;
}
}
}
//退出时,清理工作环境
cleanup_DeviceInfo :
err=GetLastError();
SetupDiDestroyDeviceInfoList(hDevInfo);
SetLastError(err);
return TRUE ;
}