/*****************************************
Author:foo_hack This is File named:Setup.h The Funtion Implement in Setup.cpp ******************************************/ #include "stdafx.h" void UDBG(TCHAR *msg, ...); void FreeAllInfFiles();
int FindAllInfFiles(WCHAR* csDir);
void InstallDriver();
int UpdateDriver();
void FindAllDevices(const WCHAR* asHID);
void FreeDevices();
void RemoveDevices();
BOOL Reboot();
BOOL ConfigRight(WCHAR* szPath); VOID SearchRegistryHardID(PWCHAR pHardIDBuffer); //////////////////////////////////////////////////////////////////// BOOL IsDeviceInstallInProgress(VOID);
int RemoveDriver(_TCHAR *HardwareID);
VOID UninstallWDMDriver(LPCTSTR theHardware);
BOOL UnicodeToAnsi(LPCWSTR Source, const WORD wLen, LPSTR Destination, const WORD sLen);
BOOL AnsiToUnicode(LPCSTR Source, const WORD sLen, LPWSTR Destination, const WORD wLen);
//BOOL GetINFData(FILE *pFile);
VOID FindComma(LPSTR szData);
//BOOL GetSectionData(FILE* pFile, const char* szKey, const char bIsVender);
//BOOL IsInstalled();
BOOL InstallClassDriver(LPCTSTR theINFName);
BOOL StartInstallWDMDriver(LPCTSTR theInfName) ; BOOL FindExistingDevice(IN LPTSTR HardwareId); VOID InitialGlobalVar(); //////////////////////////////////////////////////////////////////// //extern WORD g_wVender;
//extern WORD g_wHardware;
//extern TCHAR g_strVender[20][64];
//extern TCHAR g_strHardware[20][64];
//extern TCHAR g_strHID[MAX_PATH+1]; /////////////////////////////////////////////////////////////////// typedef struct
{
WCHAR asHID[MAX_PATH];
int nInfNum; // g_asInfList下标号 int nNumCone;
int nNumNotCone;
bool bNeedUpdate; bool bWillBeUpdate;
bool bSuccess;
//int nFail;
} HID_INFO, *PHID_INFO; typedef struct
{
WCHAR asInfName[MAX_PATH]; // 文件名
WCHAR asFullPath[MAX_PATH]; // 全路径
WCHAR asDesPath[MAX_PATH];
WCHAR *asDesName;
WCHAR asVersion[MAX_PATH];
WCHAR asClassName[MAX_PATH];
WCHAR asProvider[MAX_PATH];
WCHAR asDSign[MAX_PATH];
bool bWillBeInstall;
int nResultInstall;
}INF_INFO, *PINF_INFO; #define MAX_SYMBOL_LINK 250 typedef struct Hid_Ddvices{
WCHAR asHID[MAX_PATH]; WCHAR* asDeviceInstanceID[MAX_SYMBOL_LINK];
bool bLink[MAX_SYMBOL_LINK];
bool bSuccess[MAX_SYMBOL_LINK];
bool bWillBeDelete[MAX_SYMBOL_LINK]; int nMaxCount;
int nCount; bool bNeedReboot; Hid_Ddvices()
{
nCount = nMaxCount = ;
bNeedReboot = false; ZeroMemory(asHID, sizeof(asHID)+ sizeof(asDeviceInstanceID) +
sizeof(bLink) + sizeof(bSuccess) + sizeof(bWillBeDelete));
}
}HID_DEVICES, *PHID_DEVICES; #define MAX_INF_COUNT 40
#define MAX_HID_COUNT 250 extern PINF_INFO g_InfList[MAX_INF_COUNT];
extern int g_nInfCount; // INF文 extern PHID_INFO g_HIDInfo[MAX_HID_COUNT];
extern int g_nHIDCount ; // HID个数 extern HID_DEVICES g_HIDDevices;

Setup.h

 #include "stdafx.h"
#include <newdev.h>
#include <setupapi.h>
#include <cfgmgr32.h>
#include <regstr.h>
#include <strsafe.h>
#include <string.h> #include <Aclapi.h>
#include "setup.h" #pragma comment(lib,"Advapi32") #pragma comment(lib, "newdev.lib")
#pragma comment(lib, "setupapi.lib") void GetHIDList(int nInfIndex); DWORD DeleteTree(HKEY RootKey, const WCHAR *pSubKey); // 不带变参
void ULOG(TCHAR *msg)
{
OutputDebugString(_T("UsbKitApp:"));
OutputDebugString(msg);
OutputDebugString(_T("\r\n"));
} #ifdef DEBUG
// 带变参的Log函数
void UDBG(TCHAR *msg, ...)
{
TCHAR strMsg[]; va_list argp;
va_start(argp, msg);
_vstprintf_s(strMsg, , msg, argp);
va_end(argp);
OutputDebugString(_T("UsbKitApp:"));
OutputDebugString(strMsg);
OutputDebugString(_T("\r\n"));
}
#else
void UDBG(TCHAR* msg, ...)
{ }
#endif PINF_INFO g_InfList[MAX_INF_COUNT];
int g_nInfMaxCount = ;
int g_nInfCount = ; // INF文件数 PHID_INFO g_HIDInfo[MAX_HID_COUNT];
int g_nHIDMaxCount = ;
int g_nHIDCount = ; // HID个数 HID_DEVICES g_HIDDevices; void FreeDevices()
{
for(int i = ; i < g_HIDDevices.nMaxCount; i++)
{
delete g_HIDDevices.asDeviceInstanceID[i];
} ZeroMemory(&g_HIDDevices, sizeof(g_HIDDevices));
} void FreeAllInfFiles()
{
for(int i = ; i < g_nHIDMaxCount; i++)
delete g_HIDInfo[i]; g_nHIDMaxCount = g_nHIDCount = ; for(int i = ; i < g_nInfMaxCount; i++)
delete g_InfList[i]; g_nInfMaxCount = g_nInfCount = ;
} //在特定路径下寻找所有的inf文件
int FindAllInfFiles(WCHAR* csDir = NULL)
{
WIN32_FIND_DATA FindFileData;
WCHAR dir[MAX_PATH];
WCHAR path[MAX_PATH];
HANDLE hFind = INVALID_HANDLE_VALUE; if(csDir == NULL)
{
// 在当前路径中搜索所有inf文件
GetCurrentDirectory(MAX_PATH, dir);
//StringCchCopy(path, MAX_PATH, dir);//此函数不支持win XP SP1
wcscpy(path,dir);
}
else
{
if(!GetFullPathName(csDir, MAX_PATH, dir, NULL))
GetCurrentDirectory(MAX_PATH, dir); //StringCchCopy(path, MAX_PATH, dir); wcscpy(path,dir);
} //StringCchCat(path, MAX_PATH, L"\\*.inf");//此函数不支持win XP SP1
wcscat(path,L"\\*.inf"); wprintf(path);
printf("\n"); __try{ g_nInfCount = ;
g_nHIDCount = ; // 遍历
hFind = FindFirstFile(path, &FindFileData); if (hFind == INVALID_HANDLE_VALUE)
{
printf("没有发现inf文件\n");
__leave;
} do{
if(g_nInfCount >= g_nInfMaxCount)
{
g_InfList[g_nInfCount] = new INF_INFO;
g_nInfMaxCount = g_nInfCount + ;
} ZeroMemory(g_InfList[g_nInfCount], sizeof(INF_INFO)); //StringCchCopy(path, MAX_PATH, dir);
wcscpy(path,dir);
//StringCchCat(path, MAX_PATH, L"\\");
wcscat(path,L"\\");
//StringCchCat(path, MAX_PATH, FindFileData.cFileName);
wcscat(path,FindFileData.cFileName);
//StringCchCopy(g_InfList[g_nInfCount]->asInfName, MAX_PATH, FindFileData.cFileName);
wcscpy(g_InfList[g_nInfCount]->asInfName,FindFileData.cFileName);
//StringCchCopy(g_InfList[g_nInfCount]->asFullPath, MAX_PATH, path);
wcscpy(g_InfList[g_nInfCount]->asFullPath,path);
// 查找每个inf文件中的所有HID
wprintf(L"找到文件:%s\n", FindFileData.cFileName); GetHIDList(g_nInfCount);
g_nInfCount ++; }while (FindNextFile(hFind, &FindFileData) != && g_nInfMaxCount < MAX_INF_COUNT) ; }
__finally{
if(hFind != INVALID_HANDLE_VALUE)
{
FindClose(hFind);
}
} return g_nHIDCount;
} //查找特定inf文件中的所有HID(硬件ID)
void GetHIDList(int nInfIndex)
{
INFCONTEXT infcont;
INFCONTEXT infcont_dev; HINF hInf = INVALID_HANDLE_VALUE;
DWORD config_flags, problem, status;
BOOL reboot;
WCHAR inf_path[MAX_PATH]; WCHAR direct[MAX_PATH];
WCHAR manu[MAX_PATH];
WCHAR manu_os[MAX_PATH];
WCHAR hid[MAX_PATH];
WCHAR tmp_id[MAX_PATH]; WCHAR os[][]; __try
{
// 取INF路径
wprintf(g_InfList[nInfIndex]->asFullPath);
if(!GetFullPathName(g_InfList[nInfIndex]->asFullPath, MAX_PATH, inf_path, NULL))
{
printf(".inf文件 %s 未找到\n", g_InfList[nInfIndex]->asInfName);
__leave;
} wprintf(L"INF 文件路径:%s\n", inf_path); // 打开INF文件
hInf = SetupOpenInfFile(inf_path, NULL, INF_STYLE_WIN4, NULL); if(hInf == INVALID_HANDLE_VALUE)
{
wprintf(L"打开文件失败:%s", inf_path);
__leave;
} if(!SetupFindFirstLine(hInf, L"version", NULL, &infcont))
{
printf("找不到[Version]域,不是合法的Inf文件\n");
__leave;
} //
// 获取Version信息
// do
{
if(!SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
continue; _wcslwr(direct);//把字符串转为小写
if( == wcscmp(direct, L"class"))
{
if(SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
{
//StringCchCopy(g_InfList[nInfIndex]->asClassName, MAX_PATH, direct);
wcscpy(g_InfList[nInfIndex]->asClassName,direct);
}
}
else if( == wcscmp(direct, L"driverver"))
{
if(SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
{
//StringCchCopy(g_InfList[nInfIndex]->asVersion, MAX_PATH, direct);
wcscpy(g_InfList[nInfIndex]->asVersion,direct); if(SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
{
//StringCchCat(g_InfList[nInfIndex]->asVersion, MAX_PATH, L", ");
wcscat(g_InfList[nInfIndex]->asVersion,L", ");
//StringCchCat(g_InfList[nInfIndex]->asVersion, MAX_PATH, direct);
wcscat(g_InfList[nInfIndex]->asVersion,direct);
}
}
}
else if( == wcscmp(direct, L"provider"))
{
if(SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
{
//StringCchCopy(g_InfList[nInfIndex]->asProvider, MAX_PATH, direct);
wcscpy(g_InfList[nInfIndex]->asProvider,direct);
}
}
else if(wcsstr(direct, L"catalogfile"))//返回第一个子字符创的指针
{
if(SetupGetStringField(&infcont, , direct, sizeof(direct), NULL))
{
//StringCchCopy(g_InfList[nInfIndex]->asDSign, MAX_PATH, direct);
wcscpy(g_InfList[nInfIndex]->asDSign,direct);
}
}
} while (SetupFindNextLine(&infcont, &infcont)); printf("INF 信息:\n");
wprintf(L"%s\n", g_InfList[nInfIndex]->asClassName);
wprintf(L"%s\n", g_InfList[nInfIndex]->asProvider);
wprintf(L"%s\n", g_InfList[nInfIndex]->asDSign);
wprintf(L"%s\n", g_InfList[nInfIndex]->asVersion); if(g_nHIDMaxCount >= MAX_HID_COUNT)
__leave; //
// 搜索设备描述符
// if(!SetupFindFirstLine(hInf, L"Manufacturer", NULL, &infcont))
{
printf("没有可用设备描述符\n");
__leave;
} SYSTEM_INFO siSysInfo;
GetSystemInfo(&siSysInfo); do{
int i = ;
int j = ; // 一行行搜索
if(!SetupGetStringField(&infcont, , manu, sizeof(manu), NULL))
{
continue;
} wprintf(manu); printf("\n"); for(; i < ; i++)
{
if(!SetupGetStringField(&infcont, i+, os[i], sizeof(os[]), NULL))
break;
else
printf("OS: %s\n", os[i]); _wcslwr(os[i]);
} // 寻找最佳的平台匹配
if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) // X64
{
for(; j < i; j++)
{
if(wcscmp(os[j], L"ntamd64"))
{
//StringCchCopy(manu_os, sizeof(manu_os), manu);
wcscpy(manu_os,manu);
//StringCchCat(manu_os, sizeof(manu_os), L".");
wcscat(manu_os,L".");
//StringCchCat(manu_os, sizeof(manu_os), os[j]);
wcscat(manu_os,os[i]); // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
//StringCchCopy(manu, sizeof(manu), manu_os);
wcscpy(manu,manu_os); break;
}
}
}
else if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
{
for(; j < i; j++)
{
if( == wcsstr(os[j], L"ntia64"))
{
//StringCchCopy(manu_os, sizeof(manu_os), manu);
wcscpy(manu_os,manu);
//StringCchCat(manu_os, sizeof(manu_os), L".");
wcscat(manu_os,L".");
//StringCchCat(manu_os, sizeof(manu_os), os[j]);
wcscat(manu_os,os[j]); // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
//StringCchCopy(manu, sizeof(manu), manu_os);
wcscpy(manu,manu_os); break;
}
}
}
else if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
{
for(; j < i; j++)
{
if( == wcsstr(os[j], L"ntx86"))
{
//StringCchCopy(manu_os, sizeof(manu_os), manu);
wcscpy(manu_os,manu);
//StringCchCat(manu_os, sizeof(manu_os), L".");
wcscat(manu_os,L".");
//StringCchCat(manu_os, sizeof(manu_os), os[j]);
wcscat(manu_os,os[j]);
wprintf(manu_os);
printf("\n");
// 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
//StringCchCopy(manu, sizeof(manu), manu_os);
wcscpy(manu,manu_os); break;
}
}
} // 最后,如果最符合的版本没有找到,就看看.nt有没有
if(NULL == wcsstr(manu, L".ntx86") &&
NULL == wcsstr(manu, L".ntia64") &&
NULL == wcsstr(manu, L".ntamd64"))
{
for(j = ; j < i; j++)
{
if( == wcsstr(os[j], L".nt"))
{
//StringCchCopy(manu_os, sizeof(manu_os), manu);
wcscpy(manu_os,manu);
//StringCchCat(manu_os, sizeof(manu_os), L".");
wcscat(manu_os,L".");
//StringCchCat(manu_os, sizeof(manu_os), os[j]);
wcscat(manu_os,os[j]); // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
//StringCchCopy(manu, sizeof(manu), manu_os);
wcscpy(manu,manu_os); break;
}
}
} wprintf(L"设备域名:%s\n", manu);
if(!SetupFindFirstLine(hInf, manu, NULL, &infcont_dev))
{
printf("找不到设备模块\n");
continue;
} do{
if(!SetupGetStringField(&infcont_dev, , hid, sizeof(hid), NULL))
continue; // 保存HID记录
// _wcslwr(hid);
wprintf(L"HID: %s\n", hid); if(g_nHIDMaxCount <= g_nHIDCount)
{
g_HIDInfo[g_nHIDCount] = new HID_INFO;
g_nHIDMaxCount = g_nHIDCount + ;
} ZeroMemory(g_HIDInfo[g_nHIDCount], sizeof(HID_INFO));
//StringCchCopy(g_HIDInfo[g_nHIDCount]->asHID, MAX_PATH, hid);
wcscpy(g_HIDInfo[g_nHIDCount]->asHID,hid);
g_HIDInfo[g_nHIDCount]->nInfNum = nInfIndex;
g_nHIDCount++; }while(SetupFindNextLine(&infcont_dev, &infcont_dev) && g_nHIDMaxCount < MAX_HID_COUNT); // 获取下一个设备ID
}while(SetupFindNextLine(&infcont, &infcont) && g_nHIDMaxCount < MAX_HID_COUNT);
}
__finally
{
if(hInf != INVALID_HANDLE_VALUE)
SetupCloseInfFile(hInf);
}
} BOOL Reboot()
{
HANDLE Token = NULL;
TOKEN_PRIVILEGES NewPrivileges;
LUID Luid; __try
{
// 使能ShutDown特权
if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&Token))
__leave; if(!LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&Luid))
__leave; NewPrivileges.PrivilegeCount = ;
NewPrivileges.Privileges[].Luid = Luid;
NewPrivileges.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(Token, FALSE, &NewPrivileges, , NULL, NULL);
}
__finally
{
if(Token) CloseHandle(Token);
} //尝试重启
return InitiateSystemShutdownEx(NULL, NULL, , FALSE, TRUE, REASON_PLANNED_FLAG | REASON_HWINSTALL);
} // 删除设备对应的驱动程序,调用SetupDiCallClassInstaller函数,并执行DIF_REMOVE动作
// 参数Devs和DevInfo用来唯一标识目标设备
bool RemoveDevice(__in HDEVINFO Devs, __in PSP_DEVINFO_DATA DevInfo)
{
UDBG(_T("[RemoveDriverForSpecifiedDevice]")); SP_REMOVEDEVICE_PARAMS rmdParams;
SP_DEVINSTALL_PARAMS devParams; rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
rmdParams.HwProfile = ; if(SetupDiSetClassInstallParams(Devs, DevInfo, &rmdParams.ClassInstallHeader, sizeof(rmdParams)) &&
SetupDiCallClassInstaller(DIF_REMOVE, Devs, DevInfo))
{
wprintf(_T("卸载驱动成功\n")); // 检查是否需要重启机器
devParams.cbSize = sizeof(devParams);
if(SetupDiGetDeviceInstallParams(Devs, DevInfo, &devParams) &&
(devParams.Flags & (DI_NEEDRESTART|DI_NEEDREBOOT)))
{
g_HIDDevices.bNeedReboot = true;
} return true;
} return false;
} void RemoveDevices()
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int nDevIndex;
WCHAR id[MAX_PATH]; g_HIDDevices.bNeedReboot = false; // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES); // class名无效
if(dev_info == INVALID_HANDLE_VALUE)
{
printf("无效的HDEVINFO句柄\n");
return;
} nDevIndex = ; // 枚举设备
dev_info_data.cbSize = sizeof(dev_info_data);
while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
{
if(CR_SUCCESS != CM_Get_Device_ID(dev_info_data.DevInst, id, MAX_PATH, ))
continue; _wcslwr(id); for(int i = ; i < g_HIDDevices.nCount; i++)
{
if(g_HIDDevices.bWillBeDelete[i] &&
== wcscmp(id, g_HIDDevices.asDeviceInstanceID[i]))
{
wprintf(id);
printf("\n");
g_HIDDevices.bSuccess[i] = RemoveDevice(dev_info, &dev_info_data);
}
} nDevIndex++;
} SetupDiDestroyDeviceInfoList(dev_info);
} //该函数主要就是根据硬件ID查找在本地机器上有没有这样一个设备,\
把查找到的ID放到全局变量中,还检测设备有没有连接系统
void FindAllDevices(const WCHAR* asHID)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data; int nDevIndex;
WCHAR id[MAX_PATH];
WCHAR *p;
ULONG problem;
ULONG status; WCHAR* ashid = _wcsdup(asHID);
_wcslwr(ashid);//转换ashid中的大写字母 printf("FindAllDevices\n"); g_HIDDevices.nCount = ; // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES); // class名无效
if(dev_info == INVALID_HANDLE_VALUE)
{
printf("无效的HDEVINFO句柄\n");
free(ashid);
return;
} nDevIndex = ; // 枚举设备,从0开始枚举设备
dev_info_data.cbSize = sizeof(dev_info_data);
while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
{
if(CR_SUCCESS != CM_Get_Device_ID(dev_info_data.DevInst, id, MAX_PATH, ))
continue; (id);
if(wcsstr(id, ashid))
{
if(g_HIDDevices.nCount >= g_HIDDevices.nMaxCount)
{
g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nMaxCount] = new WCHAR[MAX_PATH];
g_HIDDevices.nMaxCount++;
} // Device实例ID。把id拷贝到parameter 1中
//StringCchCopy(g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nCount], MAX_PATH, id);
wcscpy(g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nCount],id);
// 连接状态
g_HIDDevices.bLink[g_HIDDevices.nCount] = false;
if(CM_Get_DevNode_Status(&status,
&problem,
dev_info_data.DevInst,
) != CR_NO_SUCH_DEVINST)
{
g_HIDDevices.bLink[g_HIDDevices.nCount] = true;
} g_HIDDevices.nCount++;
} nDevIndex++;
} SetupDiDestroyDeviceInfoList(dev_info);
free(ashid);
} void InstallDriver()
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int nDevIndex;
WCHAR id[MAX_PATH];
WCHAR tmp_id[MAX_PATH];
WCHAR *p;
ULONG problem;
ULONG status;
int nInfIndex; for(nInfIndex = ; nInfIndex < g_nInfCount; nInfIndex++)
{
if(false == g_InfList[nInfIndex]->bWillBeInstall)
continue; // 拷贝INF文件(预安装到Driver Store中)
wprintf(L"Parameter 1 is %s\n",g_InfList[nInfIndex] ->asFullPath);
//getch();
//wprintf(L"Parameter 1 is %s\n",g_InfList[nInfIndex] ->asDesPath);
if(FALSE == SetupCopyOEMInf(g_InfList[nInfIndex]->asFullPath, NULL, SPOST_PATH,,
, ,
NULL, NULL))
{
printf("SetCopyOEMInf1 Error Code is %d\n",GetLastError()); if(GetLastError() == ERROR_FILE_EXISTS)
{
g_InfList[nInfIndex]->nResultInstall = ;
wprintf(L"located in inf dir's name:%s\n",g_InfList[nInfIndex]->asDesPath); PWCHAR pSubStr1,pSubWork1;
WCHAR OemFileName3[]; if(NULL != (pSubStr1 = wcsstr((wchar_t*)g_InfList[nInfIndex]->asDesPath,L"oem")))
{
pSubWork1 = pSubStr1; while((*pSubWork1) != 'f')
{
pSubWork1++;
} pSubWork1++; *pSubWork1 = '\0'; wcscpy(OemFileName3,pSubStr1); wprintf(L"OemFileName3 is %s\n",OemFileName3); //getch();
} if(SetupUninstallOEMInf(OemFileName3, SUOI_FORCEDELETE, NULL))
{
printf("new Driver Package Has Deleted succced! on windows XP\n"); if(FALSE == SetupCopyOEMInf(g_InfList[nInfIndex]->asFullPath, NULL, SPOST_PATH, SP_COPY_NOOVERWRITE,
g_InfList[nInfIndex]->asDesPath, MAX_PATH,
NULL, &g_InfList[nInfIndex]->asDesName))
{
printf("SetCopyOEMInf2 Error Code is %d\n",GetLastError());
}
else
printf("SetupCopyOEMInf2 succeed!\n"); //getch(); } }
else
g_InfList[nInfIndex]->nResultInstall = -;
}else
{ printf("Install Succeed!\n"); //getch();
g_InfList[nInfIndex]->nResultInstall = ;
} BOOL bResult = FALSE;
HDEVINFO DeviceInfoSet = INVALID_HANDLE_VALUE;
SP_DEVINFO_DATA DeviceInfoData;
GUID ClassGUID;
TCHAR ClassName[MAX_CLASS_NAME_LEN];
TCHAR hwIdList[LINE_LEN+];
DWORD Status; if (!SetupDiGetINFClass (g_InfList[nInfIndex]->asFullPath, &ClassGUID, ClassName, sizeof(ClassName)/sizeof(TCHAR), ) )
{
printf("SetupDiGetINFClass fail,Error Code is %d\n",GetLastError());
} DeviceInfoSet = SetupDiGetClassDevs(&ClassGUID,ClassName,NULL,DIGCF_PRESENT); if(DeviceInfoSet == INVALID_HANDLE_VALUE)
{
printf("SetupDiGetClassDevs fail,Error Code is %d\n",GetLastError());
} /*DWORD wIdx = 0; while (TRUE)
{
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
//找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息
if (SetupDiEnumDeviceInfo(DeviceInfoSet, wIdx, &DeviceInfoData))
{ printf("SetupDiEnumDeviceInfo Success!\n"); char Buffer[2048] = {0}; //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息
if (SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID,
0L, (PBYTE)Buffer, 2048, 0L))
{
printf("SetupDiGetDeviceRegistryProperty Success!\n"); wprintf(L"Buffer is %s\n",Buffer); if (!lstrcmpi(L"USB\\VID_0451&PID_AF32&REV_0000", (LPTSTR)Buffer))
{
printf("theHardware is matched!\n"); DWORD ConfigFlag; if(SetupDiGetDeviceRegistryProperty(DeviceInfoSet,&DeviceInfoData,SPDRP_CONFIGFLAGS,
0L,(PBYTE)&ConfigFlag,sizeof(ConfigFlag),0L))
{ ConfigFlag |= CONFIGFLAG_REINSTALL; SetupDiSetDeviceRegistryProperty(DeviceInfoSet,&DeviceInfoData,SPDRP_CONFIGFLAGS,
(PBYTE)&ConfigFlag,sizeof(ConfigFlag)); } if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32&REV_0000",
g_InfList[nInfIndex] ->asFullPath,INSTALLFLAG_FORCE,NULL))
{
printf("SetupDiGetINFClass fail,Error Code is %x\n",GetLastError());
} break;
} }
}
else
{ break;
} wIdx++;
} */ /*wprintf(L"ClassName is %s\n",ClassName); DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); if (!SetupDiCreateDeviceInfo(DeviceInfoSet, L"USB\\VID_0451&PID_AF32\\7LUCK", &ClassGUID, NULL, NULL, DICD_INHERIT_CLASSDRVS, &DeviceInfoData) )
{
printf("SetupDiCreateDeviceInfo fail,Error Code is %x\n",GetLastError());
} ZeroMemory (hwIdList, sizeof(hwIdList) ); lstrcpyn (hwIdList, L"USB\\VID_0451&PID_AF32", LINE_LEN); if (!SetupDiSetDeviceRegistryProperty (DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID, (LPBYTE)hwIdList,
( lstrlen (hwIdList) + 1 + 1) * sizeof (TCHAR) ) )
{
printf("SetupDiSetDeviceRegistryProperty fail,Error Code is %d\n",GetLastError()); } if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, DeviceInfoSet, &DeviceInfoData) )
{
printf("SetupDiCallClassInstaller fail,Error Code is %d\n",GetLastError());
}*/ /*if (!UpdateDriverForPlugAndPlayDevices(
NULL,
L"USB\\VID_0451&PID_AF32",
g_InfList[nInfIndex]->asFullPath,
INSTALLFLAG_FORCE,
NULL) )
{
printf("UpdateDriverForPlugAndPlayDevices,Error Code is %x\n",GetLastError());
}*/ //Return Value:0xe0000203指定设备不在当前系统,0xe000020b没为设备指定设备集
/*if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32",
g_InfList[nInfIndex]->asFullPath,INSTALLFLAG_FORCE,NULL))
{
。 printf("UpdateDriverForPlugAndPlayDevices Failed! Error Code is %x\n",GetLastError());
}*/ getch(); /*if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32",
g_InfList[nInfIndex]->asFullPath,INSTALLFLAG_FORCE,NULL))
{
printf("UpdateDriverForPlugAndPlayDevices Failed! Error Code is %x\n",GetLastError());
}*/ //getch(); for(int i = ; i < g_nHIDCount; i++)
{
if(g_HIDInfo[i]->nInfNum == nInfIndex)
{
g_HIDInfo[i]->nNumCone = ;
g_HIDInfo[i]->nNumNotCone = ;
g_HIDInfo[i]->bNeedUpdate = false;
}
} // 获取设备实例数
if(g_InfList[nInfIndex]->nResultInstall == && g_InfList[nInfIndex]->asClassName[])
{ wprintf(g_InfList[nInfIndex]->asClassName);
printf("\n"); // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES); // class名无效
if(dev_info == INVALID_HANDLE_VALUE){
printf("class 名无效\n");
continue;
} nDevIndex = ; // 枚举设备
dev_info_data.cbSize = sizeof(dev_info_data);
while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
{
// 取设备ID
if(SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
SPDRP_HARDWAREID,
NULL,
(BYTE *)tmp_id,
sizeof(tmp_id),
NULL))
{
//获得的是一个字符串列表,故而需要遍历
for(p = tmp_id; *p; p += (wcslen(p) + ))
{
_wcslwr(p);
for(int x = ; x < g_nHIDCount; x++)
{
if(g_HIDInfo[x]->nInfNum != nInfIndex)
continue; if(wcsstr(p, g_HIDInfo[x]->asHID)){
g_HIDInfo[x]->bNeedUpdate = true;// 此设备已存在,需要更新。
if(CM_Get_DevNode_Status(&status,
&problem,
dev_info_data.DevInst,
) == CR_NO_SUCH_DEVINST)
{
g_HIDInfo[x]->nNumNotCone++;
}
else
g_HIDInfo[x]->nNumCone++;
}
}
}
} nDevIndex++;
} SetupDiDestroyDeviceInfoList(dev_info);
} SetupDiDestroyDeviceInfoList(dev_info); }
} // 更新驱动程序
int UpdateDriver()
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
INFCONTEXT infcont;
HINF hInf = NULL;
DWORD config_flags, problem, status;
BOOL reboot;
char inf_path[MAX_PATH];
char id[MAX_PATH];
char tmp_id[MAX_PATH];
char *p;
int dev_index; dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA); __try
{
for(int i = ; i < g_nHIDCount; i++)
{
if(g_HIDInfo[i]->bWillBeUpdate)
{
if(g_HIDInfo[i]->nNumCone)
{
// 为当前连接到系统的所有设备更新驱动
g_HIDInfo[i]->bSuccess = UpdateDriverForPlugAndPlayDevices(NULL, g_HIDInfo[i]->asHID,
g_InfList[g_HIDInfo[i]->nInfNum]->asDesPath,
INSTALLFLAG_FORCE,
&reboot);
} if(g_HIDInfo[i]->nNumNotCone)
{
dev_index = ; // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES); if(dev_info == INVALID_HANDLE_VALUE)
continue; // 枚举设备
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
// 先取设备ID,判断是否是当前更新设备
if(SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
SPDRP_HARDWAREID, NULL,
(BYTE *)tmp_id,
sizeof(tmp_id),
NULL))
{
//获得的是一个字符串列表,故而需要遍历
for(p = tmp_id; *p; p += (strlen(p) + ))
{
strlwr(p); if(strstr(p, id))
{
// 判断此设备是不是当前未连接在系统
if(CM_Get_DevNode_Status(&status,
&problem,
dev_info_data.DevInst,
) == CR_NO_SUCH_DEVINST)
{
// 取当前配置值
if(SetupDiGetDeviceRegistryProperty(dev_info,
&dev_info_data,
SPDRP_CONFIGFLAGS,
NULL,
(BYTE *)&config_flags,
sizeof(config_flags),
NULL))
{
// 与CONFIGFLAG_REINSTALL或
config_flags |= CONFIGFLAG_REINSTALL; // 将新的配置值写入
SetupDiSetDeviceRegistryProperty(dev_info,
&dev_info_data,
SPDRP_CONFIGFLAGS,
(BYTE *)&config_flags,
sizeof(config_flags));
}
} // 找到一个即可,跳出。
break;
}
}
} dev_index++;
} SetupDiDestroyDeviceInfoList(dev_info);
}
}
} }
__finally
{
} return ;
} /////////////////////以下函数是移入的////////////////////////////////////// BOOL IsDeviceInstallInProgress (VOID)
{
return !(CM_WaitNoPendingInstallEvents() == WAIT_OBJECT_0);
} int RemoveDriver(_TCHAR *HardwareID)
{
HDEVINFO DeviceInfoSet;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i,err;
//GUID devGUID ={36fc9e60-c465-11cf-8056-444553540000}; DeviceInfoSet = SetupDiGetClassDevs(NULL, // All Classes
,
,
DIGCF_ALLCLASSES | DIGCF_PRESENT ); // All devices present on system if (DeviceInfoSet == INVALID_HANDLE_VALUE)
{
printf("GetClassDevs(All Present Devices)\n");
return ;
} //
// Enumerate through all Devices.
//
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=;SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData);i++)
{
DWORD DataT;
LPTSTR p,buffer = NULL;
DWORD buffersize = ; //
// We won't know the size of the HardwareID buffer until we call
// this function. So call it with a null to begin with, and then
// use the required buffer size to Alloc the nessicary space.
// Keep calling we have success or an unknown failure.
//
while (!SetupDiGetDeviceRegistryProperty(
DeviceInfoSet,
&DeviceInfoData,
SPDRP_HARDWAREID,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
//
// May be a Legacy Device with no HardwareID. Continue.
//
break;
}
else if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
//
// We need to change the buffer size.
//
if (buffer)
LocalFree(buffer);
buffer = (LPTSTR)LocalAlloc(LPTR,buffersize);
}
else
{
//
// Unknown Failure.
//
printf("GetDeviceRegistryProperty");
goto cleanup_DeviceInfo;
}
} if (GetLastError() == ERROR_INVALID_DATA)
continue; //
// Compare each entry in the buffer multi-sz list with our HardwareID. //
for (p = buffer; *p && (p < &buffer[buffersize]);p+=lstrlen(p)*sizeof(TCHAR) + ) {
//_tprintf(TEXT("Compare device ID: [%s]/n"),p); if (!_tcscmp(HardwareID,p))
{
//_tprintf(TEXT("Found! [%s]/n"),p); //
// Worker function to remove device.
//
//if (SetupDiCallClassInstaller(DIF_REMOVE,
// DeviceInfoSet,
// &DeviceInfoData)) if (SetupDiRemoveDevice(DeviceInfoSet, &DeviceInfoData)) {
printf("CallClassInstaller(REMOVE)\n");
}
else
printf("Remove Driver Fail\n");
break;
} //printf("TTTTTTTTTTTTTTTTT is %s\n",p);
//getch();
} if (buffer) LocalFree(buffer);
} if ((GetLastError()!=NO_ERROR)&&(GetLastError()!=ERROR_NO_MORE_ITEMS))
{
printf("EnumDeviceInfo\n");
} //
// Cleanup.
//
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(DeviceInfoSet); return err;
} VOID UninstallWDMDriver(LPCTSTR theHardware)
{ /* HKEY hKey;
//删除安装包inf,不然刷新设备会重新安装
if(INVALID_HANDLE_VALUE==(hKey = SetupDiOpenDevRegKey(hDevInfo,&spDevInfoData,DICS_FLAG_GLOBAL,0,
DIREG_DEV,KEY_ALL_ACCESS)))
{
printf("Open Key Has Failed.\n");
}*/ //RegGetValue(hKey,L"InfPath");
HKEY hKey[] = {};
DWORD type_1=REG_SZ;
BYTE buffer[] = {};
BYTE buffer2[] = {};
DWORD cbData_1=;
PWCHAR pSubStr = NULL;
PWCHAR pSubWork = NULL;
WCHAR SubKeyName[] = {};
DWORD SizeSubKeyName = sizeof(WCHAR)*;
DWORD Index = ;
WCHAR KeyPath[] = L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32";
//WCHAR constKeyPath[512] = L"SYSTEM\\CurrentControlSet\\Enum\\";
//wcscat(KeyPath,theHardware);
//wcscat(constKeyPath,theHardware);
WCHAR Path[] = L"MACHINE\\SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32";
//wcscat(Path,theHardware);
WCHAR DeleteKeyPath[] = L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32" ;
//wcscat(DeleteKeyPath,theHardware);
//WCHAR EndChar = 'f'; //if(ConfigRight(Path))
// printf("Set Right Success!\n"); //这里如果是KEY_ALL_ACCESS就会返回失败,以前尝试注册表提权ConfigRight失败。原因是无SYSTEM权限
//
if(ERROR_SUCCESS !=RegOpenKeyEx(HKEY_LOCAL_MACHINE,KeyPath,,KEY_ALL_ACCESS,&hKey[]))
printf("UninstallWDMDriver OpenKey Fail! error code is %d\n",GetLastError()); printf("OpenKey Success!\n"); //getch(); ZeroMemory(KeyPath,sizeof(WCHAR)*); //枚举子键 while(ERROR_SUCCESS == RegEnumKey(hKey[],Index,SubKeyName,SizeSubKeyName/*,NULL,NULL,NULL,NULL*/))
{ wcscpy(KeyPath,L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32");
wcscat(KeyPath,L"\\");
wcscat(KeyPath,SubKeyName); Index++; // ZeroMemory(buffer,sizeof(BYTE)*512);
//ZeroMemory(buffer2,sizeof(BYTE)*512);
// ZeroMemory(SubKeyName,SizeSubKeyName);
//ZeroMemory(KeyPath,sizeof(WCHAR)*512); if(ERROR_SUCCESS==RegOpenKeyEx(HKEY_LOCAL_MACHINE,KeyPath,,KEY_READ,&hKey[Index]))
printf("OpenKey Success!\n"); if( ERROR_SUCCESS==RegQueryValueEx(hKey[Index],L"DeviceDesc",NULL,&type_1,buffer,&cbData_1)) printf("Get Buffer1 Success!\n"); printf("%d\n",GetLastError()); if( ERROR_SUCCESS==RegQueryValueEx(hKey[Index],L"Mfg",NULL,&type_1,buffer2,&cbData_1))
printf("Get Buffer2 Success!\n"); printf("%d\n",GetLastError()); RegCloseKey(hKey[Index]); //搜索OEM文件 if(NULL == (pSubStr = wcsstr((wchar_t*)buffer,L"oem")))
{
printf("Search SubString_buffer Fail!\n"); if(NULL == (pSubStr = wcsstr((wchar_t*)buffer2,L"oem")))
{
printf("Search SubString_buffer2 Fail!\n"); ZeroMemory(buffer,sizeof(BYTE)*);
ZeroMemory(buffer2,sizeof(BYTE)*);
ZeroMemory(SubKeyName,SizeSubKeyName);
ZeroMemory(KeyPath,sizeof(WCHAR)*);
//KeyPath = NULL;
continue;
}
else
{
// ZeroMemory(buffer,sizeof(BYTE)*512);
//ZeroMemory(buffer2,sizeof(BYTE)*512);
//ZeroMemory(SubKeyName,SizeSubKeyName);
//ZeroMemory(KeyPath,sizeof(WCHAR)*512);
//KeyPath = NULL;
//continue; printf("Search Success!\n"); pSubWork = pSubStr; while((*pSubWork) != 'f')
{
pSubWork++;
} pSubWork++; *pSubWork = '\0'; WCHAR OemFileName1[]; wcscpy(OemFileName1,pSubStr); SP_DEVINFO_DATA spDevInfoData = {};
HDEVINFO hDevInfo = 0L;
WORD wIdx, wCount = ; //得到设备信息结构的句柄
hDevInfo = SetupDiGetClassDevs(0L, 0L, 0L, DIGCF_ALLCLASSES | DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
printf("Fail!\n");
return;
} wIdx = ;
while (TRUE)
{
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
//找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息
if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))
{
char Buffer[] = {}; //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,
0L, (PBYTE)Buffer, , 0L))
{
if (!lstrcmpi(theHardware, (LPTSTR)Buffer))
{
//从系统中删除一个注册的设备接口
if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))
printf("Remove Fail is %d!\n",GetLastError());
//if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
// printf("Remove Fail is %d!\n",GetLastError());
wCount++;
}
}
}
else
break;
wIdx++;
} if (wCount != )
_tprintf(_T("UnInstall Successed...\n")); //getch(); //wprintf("%s\n",(wchar_t*)pSubStr);
if(SetupUninstallOEMInf(OemFileName1, SUOI_FORCEDELETE, NULL))
printf("Driver Package Has Deleted succced!\n"); //销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo); /* for(int i = 0; i <= Index; i++)
{
RegCloseKey(hKey[i]);
}*/ /*if(ERROR_SUCCESS==RegDeleteTree(hKey[0],NULL))
{
printf("Registry Has Delete Success!\n");
return ;
}*/ RegCloseKey(hKey[]); DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath); //printf("Registry Has Delete Su",GetLastError()); return ;
}
}
else
{
// ZeroMemory(buffer,sizeof(BYTE)*512);
//ZeroMemory(buffer2,sizeof(BYTE)*512);
//ZeroMemory(SubKeyName,SizeSubKeyName);
//ZeroMemory(KeyPath,sizeof(WCHAR)*512);
//KeyPath = NULL;
//continue; printf("Search Success!\n"); pSubWork = pSubStr; while((*pSubWork) != 'f')
{
pSubWork++;
} pSubWork++; *pSubWork = '\0'; WCHAR OemFileName2[]; wcscpy(OemFileName2,pSubStr); SP_DEVINFO_DATA spDevInfoData = {};
HDEVINFO hDevInfo = 0L;
WORD wIdx, wCount = ; //得到设备信息结构的句柄
hDevInfo = SetupDiGetClassDevs(0L, 0L, 0L, DIGCF_ALLCLASSES | DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
printf("Fail!\n");
return;
} wIdx = ;
while (TRUE)
{
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
//找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息
if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))
{
char Buffer[] = {}; //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,
0L, (PBYTE)Buffer, , 0L))
{ printf("SetupDiGetDeviceRegistryProperty Success!\n"); if (!lstrcmpi(theHardware, (LPTSTR)Buffer))
{ //从系统中删除一个注册的设备接口
if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))
printf("Remove Fail is %d!\n",GetLastError());
//if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
// printf("Remove Fail is %d!\n",GetLastError()); wCount++;
} }
}
else
break;
wIdx++;
} if (wCount != )
_tprintf(_T("UnInstall Successed...\n")); // getch();
//wprintf("%s\n",(wchar_t*)pSubStr);
if(SetupUninstallOEMInf(OemFileName2, SUOI_FORCEDELETE, NULL))
printf("Driver Package Has Deleted succced!\n"); //销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo); /*for(int i = 0; i <= Index; i++)
{
RegCloseKey(hKey[i]);
}*/
//
/*if(ERROR_SUCCESS==RegDeleteTree(hKey[0],NULL))
{
printf("Registry Has Delete Success!\n");
return;
}*/ RegCloseKey(hKey[]); DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath); // printf("Registry Has Delete Fail! Error Code is %d\n",GetLastError()); return;
} } printf("Here is windows XP!\n"); //getch(); SP_DEVINFO_DATA spDevInfoData = {};
HDEVINFO hDevInfo = 0L;
WORD wIdx, wCount = ;
WCHAR oem_file_name[] = {};
//GUID usb_guid = {36fc9e60,c465,11cf,8056,444553540000};
//得到设备信息结构的句柄
hDevInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); if (hDevInfo == INVALID_HANDLE_VALUE)
{
printf("Fail!\n");
printf("SetupDiGetClassDevs Error Code is %d\n",GetLastError());
return;
} wIdx = ; printf("hDevInfo is %x\n",hDevInfo); while (TRUE)
{
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
//找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息
if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))
{ printf("SetupDiEnumDeviceInfo Success!\n"); char Buffer[] = {}; //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息
if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,
0L, (PBYTE)Buffer, , 0L))
{
printf("SetupDiGetDeviceRegistryProperty Success!\n"); wprintf(L"Buffer is %s\n",Buffer); if (!lstrcmpi(theHardware, (LPTSTR)Buffer))
{
printf("theHardware is matched!\n"); HKEY hDevKey;
BYTE buffer3[] = {};
DWORD buffer3_size = ;
//打开有关设备注册表
hDevKey = SetupDiOpenDevRegKey(hDevInfo,&spDevInfoData, DICS_FLAG_GLOBAL,,DIREG_DRV,KEY_ALL_ACCESS); if(hDevKey == INVALID_HANDLE_VALUE)
{
printf("SetupDiOpenRegKey Error Code is %d\n",GetLastError());
} if(ERROR_SUCCESS == RegQueryValueEx(hDevKey,L"InfPath",NULL,NULL,buffer3,&buffer3_size))
{
wprintf(L"Get Buffer3 Success! Buffer3 is %s\n",buffer3);
} wcscpy(oem_file_name,(wchar_t*)buffer3);
wprintf(oem_file_name);
printf("\n");
//getch();
RegCloseKey(hDevKey);
//从系统中删除一个注册的设备接口
/*if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))
{
printf("Remove Fail is %d!\n",GetLastError());
}*/ /*if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
printf("Remove Fail is %d!\n",GetLastError());*/
SP_REMOVEDEVICE_PARAMS rmdParams;
SP_DEVINSTALL_PARAMS devParams; rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
rmdParams.HwProfile = ; if(SetupDiSetClassInstallParams(hDevInfo, &spDevInfoData, &rmdParams.ClassInstallHeader, sizeof(rmdParams)) &&
SetupDiCallClassInstaller(DIF_REMOVE, hDevInfo, &spDevInfoData))
{ }
wCount++;
} }
}
else
{ break;
} wIdx++;
} if (wCount != )
_tprintf(_T(" UnInstall Successed on windows XP...\n")); if(SetupUninstallOEMInf(oem_file_name, SUOI_FORCEDELETE, NULL))
printf("Driver Package Has Deleted succced! on windows XP\n"); //getch(); //销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo); //递归删除DeleteKeyPath下子键
/*DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath); HKEY hKey2;//删除DeleteKeyPath键本身 if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE,DeleteKeyPath,0,KEY_ALL_ACCESS,&hKey2))
{
printf("Can not Open Key!(Delete part!) Error Code is %d\n",GetLastError());
return ;
} RegDeleteKey(hKey2,DeleteKeyPath); RegCloseKey(hKey2);*/ //InitialGlobalVar();
return;
} BOOL UnicodeToAnsi(LPCWSTR Source, const WORD wLen, LPSTR Destination, const WORD sLen)
{
return WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, Source, wLen, Destination,
sLen, 0L, 0L);
} BOOL AnsiToUnicode(LPCSTR Source, const WORD sLen, LPWSTR Destination, const WORD wLen)
{
return MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Source, sLen, Destination, wLen);
} /*BOOL GetINFData(FILE *pFile)
{
WORD wLoop; if (!g_wVender || !g_wHardware)
InitialGlobalVar();
if (GetSectionData(pFile, "[Manufacturer]", TRUE) == FALSE)
return FALSE; //rewind(pFile); for (wLoop = 0; wLoop < g_wVender; wLoop++)
{
CHAR szVender[64] = {0};
UnicodeToAnsi(g_strVender[wLoop], _tcslen(g_strVender[wLoop]), szVender, 64);
GetSectionData(pFile, "Device.NTamd64", FALSE);
}
if (g_wHardware != 0)
{
if (IsInstalled() == TRUE)//如果已经安装
return FALSE;
else
return TRUE;
}
return FALSE;
} */ /*VOID InitialGlobalVar()
{
WORD wLoop; g_wVender = g_wHardware = 0;
for (wLoop = 0; wLoop < 20; wLoop++)
{
RtlZeroMemory(g_strVender[wLoop], sizeof(TCHAR)*64);
RtlZeroMemory(g_strHardware[wLoop], sizeof(TCHAR)*64);
}
} */ VOID FindComma(LPSTR szData)
{
WORD wLen = (WORD)strlen(szData);
WORD wIdx;
WORD wLoop;
CHAR szTmp[] = {}; for (wIdx = , wLoop = ; wLoop < wLen; wLoop++)
{
if (szData[wLoop] == ',')
szData[wLoop] = '.';
else if (szData[wLoop] == ' ')
continue;
szTmp[wIdx++] = szData[wLoop];
}
memcpy(szData, szTmp, wIdx*sizeof(char));
szData[wIdx] = ;
} VOID StrLTrim(LPSTR szData)
{
LPSTR ptr = szData;
//判断是否为空格
while (isspace(*ptr))
ptr++; if (strcmp(ptr, szData))
{
WORD wLen = (WORD)(strlen(szData) - (ptr - szData));
memmove(szData, ptr, (wLen+)*sizeof(char));
}
} VOID StrRTrim(LPSTR szData)
{
LPSTR ptr = szData;
LPSTR pTmp = NULL; //debug模式下 使用isspace判断中文 需要设置编码
#if defined(WIN32) && defined(_DEBUG)
char* locale = setlocale( LC_ALL, ".OCP" );
#endif while (*ptr != )
{
//判断是否为空格
if (isspace(*ptr))
{
if (!pTmp)
pTmp = ptr;
}
else
pTmp = NULL;
ptr++;
} if (pTmp)
{
*pTmp = ;
memmove(szData, szData, strlen(szData) - strlen(pTmp));
}
} //从字符串右边开始截取字符串
VOID StrRight(LPSTR szData, WORD wCount)
{
WORD wLen = (WORD)strlen(szData) - wCount; if (wCount > 0x7FFF)//负数
wCount = ;
if (wCount >= (WORD)strlen(szData))
return; memmove(szData, szData + wLen, wCount * sizeof(char));
szData[wCount] = ;
} VOID ConvertGUIDToString(const GUID guid, LPSTR pData)
{
CHAR szData[] = {};
CHAR szTmp[] = {};
WORD wLoop; sprintf_s(pData, _countof(szData), "%04X-%02X-%02X-", guid.Data1, guid.Data2, guid.Data3);
for (wLoop = ; wLoop < ; wLoop++)
{
if (wLoop == )
strcat_s(szData, "-");
sprintf_s(szTmp, _countof(szTmp), "%02X", guid.Data4[wLoop]);
strcat_s(szData, szTmp);
} memcpy(pData + strlen(pData), szData, strlen(szData));
} /*BOOL IsInstalled()
{
HDEVINFO hDevInfo = 0L;
SP_DEVINFO_DATA spDevInfoData = {0L};
WORD wIdx;
BOOL bIsFound; //得到设备信息结构的句柄
hDevInfo = SetupDiGetClassDevs(0L, 0, 0, DIGCF_ALLCLASSES | DIGCF_PRESENT);
if (hDevInfo == INVALID_HANDLE_VALUE)
{
printf("SetupDiGetClassDevs is %d",GetLastError());
return FALSE;
} spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
wIdx = 0;
bIsFound = 0;
while (++wIdx)
{
//找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息
if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))
{
LPTSTR ptr;
LPBYTE pBuffer = NULL;
DWORD dwData = 0L;
DWORD dwRetVal;
DWORD dwBufSize = 0L; while (TRUE)
{
//可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息
dwRetVal = SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,
&dwData, (PBYTE)pBuffer, dwBufSize, &dwBufSize);
if (!dwRetVal)
dwRetVal = GetLastError();
else
break;
if (dwRetVal == ERROR_INVALID_DATA)
break;
else if (dwRetVal == ERROR_INSUFFICIENT_BUFFER)
{
if (pBuffer)
LocalFree(pBuffer);
pBuffer = (LPBYTE)LocalAlloc(LPTR, dwBufSize);
}
else
{
printf("SetupDiGetDeviceRegistryProperty is %d",dwRetVal);
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
return FALSE;
}
} if (dwRetVal == ERROR_INVALID_DATA)
continue; for (ptr = (LPTSTR)pBuffer; *ptr && (ptr < (LPTSTR)&pBuffer[dwBufSize]); ptr += _tcslen(ptr) + sizeof(TCHAR))
{
WORD wLoop; for (wLoop = 0; wLoop < g_wHardware; wLoop++)
{
if (!_tcscmp(g_strHardware[wLoop], ptr))
{
bIsFound = TRUE;
break;
}
}
}
if (pBuffer)
LocalFree(pBuffer);
if (bIsFound)
break;
}
}
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
return bIsFound;
} */ //寻找指定的节名 如果找到返回TRUE 反之返回FALSE
BOOL FindSectionName(FILE *pFile, const char *szKey)
{
char szData[] = {}; if (!pFile)
return FALSE; //将文件内部的位置指针重新指向一个流(数据流/文件)的开头
rewind(pFile);
//循环读取文件内容
while (!feof(pFile))
{
//读取一行
fgets(szData, , pFile);
//去除前后空格
StrLTrim(szData);
StrRTrim(szData); if (strcmp(szKey, szData) == )
return TRUE;
}
return FALSE;
} //得到INF文件中节的数量
/*BOOL GetSectionData(FILE* pFile, const char* szKey, const char bIsVender)
{
char szData[128] = {0}; if (bIsVender)
strcpy_s(szData, szKey);
else
sprintf_s(szData, _countof(szData), "[%s]", szKey); if (FindSectionName(pFile, szData) == FALSE)
return FALSE; RtlZeroMemory(szData, sizeof(char)*128);
while (!feof(pFile))
{
char *str = NULL;
fgets(szData, 127, pFile);
szData[strlen(szData)-1] = 0;
StrLTrim(szData);
StrRTrim(szData);
if (!*szData)
continue;
if (szData[0] == ';')
continue; if (strchr(szData, '['))
{
StrLTrim(szData);
if (szData[0] != ';')
return 1;
else
continue;
} if (bIsVender)
str = strchr(szData, '=');
else
str = strchr(szData, ','); if (*str)
{
char szTmp[128] = {0};
WORD pos = (WORD)(str - szData + 1); StrRight(szData, (short)(strlen(szData)-pos));
StrLTrim(szData);
StrRTrim(szData);
FindComma(szData);
if (bIsVender)
{
AnsiToUnicode(szData, strlen(szData), g_strVender[g_wVender++], 64);
}
else
{
AnsiToUnicode(szData, strlen(szData), g_strHardware[g_wHardware++], 64);
}
} //end if
}
return TRUE;
} */ //实质性的安装驱动
BOOL InstallClassDriver(LPCTSTR theINFName)
{
GUID guid = {};
SP_DEVINFO_DATA spDevData = {};
HDEVINFO hDevInfo = 0L;
TCHAR className[MAX_CLASS_NAME_LEN] = {};
LPTSTR pHID = NULL;
WORD wLoop;
BOOL bRebootRequired; //取得此驱动的GUID值 ,className也是输出参数
if (!SetupDiGetINFClass(theINFName, &guid, className, MAX_CLASS_NAME_LEN, ))
{
printf( "SetupDiGetINFClass is %d\n",GetLastError());
return FALSE;
} //创建设备信息块列表
hDevInfo = SetupDiCreateDeviceInfoList(&guid, );
if (hDevInfo == INVALID_HANDLE_VALUE)
{
printf("SetupDiCreateDeviceInfoList is %d\n",GetLastError());
return FALSE;
} spDevData.cbSize = sizeof(SP_DEVINFO_DATA);
//创建设备信息块
if (!SetupDiCreateDeviceInfo(hDevInfo, className, &guid, 0L, 0L, DICD_GENERATE_ID, &spDevData))
{
printf("SetupDiCreateDeviceInfo is %d",GetLastError());
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
return FALSE;
} // for (wLoop = 0; wLoop < g_wHardware; wLoop++)
//{
if (pHID)
LocalFree(pHID); pHID = (LPTSTR)LocalAlloc(LPTR, _tcslen(L"USB\\VID_0451&PID_AF32")**sizeof(TCHAR));
if (!pHID)
{
printf("LocalAlloc is %d",GetLastError());
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
return FALSE;
} _tcscpy_s(pHID, _tcslen(L"USB\\VID_0451&PID_AF32")*,
L"USB\\VID_0451&PID_AF32");
//设定硬件ID
if (!SetupDiSetDeviceRegistryProperty(hDevInfo, &spDevData, SPDRP_HARDWAREID, (PBYTE)pHID,
(DWORD)(_tcslen(L"USB\\VID_0451&PID_AF32")**sizeof(TCHAR))))
{
printf("SetupDiSetDeviceRegistryProperty is %d",GetLastError());
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
LocalFree(pHID);
return FALSE;
}
//调用相应的类程序来注册设备
if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, hDevInfo, &spDevData))
{
printf("SetupDiCallClassInstaller is %d", GetLastError());
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
LocalFree(pHID);
return FALSE;
} bRebootRequired = FALSE;
//安装更新和硬件ID相匹配的驱动程序
if (!UpdateDriverForPlugAndPlayDevices(0L, L"USB\\VID_0451&PID_AF32"
, theINFName,
INSTALLFLAG_FORCE, &bRebootRequired))
{
DWORD dwErrorCode = GetLastError();
//调用相应的类程序来移除设备
if (!SetupDiCallClassInstaller(DIF_REMOVE, hDevInfo, &spDevData))
printf("SetupDiCallClassInstaller(Remove) is %d",GetLastError());
printf("UpdateDriverForPlugAndPlayDevices is %d",(WORD)dwErrorCode);
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
LocalFree(pHID); //getch();
return FALSE;
}
LocalFree(pHID);
pHID = NULL; // }
//销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo);
_tprintf(_T("Install Successed\n"));
return TRUE;
} // 安装WDM驱动的测试工作
BOOL StartInstallWDMDriver(LPCTSTR theInfName)
{
HDEVINFO hDevInfo = 0L;
GUID guid = {0L};
SP_DEVINSTALL_PARAMS spDevInst = {0L};
TCHAR strClass[MAX_CLASS_NAME_LEN] = {0L}; //取得此驱动的GUID值
if (!SetupDiGetINFClass(theInfName, &guid, strClass, MAX_CLASS_NAME_LEN, ))
{
printf("SetupDiGetINFClass is %d",GetLastError());
return FALSE;
} //得到设备信息结构的句柄
hDevInfo = SetupDiGetClassDevs(&guid, 0L, 0L, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_PROFILE);
if (!hDevInfo)
{
printf("SetupDiGetClassDevs is %d",GetLastError());
return FALSE;
} spDevInst.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
//获得指定设备的安装信息
if (!SetupDiGetDeviceInstallParams(hDevInfo, 0L, &spDevInst))
{
printf("SetupDiGetDeviceInstallParams is %d",GetLastError());
return FALSE;
} spDevInst.Flags = DI_ENUMSINGLEINF;
spDevInst.FlagsEx = DI_FLAGSEX_ALLOWEXCLUDEDDRVS;
_tcscpy_s(spDevInst.DriverPath, _countof(spDevInst.DriverPath), theInfName); //为设备信息集或者是一个实际的设备信息单元设置或清除类安装参数
if (!SetupDiSetDeviceInstallParams(hDevInfo, , &spDevInst))
{ printf("SetupDiSetDeviceInstallParams is %d",GetLastError());
return FALSE;
} //获取这个设备的驱动程序信息列表
if (!SetupDiBuildDriverInfoList(hDevInfo, , SPDIT_CLASSDRIVER))
{ printf("SetupDiDeviceInstallParams is %d",GetLastError());
return FALSE;
} //销毁一个设备信息集合
SetupDiDestroyDeviceInfoList(hDevInfo); //进入安装设备驱动函数
return InstallClassDriver(theInfName);
} BOOL FindExistingDevice(IN LPTSTR HardwareId)
{
HDEVINFO DeviceInfoSet;
SP_DEVINFO_DATA DeviceInfoData;
DWORD i,err;
BOOL Found; //
// Create a Device Information Set with all present devices.
//
DeviceInfoSet = SetupDiGetClassDevs(NULL, // All Classes
,
,
DIGCF_ALLCLASSES | DIGCF_PRESENT ); // All devices present on system if (DeviceInfoSet == INVALID_HANDLE_VALUE)
{
return printf("GetClassDevs(All Present Devices)"); } //_tprintf(TEXT("Search for Device ID: [%s]/n"),HardwareId); //
// Enumerate through all Devices.
//
Found = FALSE;
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=;SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData);i++)
{
DWORD DataT;
LPTSTR p,buffer = NULL;
DWORD buffersize = ; //
// We won't know the size of the HardwareID buffer until we call
// this function. So call it with a null to begin with, and then
// use the required buffer size to Alloc the nessicary space.
// Keep calling we have success or an unknown failure.
//
while (!SetupDiGetDeviceRegistryProperty(
DeviceInfoSet,
&DeviceInfoData,
SPDRP_HARDWAREID,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INVALID_DATA)
{
//
// May be a Legacy Device with no HardwareID. Continue.
//
break;
}
else if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
//
// We need to change the buffer size.
//
if (buffer)
LocalFree(buffer);
buffer = (LPTSTR)LocalAlloc(LPTR,buffersize);
}
else
{
//
// Unknown Failure.
//
printf("GetDeviceRegistryProperty");
goto cleanup_DeviceInfo;
}
} if (GetLastError() == ERROR_INVALID_DATA)
continue; //
// Compare each entry in the buffer multi-sz list with our HardwareID. //
for (p=buffer;*p&&(p<&buffer[buffersize]);p+=lstrlen(p)+sizeof(TCHAR)) {
//_tprintf(TEXT("Compare device ID: [%s]/n"),p); if (!_tcscmp(HardwareId,p))
{
//_tprintf(TEXT("Found! [%s]/n"),p);
Found = TRUE;
break;
}
} if (buffer) LocalFree(buffer);
if (Found) break;
} if (GetLastError() != NO_ERROR)
{
printf("EnumDeviceInfo");
} //
// Cleanup.
//
cleanup_DeviceInfo:
err = GetLastError();
SetupDiDestroyDeviceInfoList(DeviceInfoSet);
SetLastError(err); return err == NO_ERROR; //???
} BOOL ConfigRight(WCHAR* szPath)
{
if (szPath == NULL)
{
return FALSE;
}
/*BOOL bRet = TRUE; SE_OBJECT_TYPE objectType;
PACL newDACL;
objectType = SE_REGISTRY_KEY; if (SetEntriesInAclW(0, NULL, NULL, &newDACL) != ERROR_SUCCESS)
{
return FALSE;
} DWORD dwRet = 0; EXPLICIT_ACCESSW ea;
memset(&ea, 0, sizeof(EXPLICIT_ACCESS)); BuildExplicitAccessWithNameW(&ea,L"Everyone", KEY_ALL_ACCESS, SET_ACCESS, SUB_CONTAINERS_AND_OBJECTS_INHERIT); if (SetEntriesInAclW(1, &ea, NULL, &newDACL) != ERROR_SUCCESS)
{
bRet = FALSE;
goto Clean_Up;
}
DWORD ret; //调用失败,访问被拒绝
if (ERROR_SUCCESS!= (ret = SetNamedSecurityInfoW(szPath, objectType, DACL_SECURITY_INFORMATION, NULL, NULL, newDACL, NULL)))
{
bRet = FALSE;
printf("ret value is %d\n",ret);
goto Clean_Up;
} Clean_Up:
if (newDACL != NULL)
{
LocalFree((HLOCAL)newDACL);
}*/
PACL pOldDacl=NULL;
PACL pNewDacl=NULL;
DWORD dRet;
EXPLICIT_ACCESS eia;
PSECURITY_DESCRIPTOR pSID=NULL; dRet = GetNamedSecurityInfo(szPath,SE_REGISTRY_KEY,DACL_SECURITY_INFORMATION,NULL,NULL,&pOldDacl,NULL,&pSID);// 获取SAM主键的DACL if(dRet!=ERROR_SUCCESS)
{
return ;
}
//创建一个ACE,允许Everyone组成员完全控制对象,并允许子对象继承此权限
ZeroMemory(&eia,sizeof(EXPLICIT_ACCESS));
BuildExplicitAccessWithName(&eia,L"SYSTEM",KEY_ALL_ACCESS,SET_ACCESS,SUB_CONTAINERS_AND_OBJECTS_INHERIT);
// 将新的ACE加入DACL
dRet = SetEntriesInAcl(,&eia,pOldDacl,&pNewDacl);
if(dRet!=ERROR_SUCCESS)
{
return ;
}
// 更新SAM主键的DACL
dRet = SetNamedSecurityInfo(szPath,SE_REGISTRY_KEY,DACL_SECURITY_INFORMATION,NULL,NULL,pNewDacl,NULL); if(dRet!=ERROR_SUCCESS)
{
printf("%d\n",dRet);
return ;
}
//return bRet;
} DWORD DeleteTree(HKEY RootKey, const WCHAR *pSubKey)
{ HKEY hKey;
DWORD nRet;
DWORD NameCnt,NameMaxLen;
DWORD KeyCnt,KeyMaxLen,MaxDateLen;
//static WCHAR sFormat[256] = L"";
//wcscat(sFormat, L"----"); static int dwDeep = -;
dwDeep++; nRet=RegOpenKeyEx(RootKey,pSubKey,,KEY_ALL_ACCESS,&hKey);
if(nRet!=ERROR_SUCCESS)
{
printf("Can not Open Key!(Delete part!) Error Code is %d\n",GetLastError());
return ;
} nRet = RegQueryInfoKey(hKey,NULL,NULL,NULL,&KeyCnt,&KeyMaxLen,NULL,&NameCnt,
&NameMaxLen,&MaxDateLen,NULL,NULL); if(nRet == ERROR_SUCCESS)
{
printf("RegQueryInfoKey Success!\n"); for(int dwIndex = KeyCnt - ; dwIndex >= ; dwIndex--) //枚举键值
{
WCHAR sKeyName[] = {};
RegEnumKey(hKey, dwIndex, sKeyName, sizeof(sKeyName)); HKEY hKeySub;
DWORD KeyCntSub;
WCHAR pSubKeyTemp[] = {};
wcscpy(pSubKeyTemp, pSubKey);
wcscat(pSubKeyTemp, L"\\");
wcscat(pSubKeyTemp, sKeyName); nRet = RegOpenKeyEx(RootKey,pSubKeyTemp,,KEY_ALL_ACCESS,&hKeySub); if(nRet == ERROR_SUCCESS)
{
printf("RegOpenKeyEx Success!\n"); nRet = RegQueryInfoKey(hKeySub,NULL,NULL,NULL,&KeyCntSub,&KeyMaxLen,NULL,&NameCnt,
&NameMaxLen,&MaxDateLen,NULL,NULL); if(nRet == ERROR_SUCCESS)
{
if (KeyCntSub != )
{
DeleteTree(RootKey, pSubKeyTemp);
} RegCloseKey(hKeySub);
}
} // cout << sFormat << sKeyName << endl; RegDeleteKey(RootKey ,pSubKeyTemp);
} RegCloseKey(hKey);
} // sFormat[strlen(sFormat) - 4] = 0; if (dwDeep == )
{
RegDeleteKey(RootKey ,pSubKey);
} return ;
} VOID SearchRegistryHardID(PWCHAR pHardIDBuffer)
{
const PWCHAR pReg = L"SYSTEM\\CurrentControlSet\\Enum\\USB";
HKEY hKey; if(ERROR_SUCCESS !=RegOpenKeyEx(HKEY_LOCAL_MACHINE,pReg,,KEY_ALL_ACCESS,&hKey))
printf("in SearchOpenKey Fail! error code is %d\n",GetLastError()); DWORD Index = ;
WCHAR SubKeyName[] = {}; while(ERROR_SUCCESS == RegEnumKey(hKey,Index,SubKeyName,sizeof(WCHAR)*))
{
if(!lstrcmpi(SubKeyName,L"VID_0451&PID_AF32"))
{
wcscpy(pHardIDBuffer,L"VID_0451&PID_AF32");
RegCloseKey(hKey);
return;
} else if(!lstrcmpi(SubKeyName,L"VID_04B41&PID_8613"))
{
wcscpy(pHardIDBuffer,L"VID_04B41&PID_8613");
RegCloseKey(hKey);
return;
} else if(!lstrcmpi(SubKeyName,L"VID_0547&PID_1002"))
{
wcscpy(pHardIDBuffer,L"VID_0547&PID_1002");
RegCloseKey(hKey);
return;
} ZeroMemory(SubKeyName,sizeof(WCHAR)*); Index++;
} }

Setup.cpp

 // InstallWDFDriver.cpp : Defines the entry point for the console application.
// #include "stdafx.h"
#include "setup.h"
#include "Shlwapi.h" #pragma comment(lib,"Shlwapi.lib") BOOL SystemShutdown(); int _tmain(int argc, _TCHAR* argv[])
{
WCHAR Wlp_USB_PATH[] = L"C:\\Windows\\System32\\drivers\\WLP_USB_Driver.sys";
//WCHAR Wdf_USB_PATH[] = L"C:\\Windows\\System32\\drivers\\CYUSB3.sys";
WCHAR New_Inf_Path[] = L"D:\\wlp driver\\WDF Driver _new\\win7\\x64\\cyusb3.inf";
WCHAR InfFileName[] = L"\\cyusb3.inf";
CHAR szInfPath[] = {};
FILE *fp = NULL; WCHAR CurrentDirBuffer[] = {};
WCHAR OutCurrentDirBuffer[] = {}; GetModuleFileName(NULL,CurrentDirBuffer,_countof(CurrentDirBuffer));
//GetCurrentDirectory(215,CurrentDirBuffer);
//lstrcat(CurrentDirBuffer, InfFileName);
_wsplitpath_s(CurrentDirBuffer,NULL,,OutCurrentDirBuffer,_countof(OutCurrentDirBuffer),
NULL,,NULL,);
printf("This Process is Driver Installtion Program...\n"); //getch();
//WCHAR HIDBuffer[128] = {0}; if(PathFileExists(Wlp_USB_PATH))
{
printf("Exists WLP_USB_Driver.sys!\n"); //SearchRegistryHardID(HIDBuffer); //WCHAR HardID[215] = L"USB\\"; //wcscat(HardID,HIDBuffer);
//getch(); UninstallWDMDriver(L"USB\\VID_0451&PID_AF32&REV_0000"); if(DeleteFile(Wlp_USB_PATH))
{
printf("WLP_USB_Driver.sys File has Deleted!\n");
} // getch(); /* if(FindExistingDevice(L"USB\\VID_0451&PID_AF32&REV_0000"))
{
printf("找打了!\n"); getch();
}
else
{
printf("没找到!\n");
getch();
}*/ printf("Get Started Install the New DLF Driver...\n"); // RemoveDriver(L"USB\\VID_0451&PID_AF32&REV_0000");
while(IsDeviceInstallInProgress())
{
printf("Has Driver Installtion Program is Processing!\n");
} printf("Get Started analyse inf File!\n"); UnicodeToAnsi(New_Inf_Path, _tcslen(New_Inf_Path), szInfPath, ); FindAllInfFiles(OutCurrentDirBuffer/* L"D:\\wlp driver\\WDF Driver _new\\win7\\x64"*/); for(int i = ; i < g_nHIDCount; i++)
g_HIDInfo[i]->bNeedUpdate = false; for(int i = ; i < g_nInfCount; i++)
g_InfList[i]->bWillBeInstall = false; int SearchInfIndex = ; while(SearchInfIndex < g_nInfCount)
{
if(g_InfList[SearchInfIndex] != NULL)
{
g_InfList[SearchInfIndex]->bWillBeInstall = TRUE;
} SearchInfIndex++;
} InstallDriver(); //UpdateDriver();
printf("Install Successed!\n");
//if ((fopen_s(&fp, szInfPath, "r"))!=0)
//{
// _tprintf(_T("can not open file %s\n"), CurrentDirBuffer);
//return 0;
//} // GetINFData(fp);
// fclose(fp); // 安装WDM驱动 /*if (StartInstallWDMDriver(New_Inf_Path) == FALSE)
{
_tprintf(_T("Start Install WDF Driver failed\n"));
getch();
return 0;
} */ /*if(IDOK == MessageBox(NULL,L"Need to Restart the System to Complete Installation!",
L"Tip",MB_OK))
{
if(SystemShutdown())
{
printf("ShutDown the System And Restart the System!\n");
} }*/ //getch(); printf("Press any key to continue!\n"); }
else
{
printf("No Exists WLP_USB_Driver.sys!\n"); //getch(); UninstallWDMDriver(L"USB\\VID_0451&PID_AF32&REV_0000"); printf("Get Started Install the New DLF Driver...\n"); printf("Get Started analyse inf File!\n"); UnicodeToAnsi(New_Inf_Path, _tcslen(New_Inf_Path), szInfPath, ); /*if ((fopen_s(&fp, szInfPath, "r"))!=0)
{
_tprintf(_T("can not open file %s\n"), CurrentDirBuffer);
return 0;
} */ // GetINFData(fp);
//fclose(fp); // 安装WDM驱动 /*if (StartInstallWDMDriver(New_Inf_Path) == FALSE)
{
_tprintf(_T("Start Install WDF Driver failed\n"));
getch();
return 0;
} */ FindAllInfFiles( OutCurrentDirBuffer/*L"D:\\wlp driver\\WDF Driver _new\\win7\\x64"*/); for(int i = ; i < g_nHIDCount; i++)
g_HIDInfo[i]->bNeedUpdate = false; for(int i = ; i < g_nInfCount; i++)
g_InfList[i]->bWillBeInstall = false; int SearchInfIndex = ; while(SearchInfIndex < g_nInfCount)
{
if(g_InfList[SearchInfIndex] != NULL)
{
g_InfList[SearchInfIndex]->bWillBeInstall = TRUE;
} SearchInfIndex++;
} InstallDriver(); printf("Install Successed!\n"); /*if(IDOK == MessageBox(NULL,L"Need to Restart the System to Complete Installation!",
L"Tip",MB_OK))
{
if(SystemShutdown())
{
printf("ShutDown the System And Restart the System!\n");
} }*/ //getch(); printf("Press any key to continue!\n"); } return ;
} BOOL SystemShutdown()
{
HANDLE hToken; TOKEN_PRIVILEGES tkp;
/* OpenProcessToken() 这个函数的作用是打开一个进程的访问令牌
GetCurrentProcess() 函数的作用是得到本进程的句柄*/
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hToken))
return FALSE;
// LookupPrivilegeValue() 的作用是修改进程的权限
LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,
&tkp.Privileges[].Luid);
tkp.PrivilegeCount = ; // one privilege to set 赋给本进程特权
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED;
// AdjustTokenPrivileges()的作用是通知Windows NT修改本进程的权利
AdjustTokenPrivileges(hToken, FALSE, &tkp, ,
(PTOKEN_PRIVILEGES)NULL, ); if (GetLastError() != ERROR_SUCCESS) //失败
return FALSE; if (!ExitWindowsEx(EWX_REBOOT, )) //参数在这里设置。强行退出WINDOWS(EWX_FORCE)。
return FALSE;
return TRUE;
}

main.cpp

附加产物:

发现MSDN的代码样例中由实现设备管理器功能的命令行工具

https://code.msdn.microsoft.com/DevCon-Sample-4e95d71c#content

windows设备驱动安装接口(自己仿写)的更多相关文章

  1. Linux和Windows设备驱动架构比较

    毕业后一直在学操作系统, 有时候觉得什么都懂了,有时候又觉得好像什么都不懂,但总体来说自认为对操作系统实现机制的了解比周围的人还是要多一些.去年曾花了几个星期的晚上时间断断续续翻译了这篇对Linux和 ...

  2. windows设备驱动安装指南

    高观点下的设备驱动安装(overview) 一.windows是怎样安装设备的? 第一步:新设备的识别 在给一个新设备安装驱动之前,总线或集线器(hub)驱动会为连接到PC上的设备分配一个硬件ID(h ...

  3. Windows 2008驱动安装失败的原因及解决方法

    希望这些内容能够帮助各位朋友顺利地在Windows Server 2008系统环境下安装使用好各种设备的驱动程序! 寻找安装失败原因 一般来说,当我们将目标设备的驱动安装光盘正确放置到Windows ...

  4. 关于windows 设备驱动重要的事实

    1. windows采用设备树描述所有挂在系统总线上的设备,每个设备对应一个节点. 2.每个设备有自己的device object stack/driver stack. 一个物理上的设备对应多个de ...

  5. linux设备驱动第三篇:写一个简单的字符设备驱动

          在linux设备驱动第一篇:设备驱动程序简介中简单介绍了字符驱动,本篇简单介绍如何写一个简单的字符设备驱动.本篇借鉴LDD中的源码,实现一个与硬件设备无关的字符设备驱动,仅仅操作从内核中分 ...

  6. Linux与Windows的设备驱动模型对比

    Linux与Windows的设备驱动模型对比 名词缩写: API 应用程序接口(Application Program Interface ) ABI 应用系统二进制接口(Application Bi ...

  7. Windows Server 2008驱动安装全攻略

    安装设备驱动程序原本是一件非常简单的事情,很多驱动程序在安装的时候我们只要不停单击“下一步”按钮,就能让驱动程序顺利地在对应计算机系统“落户”;不过,当身边的计算机系统升级为Windows Serve ...

  8. 字符设备驱动、平台设备驱动、设备驱动模型、sysfs的比较和关联

    转载自:http://www.kancloud.cn/yueqian_scut/emlinux/106829 学习Linux设备驱动开发的过程中自然会遇到字符设备驱动.平台设备驱动.设备驱动模型和sy ...

  9. (笔记)linux设备驱动--LED驱动

    linux设备驱动--LED驱动 最近正在学习设备驱动开发,因此打算写一个系列博客,即是对自己学习的一个总结,也是对自己的一个督促,有不对,不足,需要改正的地方还望大家指出,而且希望结识志同道合的朋友 ...

随机推荐

  1. HDOJ 1070 Milk(水题,考英文的)

    Problem Description Ignatius drinks milk everyday, now he is in the supermarket and he wants to choo ...

  2. poj2955:括号匹配,区间dp

    题目大意: 给一个由,(,),[,]组成的字符串,其中(),[]可以匹配,求最大匹配数 题解:区间dp: dp[i][j]表示区间 [i,j]中的最大匹配数 初始状态 dp[i][i+1]=(i,i+ ...

  3. 简单的新闻客户端APP开发(DCloud+thinkphp+scrapy)

    前端时间花了1个月左右,搞了个新闻APP,功能很简单,就是把页面版的新闻条目定时爬到后台数据库,然后用app显示出来. 1.客户端 使用了DCloud框架,js基本是个新手,从没写过像样的代码,htm ...

  4. jQuery效果---隐藏与显示

    隐藏与显示 index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"& ...

  5. MyBatis第一个项目示例

    1.创建一个Java project,JikeBook 2.添加项目所需的依赖包 如 mybatis-3.2.8.jar,是实现mybatis功能所必需的依赖包 mysql-connector-jav ...

  6. 【微信H5支付】微信公众号里H5网页点击调取微信支付

    最近在公众号里开发了下单支付H5网页,需要在H5里调用微信支付界面.开发思路和代码整理如下: todo...

  7. openwrt上网配置的一些理解(二)

    上一篇里面遇到了只能静态上网的问题,动态不行.所以再接再励,问题总是要解决的,偷懒的下场就是一直停留在菜鸟的水平. 首先分析下问题,要动态上网,首先我要明确不是动态获取不了IP,是获取了,上不了外网. ...

  8. 在VM中安装Android4.4连接小米手环 之 在VM中安装Android4.4

    今天刚买了个小米手环,系统须要4.4及以上,但自己手机系统版本号不匹配.故打算在VM中安装Android4.4连接小米手环. 这一节先介绍在VM中安装Android4.4(怎么安装VM就不介绍了) 1 ...

  9. Ubuntu 14.04 下手动安装Firefox的Flash插件

    有时候我们不得不採用手动安装一些软件. Ubuntu 14.04 下手动安装Firefox的Flash插件有下面几步 1. 下载Flash插件 下载地址为http://get.adobe.com/cn ...

  10. sqlserver,执行生成脚本时“引发类型为“System.OutOfMemoryException”的异常”(已解决)

    sqlserver,执行生成脚本时“引发类型为“System.OutOfMemoryException”的异常”(已解决) 出现此错误主要是因为.sql的脚本文件过大(一般都超过100M)造成内存无法 ...