windows设备驱动安装接口(自己仿写)

  1 /*****************************************
  2 Author:foo_hack
  3 
  4 This is File named:Setup.h
  5 
  6 The Funtion Implement in Setup.cpp
  7 
  8 
  9 
 10 ******************************************/
 11 
 12 
 13 #include "stdafx.h"
 14 
 15 void UDBG(TCHAR *msg, ...);
 16 
 17 void FreeAllInfFiles();
 18 int FindAllInfFiles(WCHAR* csDir);
 19 void InstallDriver();
 20 int UpdateDriver();
 21 void FindAllDevices(const WCHAR* asHID);
 22 void FreeDevices();
 23 void RemoveDevices();
 24 BOOL Reboot();
 25 BOOL ConfigRight(WCHAR* szPath);
 26 
 27 VOID SearchRegistryHardID(PWCHAR pHardIDBuffer);
 28 
 29 ////////////////////////////////////////////////////////////////////
 30 
 31 BOOL IsDeviceInstallInProgress(VOID);
 32 int RemoveDriver(_TCHAR *HardwareID);
 33 VOID UninstallWDMDriver(LPCTSTR theHardware);
 34 BOOL UnicodeToAnsi(LPCWSTR Source, const WORD wLen, LPSTR Destination, const WORD sLen);
 35 BOOL AnsiToUnicode(LPCSTR Source, const WORD sLen, LPWSTR Destination, const WORD wLen);
 36 //BOOL GetINFData(FILE *pFile);
 37 VOID FindComma(LPSTR szData);
 38 //BOOL GetSectionData(FILE* pFile, const char* szKey, const char bIsVender);
 39 //BOOL IsInstalled();
 40 BOOL InstallClassDriver(LPCTSTR theINFName);
 41 BOOL StartInstallWDMDriver(LPCTSTR theInfName) ;
 42 
 43 BOOL FindExistingDevice(IN LPTSTR HardwareId);
 44 
 45 VOID InitialGlobalVar();
 46 
 47 
 48 ////////////////////////////////////////////////////////////////////
 49 
 50  //extern WORD g_wVender;  
 51  //extern WORD g_wHardware;  
 52  //extern TCHAR g_strVender[20][64];  
 53  //extern TCHAR g_strHardware[20][64];  
 54  //extern TCHAR g_strHID[MAX_PATH+1];  
 55 
 56 
 57 
 58 ///////////////////////////////////////////////////////////////////
 59 
 60 typedef struct
 61 {
 62     WCHAR asHID[MAX_PATH];
 63     int  nInfNum;        // g_asInfList下标号
 64 
 65     int  nNumCone;
 66     int  nNumNotCone;
 67     bool bNeedUpdate;
 68 
 69     bool bWillBeUpdate;
 70     bool bSuccess;
 71     //int  nFail;
 72 } HID_INFO, *PHID_INFO;
 73 
 74 typedef struct
 75 {
 76     WCHAR asInfName[MAX_PATH];    // 文件名
 77     WCHAR asFullPath[MAX_PATH];    // 全路径
 78     WCHAR asDesPath[MAX_PATH];
 79     WCHAR *asDesName;
 80     WCHAR asVersion[MAX_PATH];
 81     WCHAR asClassName[MAX_PATH];
 82     WCHAR asProvider[MAX_PATH];
 83     WCHAR asDSign[MAX_PATH];
 84     bool bWillBeInstall;
 85     int  nResultInstall;
 86 }INF_INFO, *PINF_INFO;
 87 
 88 #define MAX_SYMBOL_LINK 250
 89 
 90 typedef struct Hid_Ddvices{
 91     WCHAR asHID[MAX_PATH];
 92 
 93     WCHAR* asDeviceInstanceID[MAX_SYMBOL_LINK];
 94     bool bLink[MAX_SYMBOL_LINK];
 95     bool bSuccess[MAX_SYMBOL_LINK];
 96     bool bWillBeDelete[MAX_SYMBOL_LINK];
 97 
 98     int nMaxCount;
 99     int nCount;
100 
101     bool bNeedReboot;
102 
103     Hid_Ddvices()
104     {
105         nCount = nMaxCount = 0;
106         bNeedReboot = false;
107 
108         ZeroMemory(asHID, sizeof(asHID)+ sizeof(asDeviceInstanceID) + 
109             sizeof(bLink) + sizeof(bSuccess) + sizeof(bWillBeDelete));
110     }
111 }HID_DEVICES, *PHID_DEVICES;
112 
113 #define MAX_INF_COUNT 40
114 #define MAX_HID_COUNT 250
115 
116 extern PINF_INFO g_InfList[MAX_INF_COUNT];
117 extern int g_nInfCount;    // INF文
118 
119 extern PHID_INFO g_HIDInfo[MAX_HID_COUNT];
120 extern int g_nHIDCount ;    // HID个数    
121 
122 extern HID_DEVICES g_HIDDevices;
Setup.h
   1 #include "stdafx.h"
   2 #include <newdev.h>
   3 #include <setupapi.h>
   4 #include <cfgmgr32.h>
   5 #include <regstr.h>
   6 #include <strsafe.h>
   7 #include <string.h>
   8 
   9 
  10 #include <Aclapi.h>
  11 #include "setup.h"
  12 
  13 #pragma comment(lib,"Advapi32")
  14 
  15 
  16 #pragma comment(lib, "newdev.lib")
  17 #pragma comment(lib, "setupapi.lib")
  18 
  19 void GetHIDList(int nInfIndex);
  20 
  21 DWORD DeleteTree(HKEY RootKey, const WCHAR *pSubKey);
  22 
  23 // 不带变参
  24 void ULOG(TCHAR *msg)
  25 {
  26     OutputDebugString(_T("UsbKitApp:"));
  27     OutputDebugString(msg);
  28     OutputDebugString(_T("\r\n"));
  29 }
  30 
  31 #ifdef DEBUG
  32 // 带变参的Log函数
  33 void UDBG(TCHAR *msg, ...)
  34 {
  35     TCHAR strMsg[1024];
  36 
  37     va_list argp;
  38     va_start(argp, msg);
  39     _vstprintf_s(strMsg, 1024, msg, argp);
  40     va_end(argp);
  41     OutputDebugString(_T("UsbKitApp:"));
  42     OutputDebugString(strMsg);
  43     OutputDebugString(_T("\r\n"));
  44 }
  45 #else
  46 void UDBG(TCHAR* msg, ...)
  47 {
  48 
  49 }
  50 #endif
  51 
  52 PINF_INFO g_InfList[MAX_INF_COUNT];
  53 int g_nInfMaxCount = 0;
  54 int g_nInfCount = 0;    // INF文件数
  55 
  56 PHID_INFO g_HIDInfo[MAX_HID_COUNT];
  57 int g_nHIDMaxCount = 0;
  58 int g_nHIDCount = 0;    // HID个数    
  59 
  60 HID_DEVICES g_HIDDevices;
  61 
  62 void FreeDevices()
  63 {
  64     for(int i = 0; i < g_HIDDevices.nMaxCount; i++)
  65     {
  66         delete g_HIDDevices.asDeviceInstanceID[i];
  67     }
  68 
  69     ZeroMemory(&g_HIDDevices, sizeof(g_HIDDevices));
  70 }
  71 
  72 void FreeAllInfFiles()
  73 {
  74     for(int i = 0; i < g_nHIDMaxCount; i++)
  75         delete g_HIDInfo[i];
  76 
  77     g_nHIDMaxCount = g_nHIDCount = 0;
  78 
  79     for(int i = 0; i < g_nInfMaxCount; i++)
  80         delete g_InfList[i];
  81 
  82     g_nInfMaxCount = g_nInfCount = 0;
  83 }
  84 
  85 //在特定路径下寻找所有的inf文件
  86 int FindAllInfFiles(WCHAR* csDir = NULL)
  87 {
  88     WIN32_FIND_DATA FindFileData;
  89     WCHAR dir[MAX_PATH];
  90     WCHAR path[MAX_PATH];
  91     HANDLE hFind = INVALID_HANDLE_VALUE;
  92 
  93     if(csDir == NULL)
  94     {
  95         // 在当前路径中搜索所有inf文件
  96         GetCurrentDirectory(MAX_PATH, dir);
  97         //StringCchCopy(path, MAX_PATH, dir);//此函数不支持win XP SP1
  98         wcscpy(path,dir);
  99     }
 100     else
 101     {
 102         if(!GetFullPathName(csDir, MAX_PATH, dir, NULL))
 103             GetCurrentDirectory(MAX_PATH, dir);
 104 
 105         //StringCchCopy(path, MAX_PATH, dir);
 106 
 107         wcscpy(path,dir);
 108     }
 109 
 110     //StringCchCat(path, MAX_PATH, L"\\*.inf");//此函数不支持win XP SP1
 111     wcscat(path,L"\\*.inf");
 112 
 113     wprintf(path);
 114     printf("\n");
 115 
 116     __try{
 117 
 118         g_nInfCount = 0;
 119         g_nHIDCount = 0;
 120 
 121         // 遍历
 122         hFind = FindFirstFile(path, &FindFileData);
 123 
 124         if (hFind == INVALID_HANDLE_VALUE) 
 125         {
 126             printf("没有发现inf文件\n");
 127             __leave;
 128         } 
 129 
 130         do{
 131             if(g_nInfCount >= g_nInfMaxCount)
 132             {
 133                 g_InfList[g_nInfCount] = new INF_INFO;
 134                 g_nInfMaxCount = g_nInfCount + 1;
 135             }
 136 
 137             ZeroMemory(g_InfList[g_nInfCount], sizeof(INF_INFO));
 138 
 139             //StringCchCopy(path, MAX_PATH, dir);
 140             wcscpy(path,dir);
 141             //StringCchCat(path, MAX_PATH, L"\\");
 142             wcscat(path,L"\\");
 143             //StringCchCat(path, MAX_PATH, FindFileData.cFileName);
 144             wcscat(path,FindFileData.cFileName);
 145             //StringCchCopy(g_InfList[g_nInfCount]->asInfName, MAX_PATH, FindFileData.cFileName);
 146             wcscpy(g_InfList[g_nInfCount]->asInfName,FindFileData.cFileName);
 147             //StringCchCopy(g_InfList[g_nInfCount]->asFullPath, MAX_PATH, path);
 148             wcscpy(g_InfList[g_nInfCount]->asFullPath,path);
 149             // 查找每个inf文件中的所有HID
 150             wprintf(L"找到文件:%s\n", FindFileData.cFileName);
 151 
 152             GetHIDList(g_nInfCount);
 153             g_nInfCount ++;
 154 
 155         }while (FindNextFile(hFind, &FindFileData) != 0 && g_nInfMaxCount < MAX_INF_COUNT) ;
 156 
 157     }
 158     __finally{
 159         if(hFind != INVALID_HANDLE_VALUE)
 160         {
 161             FindClose(hFind);
 162         }
 163     }
 164 
 165     return g_nHIDCount;
 166 }
 167 
 168 //查找特定inf文件中的所有HID(硬件ID)
 169 void GetHIDList(int nInfIndex)
 170 {
 171     INFCONTEXT infcont;    
 172     INFCONTEXT infcont_dev;
 173 
 174     HINF hInf = INVALID_HANDLE_VALUE;
 175     DWORD config_flags, problem, status;
 176     BOOL reboot;
 177     WCHAR inf_path[MAX_PATH];
 178 
 179     WCHAR direct[MAX_PATH];
 180     WCHAR manu[MAX_PATH];
 181     WCHAR manu_os[MAX_PATH];
 182     WCHAR hid[MAX_PATH];
 183     WCHAR tmp_id[MAX_PATH];
 184 
 185     WCHAR os[8][32];
 186 
 187     __try
 188     {
 189         // 取INF路径
 190         wprintf(g_InfList[nInfIndex]->asFullPath);
 191         if(!GetFullPathName(g_InfList[nInfIndex]->asFullPath, MAX_PATH, inf_path, NULL))
 192         {
 193             printf(".inf文件 %s 未找到\n", g_InfList[nInfIndex]->asInfName);
 194             __leave;
 195         }
 196 
 197         wprintf(L"INF 文件路径:%s\n", inf_path);
 198 
 199         // 打开INF文件
 200         hInf = SetupOpenInfFile(inf_path, NULL, INF_STYLE_WIN4, NULL);
 201 
 202         if(hInf == INVALID_HANDLE_VALUE)
 203         {
 204             wprintf(L"打开文件失败:%s", inf_path);
 205             __leave;
 206         }
 207 
 208         if(!SetupFindFirstLine(hInf, L"version", NULL, &infcont))
 209         {
 210             printf("找不到[Version]域,不是合法的Inf文件\n");
 211             __leave;
 212         }
 213 
 214         //
 215         // 获取Version信息
 216         //
 217 
 218         do 
 219         {
 220             if(!SetupGetStringField(&infcont, 0, direct, sizeof(direct), NULL))
 221                 continue;
 222 
 223             _wcslwr(direct);//把字符串转为小写
 224             if(0 == wcscmp(direct, L"class"))
 225             {
 226                 if(SetupGetStringField(&infcont, 1, direct, sizeof(direct), NULL))
 227                 {
 228                     //StringCchCopy(g_InfList[nInfIndex]->asClassName, MAX_PATH, direct);
 229                     wcscpy(g_InfList[nInfIndex]->asClassName,direct);
 230                 }
 231             }
 232             else if(0 == wcscmp(direct, L"driverver"))
 233             {
 234                 if(SetupGetStringField(&infcont, 1, direct, sizeof(direct), NULL))
 235                 {
 236                     //StringCchCopy(g_InfList[nInfIndex]->asVersion, MAX_PATH, direct);
 237                     wcscpy(g_InfList[nInfIndex]->asVersion,direct);
 238 
 239                     if(SetupGetStringField(&infcont, 2, direct, sizeof(direct), NULL))
 240                     {
 241                         //StringCchCat(g_InfList[nInfIndex]->asVersion, MAX_PATH, L", ");
 242                         wcscat(g_InfList[nInfIndex]->asVersion,L", ");
 243                         //StringCchCat(g_InfList[nInfIndex]->asVersion, MAX_PATH, direct);
 244                         wcscat(g_InfList[nInfIndex]->asVersion,direct);
 245                     }
 246                 }
 247             }
 248             else if(0 == wcscmp(direct, L"provider"))
 249             {
 250                 if(SetupGetStringField(&infcont, 1, direct, sizeof(direct), NULL))
 251                 {
 252                     //StringCchCopy(g_InfList[nInfIndex]->asProvider, MAX_PATH, direct);
 253                     wcscpy(g_InfList[nInfIndex]->asProvider,direct);
 254                 }
 255             }
 256             else if(wcsstr(direct, L"catalogfile"))//返回第一个子字符创的指针
 257             {
 258                 if(SetupGetStringField(&infcont, 1, direct, sizeof(direct), NULL))
 259                 {
 260                     //StringCchCopy(g_InfList[nInfIndex]->asDSign, MAX_PATH, direct);
 261                     wcscpy(g_InfList[nInfIndex]->asDSign,direct);
 262                 }
 263             }
 264         } while (SetupFindNextLine(&infcont, &infcont));
 265 
 266         printf("INF 信息:\n");
 267         wprintf(L"%s\n", g_InfList[nInfIndex]->asClassName);
 268         wprintf(L"%s\n", g_InfList[nInfIndex]->asProvider);
 269         wprintf(L"%s\n", g_InfList[nInfIndex]->asDSign);
 270         wprintf(L"%s\n", g_InfList[nInfIndex]->asVersion);
 271 
 272         if(g_nHIDMaxCount >= MAX_HID_COUNT)
 273             __leave;
 274 
 275         //
 276         // 搜索设备描述符
 277         //
 278 
 279         if(!SetupFindFirstLine(hInf, L"Manufacturer", NULL, &infcont))
 280         {
 281             printf("没有可用设备描述符\n");
 282             __leave;
 283         }
 284 
 285         SYSTEM_INFO siSysInfo;
 286         GetSystemInfo(&siSysInfo);      
 287 
 288         do{
 289             int i = 0;
 290             int j = 0;
 291 
 292             // 一行行搜索
 293             if(!SetupGetStringField(&infcont, 1, manu, sizeof(manu), NULL))
 294             {
 295                 continue;
 296             }
 297 
 298             wprintf(manu);
 299 
 300             printf("\n");
 301 
 302             for(; i < 4; i++)
 303             {
 304                 if(!SetupGetStringField(&infcont, i+2, os[i], sizeof(os[0]), NULL))
 305                     break;
 306                 else
 307                     printf("OS: %s\n", os[i]);
 308 
 309                 _wcslwr(os[i]);
 310             }
 311 
 312             // 寻找最佳的平台匹配
 313             if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) // X64
 314             {
 315                 for(; j < i; j++)
 316                 {
 317                     if(wcscmp(os[j], L"ntamd64"))
 318                     {
 319                         //StringCchCopy(manu_os, sizeof(manu_os), manu);
 320                         wcscpy(manu_os,manu);
 321                         //StringCchCat(manu_os, sizeof(manu_os), L".");
 322                         wcscat(manu_os,L".");
 323                         //StringCchCat(manu_os, sizeof(manu_os), os[j]);
 324                         wcscat(manu_os,os[i]);
 325 
 326                         // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
 327                         if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
 328                             //StringCchCopy(manu, sizeof(manu), manu_os);
 329                             wcscpy(manu,manu_os);
 330 
 331                         break;
 332                     }
 333                 }
 334             }
 335             else if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
 336             {
 337                 for(; j < i; j++)
 338                 {
 339                     if(0 == wcsstr(os[j], L"ntia64"))
 340                     {
 341                         //StringCchCopy(manu_os, sizeof(manu_os), manu);
 342                         wcscpy(manu_os,manu);
 343                         //StringCchCat(manu_os, sizeof(manu_os), L".");
 344                         wcscat(manu_os,L".");
 345                         //StringCchCat(manu_os, sizeof(manu_os), os[j]);
 346                         wcscat(manu_os,os[j]);
 347 
 348                         // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
 349                         if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
 350                             //StringCchCopy(manu, sizeof(manu), manu_os);
 351                             wcscpy(manu,manu_os);
 352 
 353                         break;
 354                     }
 355                 }
 356             }
 357             else if(siSysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
 358             {
 359                 for(; j < i; j++)
 360                 {
 361                     if(0 == wcsstr(os[j], L"ntx86"))
 362                     {
 363                         //StringCchCopy(manu_os, sizeof(manu_os), manu);
 364                         wcscpy(manu_os,manu);
 365                         //StringCchCat(manu_os, sizeof(manu_os), L".");
 366                         wcscat(manu_os,L".");
 367                         //StringCchCat(manu_os, sizeof(manu_os), os[j]);
 368                         wcscat(manu_os,os[j]);
 369                         wprintf(manu_os);
 370                         printf("\n");
 371                         // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
 372                         if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
 373                             //StringCchCopy(manu, sizeof(manu), manu_os);
 374                             wcscpy(manu,manu_os);
 375 
 376                         break;
 377                     }
 378                 }
 379             }
 380 
 381             // 最后,如果最符合的版本没有找到,就看看.nt有没有
 382             if(NULL == wcsstr(manu, L".ntx86") && 
 383                 NULL == wcsstr(manu, L".ntia64") && 
 384                 NULL == wcsstr(manu, L".ntamd64"))
 385             {
 386                 for(j = 0; j < i; j++)
 387                 {
 388                     if(0 == wcsstr(os[j], L".nt"))
 389                     {
 390                         //StringCchCopy(manu_os, sizeof(manu_os), manu);
 391                         wcscpy(manu_os,manu);
 392                         //StringCchCat(manu_os, sizeof(manu_os), L".");
 393                         wcscat(manu_os,L".");
 394                         //StringCchCat(manu_os, sizeof(manu_os), os[j]);
 395                         wcscat(manu_os,os[j]);
 396 
 397                         // 如果找到[XXX.ntamd64],就用它;否则去掉os后缀
 398                         if(SetupFindFirstLine(hInf, manu_os, NULL, &infcont_dev))
 399                             //StringCchCopy(manu, sizeof(manu), manu_os);
 400                             wcscpy(manu,manu_os);
 401 
 402                         break;
 403                     }
 404                 }
 405             }
 406 
 407             wprintf(L"设备域名:%s\n", manu);
 408             if(!SetupFindFirstLine(hInf, manu, NULL, &infcont_dev))
 409             {
 410                 printf("找不到设备模块\n");
 411                 continue;
 412             }
 413 
 414             do{
 415                 if(!SetupGetStringField(&infcont_dev, 2, hid, sizeof(hid), NULL))
 416                     continue;
 417 
 418                 // 保存HID记录
 419                 //
 420 
 421                 _wcslwr(hid);
 422                 wprintf(L"HID: %s\n", hid);
 423 
 424                 if(g_nHIDMaxCount <= g_nHIDCount)
 425                 {
 426                     g_HIDInfo[g_nHIDCount] = new HID_INFO;
 427                     g_nHIDMaxCount = g_nHIDCount + 1;
 428                 }
 429 
 430                 ZeroMemory(g_HIDInfo[g_nHIDCount], sizeof(HID_INFO));
 431                 //StringCchCopy(g_HIDInfo[g_nHIDCount]->asHID, MAX_PATH, hid);
 432                 wcscpy(g_HIDInfo[g_nHIDCount]->asHID,hid);
 433                 g_HIDInfo[g_nHIDCount]->nInfNum = nInfIndex;
 434                 g_nHIDCount++;
 435 
 436             }while(SetupFindNextLine(&infcont_dev, &infcont_dev) && g_nHIDMaxCount < MAX_HID_COUNT);
 437 
 438             // 获取下一个设备ID
 439         }while(SetupFindNextLine(&infcont, &infcont) && g_nHIDMaxCount < MAX_HID_COUNT);
 440     }
 441     __finally
 442     {
 443         if(hInf != INVALID_HANDLE_VALUE)
 444             SetupCloseInfFile(hInf);
 445     }
 446 }
 447 
 448 BOOL Reboot()
 449 {
 450     HANDLE Token = NULL;
 451     TOKEN_PRIVILEGES NewPrivileges;
 452     LUID Luid;
 453 
 454     __try
 455     {
 456         // 使能ShutDown特权
 457         if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&Token))
 458             __leave;
 459 
 460         if(!LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&Luid))
 461             __leave;
 462 
 463         NewPrivileges.PrivilegeCount = 1;
 464         NewPrivileges.Privileges[0].Luid = Luid;
 465         NewPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 466 
 467         AdjustTokenPrivileges(Token, FALSE, &NewPrivileges, 0, NULL, NULL);
 468     }
 469     __finally
 470     {
 471         if(Token) CloseHandle(Token);
 472     }
 473 
 474     //尝试重启
 475     return InitiateSystemShutdownEx(NULL, NULL, 0, FALSE, TRUE, REASON_PLANNED_FLAG | REASON_HWINSTALL);
 476 }
 477 
 478 // 删除设备对应的驱动程序,调用SetupDiCallClassInstaller函数,并执行DIF_REMOVE动作
 479 // 参数Devs和DevInfo用来唯一标识目标设备
 480 bool RemoveDevice(__in HDEVINFO Devs, __in PSP_DEVINFO_DATA DevInfo)
 481 {
 482     UDBG(_T("[RemoveDriverForSpecifiedDevice]"));
 483 
 484     SP_REMOVEDEVICE_PARAMS rmdParams;
 485     SP_DEVINSTALL_PARAMS devParams;
 486 
 487     rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
 488     rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
 489     rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
 490     rmdParams.HwProfile = 0;
 491 
 492     if(SetupDiSetClassInstallParams(Devs, DevInfo, &rmdParams.ClassInstallHeader, sizeof(rmdParams)) &&
 493         SetupDiCallClassInstaller(DIF_REMOVE, Devs, DevInfo)) 
 494     {
 495         wprintf(_T("卸载驱动成功\n"));
 496 
 497         // 检查是否需要重启机器
 498         devParams.cbSize = sizeof(devParams);
 499         if(SetupDiGetDeviceInstallParams(Devs, DevInfo, &devParams) && 
 500             (devParams.Flags & (DI_NEEDRESTART|DI_NEEDREBOOT))) 
 501         {
 502             g_HIDDevices.bNeedReboot = true;
 503         }
 504 
 505         return true;
 506     }
 507 
 508     return false;
 509 }
 510 
 511 void RemoveDevices()
 512 {
 513     HDEVINFO dev_info;
 514     SP_DEVINFO_DATA dev_info_data;
 515     int nDevIndex;
 516     WCHAR id[MAX_PATH];
 517 
 518     g_HIDDevices.bNeedReboot = false;
 519 
 520     // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
 521     dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES);
 522 
 523     // class名无效
 524     if(dev_info == INVALID_HANDLE_VALUE)
 525     {
 526         printf("无效的HDEVINFO句柄\n");
 527         return;
 528     }
 529 
 530     nDevIndex = 0;
 531 
 532     // 枚举设备
 533     dev_info_data.cbSize = sizeof(dev_info_data);
 534     while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
 535     {
 536         if(CR_SUCCESS != CM_Get_Device_ID(dev_info_data.DevInst, id, MAX_PATH, 0))
 537             continue;
 538 
 539         _wcslwr(id);
 540 
 541         for(int i = 0; i < g_HIDDevices.nCount; i++)
 542         {
 543             if(g_HIDDevices.bWillBeDelete[i] && 
 544                 0 == wcscmp(id, g_HIDDevices.asDeviceInstanceID[i]))
 545             {
 546                 wprintf(id);
 547                 printf("\n");
 548                 g_HIDDevices.bSuccess[i] = RemoveDevice(dev_info, &dev_info_data);
 549             }
 550         }
 551 
 552         nDevIndex++;
 553     }
 554 
 555     SetupDiDestroyDeviceInfoList(dev_info);
 556 }
 557 
 558 //该函数主要就是根据硬件ID查找在本地机器上有没有这样一个设备,\
 559 把查找到的ID放到全局变量中,还检测设备有没有连接系统
 560 void FindAllDevices(const WCHAR* asHID)
 561 {
 562     HDEVINFO dev_info;
 563     SP_DEVINFO_DATA dev_info_data;
 564 
 565     int nDevIndex;
 566     WCHAR id[MAX_PATH];
 567     WCHAR *p;
 568     ULONG problem;
 569     ULONG status;
 570 
 571     WCHAR* ashid = _wcsdup(asHID);
 572     _wcslwr(ashid);//转换ashid中的大写字母
 573 
 574     printf("FindAllDevices\n");
 575 
 576     g_HIDDevices.nCount = 0;
 577 
 578     // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
 579     dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES);
 580 
 581     // class名无效
 582     if(dev_info == INVALID_HANDLE_VALUE)
 583     {
 584         printf("无效的HDEVINFO句柄\n");
 585         free(ashid);
 586         return;
 587     }
 588 
 589     nDevIndex = 0;
 590 
 591     // 枚举设备,从0开始枚举设备
 592     dev_info_data.cbSize = sizeof(dev_info_data);
 593     while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
 594     {
 595         if(CR_SUCCESS != CM_Get_Device_ID(dev_info_data.DevInst, id, MAX_PATH, 0))
 596             continue;
 597 
 598         (id);
 599         if(wcsstr(id, ashid))
 600         {
 601             if(g_HIDDevices.nCount >= g_HIDDevices.nMaxCount)
 602             {
 603                 g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nMaxCount] = new WCHAR[MAX_PATH];
 604                 g_HIDDevices.nMaxCount++;
 605             }
 606 
 607             // Device实例ID。把id拷贝到parameter 1中
 608             //StringCchCopy(g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nCount], MAX_PATH, id);
 609             wcscpy(g_HIDDevices.asDeviceInstanceID[g_HIDDevices.nCount],id);
 610             // 连接状态
 611             g_HIDDevices.bLink[g_HIDDevices.nCount] = false;
 612             if(CM_Get_DevNode_Status(&status,
 613                 &problem,
 614                 dev_info_data.DevInst,
 615                 0) != CR_NO_SUCH_DEVINST)
 616             {
 617                 g_HIDDevices.bLink[g_HIDDevices.nCount] = true;
 618             }
 619 
 620             g_HIDDevices.nCount++;
 621         }
 622 
 623         nDevIndex++;
 624     }
 625 
 626     SetupDiDestroyDeviceInfoList(dev_info);
 627     free(ashid);
 628 }
 629 
 630 void InstallDriver()
 631 {
 632     HDEVINFO dev_info;
 633     SP_DEVINFO_DATA dev_info_data;
 634     int nDevIndex;
 635     WCHAR id[MAX_PATH];
 636     WCHAR tmp_id[MAX_PATH];
 637     WCHAR *p;
 638     ULONG problem;
 639     ULONG status;
 640     int nInfIndex;
 641 
 642     for(nInfIndex = 0; nInfIndex < g_nInfCount; nInfIndex++)
 643     {
 644         if(false == g_InfList[nInfIndex]->bWillBeInstall)
 645             continue;
 646 
 647         // 拷贝INF文件(预安装到Driver Store中)
 648         wprintf(L"Parameter 1 is %s\n",g_InfList[nInfIndex] ->asFullPath);
 649         //getch();
 650         //wprintf(L"Parameter 1 is %s\n",g_InfList[nInfIndex] ->asDesPath);
 651         if(FALSE ==    SetupCopyOEMInf(g_InfList[nInfIndex]->asFullPath, NULL, SPOST_PATH,0, 
 652                 0, 0, 
 653                 NULL,    NULL))
 654         {
 655             printf("SetCopyOEMInf1 Error Code is %d\n",GetLastError());
 656             
 657             if(GetLastError() == ERROR_FILE_EXISTS)
 658             {
 659                 g_InfList[nInfIndex]->nResultInstall = 1;
 660                 wprintf(L"located in inf dir's name:%s\n",g_InfList[nInfIndex]->asDesPath);
 661                 
 662                 PWCHAR pSubStr1,pSubWork1;
 663                 WCHAR OemFileName3[128];
 664                 
 665                 if(NULL != (pSubStr1 = wcsstr((wchar_t*)g_InfList[nInfIndex]->asDesPath,L"oem")))
 666                 {
 667                     pSubWork1 = pSubStr1;
 668 
 669                     while((*pSubWork1) != 'f')
 670                     {
 671                         pSubWork1++;
 672                     }
 673 
 674                     pSubWork1++;
 675 
 676                     *pSubWork1 = '\0';
 677 
 678                     
 679 
 680                     wcscpy(OemFileName3,pSubStr1);
 681 
 682                     wprintf(L"OemFileName3 is %s\n",OemFileName3);
 683 
 684                     //getch();
 685                 }
 686                 
 687                 if(SetupUninstallOEMInf(OemFileName3, SUOI_FORCEDELETE, NULL))
 688                 {
 689                     printf("new Driver Package Has Deleted succced! on windows XP\n");
 690                     
 691                     if(FALSE ==    SetupCopyOEMInf(g_InfList[nInfIndex]->asFullPath, NULL, SPOST_PATH, SP_COPY_NOOVERWRITE, 
 692                         g_InfList[nInfIndex]->asDesPath, MAX_PATH, 
 693                         NULL, &g_InfList[nInfIndex]->asDesName))
 694                     {
 695                         printf("SetCopyOEMInf2 Error Code is %d\n",GetLastError());
 696                     }
 697                     else
 698                         printf("SetupCopyOEMInf2 succeed!\n");
 699 
 700                     //getch();
 701 
 702                 }
 703 
 704             }
 705             else
 706                 g_InfList[nInfIndex]->nResultInstall = -1;
 707         }else
 708         {
 709             
 710             printf("Install Succeed!\n");
 711             
 712             //getch();
 713             g_InfList[nInfIndex]->nResultInstall = 0;
 714         }
 715         
 716         BOOL bResult = FALSE;
 717         HDEVINFO DeviceInfoSet = INVALID_HANDLE_VALUE;
 718         SP_DEVINFO_DATA DeviceInfoData;
 719         GUID ClassGUID;
 720         TCHAR ClassName[MAX_CLASS_NAME_LEN];
 721         TCHAR hwIdList[LINE_LEN+4];
 722         DWORD Status;
 723 
 724         if (!SetupDiGetINFClass (g_InfList[nInfIndex]->asFullPath, &ClassGUID, ClassName, sizeof(ClassName)/sizeof(TCHAR), 0) ) 
 725         {
 726             printf("SetupDiGetINFClass fail,Error Code is %d\n",GetLastError());
 727         }
 728         
 729         DeviceInfoSet = SetupDiGetClassDevs(&ClassGUID,ClassName,NULL,DIGCF_PRESENT);
 730 
 731         if(DeviceInfoSet == INVALID_HANDLE_VALUE)
 732         {
 733            printf("SetupDiGetClassDevs fail,Error Code is %d\n",GetLastError());
 734         }
 735         
 736         /*DWORD wIdx = 0;
 737         
 738         while (TRUE)  
 739         {  
 740             DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);  
 741             //找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息  
 742             if (SetupDiEnumDeviceInfo(DeviceInfoSet, wIdx, &DeviceInfoData))  
 743             {  
 744 
 745 
 746                 printf("SetupDiEnumDeviceInfo Success!\n");
 747 
 748                 char Buffer[2048] = {0};  
 749 
 750                 //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息  
 751                 if (SetupDiGetDeviceRegistryProperty(DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID,  
 752                     0L, (PBYTE)Buffer, 2048, 0L))  
 753                 {  
 754                     printf("SetupDiGetDeviceRegistryProperty Success!\n");
 755 
 756                     wprintf(L"Buffer is %s\n",Buffer);
 757 
 758                     if (!lstrcmpi(L"USB\\VID_0451&PID_AF32&REV_0000", (LPTSTR)Buffer))  
 759                     {  
 760                         printf("theHardware is matched!\n");
 761                         
 762                         DWORD ConfigFlag;
 763                         
 764                         if(SetupDiGetDeviceRegistryProperty(DeviceInfoSet,&DeviceInfoData,SPDRP_CONFIGFLAGS,
 765                             0L,(PBYTE)&ConfigFlag,sizeof(ConfigFlag),0L))
 766                         {
 767                             
 768                             
 769                             ConfigFlag |=  CONFIGFLAG_REINSTALL;
 770 
 771                             SetupDiSetDeviceRegistryProperty(DeviceInfoSet,&DeviceInfoData,SPDRP_CONFIGFLAGS,
 772                                 (PBYTE)&ConfigFlag,sizeof(ConfigFlag));
 773 
 774                             
 775                         }
 776                         
 777 
 778                         if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32&REV_0000",
 779                             g_InfList[nInfIndex] ->asFullPath,INSTALLFLAG_FORCE,NULL))
 780                         {
 781                             printf("SetupDiGetINFClass fail,Error Code is %x\n",GetLastError());
 782                         }
 783                         
 784                         break;
 785                     }  
 786 
 787 
 788 
 789                 }  
 790             }  
 791             else 
 792             {
 793 
 794                 break;  
 795             }
 796 
 797             wIdx++;  
 798         }  */
 799 
 800 
 801 
 802         
 803         /*wprintf(L"ClassName is %s\n",ClassName);
 804 
 805         DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
 806 
 807         if (!SetupDiCreateDeviceInfo(DeviceInfoSet, L"USB\\VID_0451&PID_AF32\\7LUCK", &ClassGUID, NULL, NULL,  DICD_INHERIT_CLASSDRVS, &DeviceInfoData) ) 
 808         { 
 809             printf("SetupDiCreateDeviceInfo fail,Error Code is %x\n",GetLastError());
 810         }
 811             
 812 
 813         ZeroMemory (hwIdList, sizeof(hwIdList) );
 814 
 815         lstrcpyn (hwIdList, L"USB\\VID_0451&PID_AF32", LINE_LEN);
 816 
 817         if (!SetupDiSetDeviceRegistryProperty (DeviceInfoSet, &DeviceInfoData, SPDRP_HARDWAREID, (LPBYTE)hwIdList, 
 818                 ( lstrlen (hwIdList) + 1 + 1) * sizeof (TCHAR) ) ) 
 819         {
 820             printf("SetupDiSetDeviceRegistryProperty fail,Error Code is %d\n",GetLastError());    
 821                 
 822         }
 823         
 824         
 825 
 826         if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, DeviceInfoSet, &DeviceInfoData) ) 
 827         {
 828             printf("SetupDiCallClassInstaller fail,Error Code is %d\n",GetLastError());
 829         }*/
 830 
 831 
 832             
 833 
 834         /*if (!UpdateDriverForPlugAndPlayDevices(
 835                 NULL,
 836                 L"USB\\VID_0451&PID_AF32",
 837                 g_InfList[nInfIndex]->asFullPath,
 838                 INSTALLFLAG_FORCE,
 839                 NULL)  ) 
 840         {
 841             printf("UpdateDriverForPlugAndPlayDevices,Error Code is %x\n",GetLastError());
 842         }*/
 843         
 844         
 845         //Return Value:0xe0000203指定设备不在当前系统,0xe000020b没为设备指定设备集
 846         /*if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32",
 847             g_InfList[nInfIndex]->asFullPath,INSTALLFLAG_FORCE,NULL))
 848             {
 849  850 
 851 
 852 
 853 
 854             printf("UpdateDriverForPlugAndPlayDevices Failed! Error Code is %x\n",GetLastError());
 855         }*/
 856 
 857         getch();
 858 
 859         /*if(!UpdateDriverForPlugAndPlayDevices(NULL,L"USB\\VID_0451&PID_AF32",
 860             g_InfList[nInfIndex]->asFullPath,INSTALLFLAG_FORCE,NULL))
 861         {
 862             printf("UpdateDriverForPlugAndPlayDevices Failed! Error Code is %x\n",GetLastError());
 863         }*/
 864 
 865 
 866         //getch();
 867 
 868         for(int i = 0; i < g_nHIDCount; i++)
 869         {
 870             if(g_HIDInfo[i]->nInfNum == nInfIndex)
 871             {
 872                 g_HIDInfo[i]->nNumCone = 0;
 873                 g_HIDInfo[i]->nNumNotCone = 0;
 874                 g_HIDInfo[i]->bNeedUpdate = false;
 875             }
 876         }
 877 
 878         // 获取设备实例数
 879         if(g_InfList[nInfIndex]->nResultInstall == 0 && g_InfList[nInfIndex]->asClassName[0])
 880         {
 881 
 882             wprintf(g_InfList[nInfIndex]->asClassName);
 883             printf("\n");
 884 
 885             // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
 886             dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES);
 887 
 888             // class名无效
 889             if(dev_info == INVALID_HANDLE_VALUE){
 890                 printf("class 名无效\n");
 891                 continue;
 892             }
 893 
 894             nDevIndex = 0;
 895 
 896             // 枚举设备
 897             dev_info_data.cbSize = sizeof(dev_info_data);
 898             while(SetupDiEnumDeviceInfo(dev_info, nDevIndex, &dev_info_data))
 899             {
 900                 // 取设备ID
 901                 if(SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
 902                     SPDRP_HARDWAREID, 
 903                     NULL,
 904                     (BYTE *)tmp_id,
 905                     sizeof(tmp_id), 
 906                     NULL))
 907                 {
 908                     //获得的是一个字符串列表,故而需要遍历
 909                     for(p = tmp_id; *p; p += (wcslen(p) + 1))
 910                     {
 911                         _wcslwr(p);
 912                         for(int x = 0; x < g_nHIDCount; x++)
 913                         {
 914                             if(g_HIDInfo[x]->nInfNum != nInfIndex)
 915                                 continue;
 916 
 917                             if(wcsstr(p, g_HIDInfo[x]->asHID)){
 918                                 g_HIDInfo[x]->bNeedUpdate = true;// 此设备已存在,需要更新。
 919                                 if(CM_Get_DevNode_Status(&status,
 920                                     &problem,
 921                                     dev_info_data.DevInst,
 922                                     0) == CR_NO_SUCH_DEVINST)
 923                                 {
 924                                     g_HIDInfo[x]->nNumNotCone++;
 925                                 }
 926                                 else
 927                                     g_HIDInfo[x]->nNumCone++;
 928                             }
 929                         }
 930                     }
 931                 }
 932 
 933                 nDevIndex++;
 934             }
 935 
 936             SetupDiDestroyDeviceInfoList(dev_info);
 937         }
 938 
 939         SetupDiDestroyDeviceInfoList(dev_info);
 940 
 941 
 942     }    
 943 }
 944 
 945 // 更新驱动程序
 946 int UpdateDriver()
 947 {
 948     HDEVINFO dev_info;
 949     SP_DEVINFO_DATA dev_info_data;
 950     INFCONTEXT infcont;
 951     HINF hInf = NULL;
 952     DWORD config_flags, problem, status;
 953     BOOL reboot;
 954     char inf_path[MAX_PATH];
 955     char id[MAX_PATH];
 956     char tmp_id[MAX_PATH];
 957     char *p;
 958     int dev_index;
 959 
 960     dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
 961 
 962     __try
 963     {
 964         for(int i = 0; i < g_nHIDCount; i++)
 965         {
 966             if(g_HIDInfo[i]->bWillBeUpdate)
 967             {
 968                 if(g_HIDInfo[i]->nNumCone)
 969                 {
 970                     // 为当前连接到系统的所有设备更新驱动
 971                     g_HIDInfo[i]->bSuccess = UpdateDriverForPlugAndPlayDevices(NULL, g_HIDInfo[i]->asHID, 
 972                                             g_InfList[g_HIDInfo[i]->nInfNum]->asDesPath, 
 973                                             INSTALLFLAG_FORCE, 
 974                                             &reboot);
 975                 }
 976 
 977                 if(g_HIDInfo[i]->nNumNotCone)
 978                 {
 979                     dev_index = 0;
 980 
 981                     // 寻找所有设备,设置Flag值为DIGCF_ALLCLASSES。
 982                     dev_info = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES);
 983 
 984                     if(dev_info == INVALID_HANDLE_VALUE)
 985                         continue;
 986 
 987                     // 枚举设备
 988                     while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
 989                     {
 990                         // 先取设备ID,判断是否是当前更新设备
 991                         if(SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
 992                             SPDRP_HARDWAREID, NULL,
 993                             (BYTE *)tmp_id,
 994                             sizeof(tmp_id), 
 995                             NULL))
 996                         {
 997                             //获得的是一个字符串列表,故而需要遍历
 998                             for(p = tmp_id; *p; p += (strlen(p) + 1))
 999                             {
1000                                 strlwr(p);
1001 
1002                                 if(strstr(p, id))
1003                                 {
1004                                     // 判断此设备是不是当前未连接在系统
1005                                     if(CM_Get_DevNode_Status(&status,
1006                                         &problem,
1007                                         dev_info_data.DevInst,
1008                                         0) == CR_NO_SUCH_DEVINST)
1009                                     {
1010                                         // 取当前配置值
1011                                         if(SetupDiGetDeviceRegistryProperty(dev_info,
1012                                             &dev_info_data,
1013                                             SPDRP_CONFIGFLAGS,
1014                                             NULL,
1015                                             (BYTE *)&config_flags,
1016                                             sizeof(config_flags),
1017                                             NULL))
1018                                         {
1019                                             // 与CONFIGFLAG_REINSTALL或
1020                                             config_flags |= CONFIGFLAG_REINSTALL;
1021 
1022                                             // 将新的配置值写入
1023                                             SetupDiSetDeviceRegistryProperty(dev_info,
1024                                                 &dev_info_data,
1025                                                 SPDRP_CONFIGFLAGS,
1026                                                 (BYTE *)&config_flags,
1027                                                 sizeof(config_flags));
1028                                         }
1029                                     }
1030                                     
1031                                     // 找到一个即可,跳出。
1032                                     break;
1033                                 }
1034                             }
1035                         }
1036 
1037                         dev_index++;
1038                     }
1039 
1040                     SetupDiDestroyDeviceInfoList(dev_info);
1041                 }
1042             }
1043         }        
1044 
1045     }
1046     __finally
1047     {
1048     }
1049 
1050     return 0;
1051 }
1052 
1053 /////////////////////以下函数是移入的//////////////////////////////////////
1054 
1055 BOOL IsDeviceInstallInProgress (VOID)
1056 {
1057     return !(CM_WaitNoPendingInstallEvents(0) == WAIT_OBJECT_0);
1058 }
1059 
1060 int RemoveDriver(_TCHAR *HardwareID)
1061 {
1062     HDEVINFO DeviceInfoSet;
1063     SP_DEVINFO_DATA DeviceInfoData;
1064     DWORD i,err;
1065     //GUID devGUID ={36fc9e60-c465-11cf-8056-444553540000};
1066 
1067     DeviceInfoSet = SetupDiGetClassDevs(NULL, // All Classes
1068         0,
1069         0,
1070         DIGCF_ALLCLASSES | DIGCF_PRESENT ); // All devices present on system
1071 
1072     if (DeviceInfoSet == INVALID_HANDLE_VALUE)
1073     {
1074         printf("GetClassDevs(All Present Devices)\n");
1075         return 1;
1076     }
1077 
1078     //
1079     //  Enumerate through all Devices.
1080     //
1081     DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
1082     for (i=0;SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData);i++)
1083     {
1084         DWORD DataT;
1085         LPTSTR p,buffer = NULL;
1086         DWORD buffersize = 0;
1087 
1088         //
1089         // We won't know the size of the HardwareID buffer until we call
1090         // this function. So call it with a null to begin with, and then
1091         // use the required buffer size to Alloc the nessicary space.
1092         // Keep calling we have success or an unknown failure.
1093         //
1094         while (!SetupDiGetDeviceRegistryProperty(
1095             DeviceInfoSet,
1096             &DeviceInfoData,
1097             SPDRP_HARDWAREID,
1098             &DataT,
1099             (PBYTE)buffer,
1100             buffersize,
1101             &buffersize))
1102         {
1103             if (GetLastError() == ERROR_INVALID_DATA)
1104             {
1105                 //
1106                 // May be a Legacy Device with no HardwareID. Continue.
1107                 //
1108                 break;
1109             }
1110             else if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1111             {
1112                 //
1113                 // We need to change the buffer size.
1114                 //
1115                 if (buffer)
1116                     LocalFree(buffer);
1117                 buffer = (LPTSTR)LocalAlloc(LPTR,buffersize);
1118             }
1119             else
1120             {
1121                 //
1122                 // Unknown Failure.
1123                 //
1124                 printf("GetDeviceRegistryProperty");
1125                 goto cleanup_DeviceInfo;
1126             }
1127         }
1128 
1129         if (GetLastError() == ERROR_INVALID_DATA)
1130             continue;
1131 
1132         //
1133         // Compare each entry in the buffer multi-sz list with our HardwareID.
1134 
1135 
1136         //
1137         for (p = buffer; *p && (p < &buffer[buffersize]);p+=lstrlen(p)*sizeof(TCHAR) + 2)
1138 
1139 
1140         {
1141             //_tprintf(TEXT("Compare device ID: [%s]/n"),p);
1142 
1143             if (!_tcscmp(HardwareID,p))
1144             {
1145                 //_tprintf(TEXT("Found! [%s]/n"),p);
1146 
1147                 //
1148                 // Worker function to remove device.
1149                 //
1150                 //if (SetupDiCallClassInstaller(DIF_REMOVE,
1151                 //    DeviceInfoSet,
1152                 //    &DeviceInfoData))
1153 
1154                 if (SetupDiRemoveDevice(DeviceInfoSet, &DeviceInfoData))
1155 
1156 
1157                 {
1158                     printf("CallClassInstaller(REMOVE)\n");
1159                 }
1160                 else
1161                     printf("Remove Driver Fail\n");
1162                 break;
1163             }
1164 
1165             //printf("TTTTTTTTTTTTTTTTT is %s\n",p);
1166             //getch();
1167         }
1168 
1169         if (buffer) LocalFree(buffer);
1170     }
1171 
1172     if ((GetLastError()!=NO_ERROR)&&(GetLastError()!=ERROR_NO_MORE_ITEMS))
1173     {
1174         printf("EnumDeviceInfo\n");
1175     }
1176 
1177     //
1178     //  Cleanup.
1179     //
1180 cleanup_DeviceInfo:
1181     err = GetLastError();
1182     SetupDiDestroyDeviceInfoList(DeviceInfoSet);
1183 
1184     return err;
1185 }
1186 
1187 VOID UninstallWDMDriver(LPCTSTR theHardware) 
1188 {
1189     
1190     
1191    /* HKEY hKey;
1192      //删除安装包inf,不然刷新设备会重新安装
1193      if(INVALID_HANDLE_VALUE==(hKey = SetupDiOpenDevRegKey(hDevInfo,&spDevInfoData,DICS_FLAG_GLOBAL,0,
1194          DIREG_DEV,KEY_ALL_ACCESS)))
1195      {
1196          printf("Open Key Has Failed.\n");
1197      }*/
1198      
1199     //RegGetValue(hKey,L"InfPath");
1200     HKEY hKey[50] = {0};
1201     DWORD type_1=REG_SZ;
1202     BYTE buffer[512] = {0};
1203     BYTE buffer2[512] = {0};
1204     DWORD cbData_1=512;
1205     PWCHAR pSubStr = NULL;
1206     PWCHAR pSubWork = NULL;
1207     WCHAR SubKeyName[128] = {0};
1208     DWORD SizeSubKeyName = sizeof(WCHAR)*128;
1209     DWORD Index = 0;
1210     WCHAR KeyPath[512] = L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32";
1211     //WCHAR constKeyPath[512] = L"SYSTEM\\CurrentControlSet\\Enum\\";
1212     //wcscat(KeyPath,theHardware);
1213     //wcscat(constKeyPath,theHardware);
1214     WCHAR Path[128] = L"MACHINE\\SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32";
1215     //wcscat(Path,theHardware);
1216     WCHAR DeleteKeyPath[128] = L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32" ;
1217     //wcscat(DeleteKeyPath,theHardware);
1218     //WCHAR  EndChar = 'f';
1219 
1220     //if(ConfigRight(Path))
1221     //    printf("Set Right Success!\n");
1222     
1223     //这里如果是KEY_ALL_ACCESS就会返回失败,以前尝试注册表提权ConfigRight失败。原因是无SYSTEM权限
1224     //
1225     if(ERROR_SUCCESS !=RegOpenKeyEx(HKEY_LOCAL_MACHINE,KeyPath,0,KEY_ALL_ACCESS,&hKey[0]))
1226         printf("UninstallWDMDriver OpenKey Fail! error code is %d\n",GetLastError());
1227 
1228     printf("OpenKey Success!\n");
1229 
1230     //getch();
1231     
1232     ZeroMemory(KeyPath,sizeof(WCHAR)*512);
1233     
1234     //枚举子键
1235 
1236     while(ERROR_SUCCESS == RegEnumKey(hKey[0],Index,SubKeyName,SizeSubKeyName/*,NULL,NULL,NULL,NULL*/))
1237     {
1238        
1239       wcscpy(KeyPath,L"SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0451&PID_AF32");
1240       wcscat(KeyPath,L"\\");
1241       wcscat(KeyPath,SubKeyName);
1242        
1243        Index++;
1244 
1245       // ZeroMemory(buffer,sizeof(BYTE)*512);
1246        //ZeroMemory(buffer2,sizeof(BYTE)*512);
1247       // ZeroMemory(SubKeyName,SizeSubKeyName);
1248        //ZeroMemory(KeyPath,sizeof(WCHAR)*512);
1249        
1250        if(ERROR_SUCCESS==RegOpenKeyEx(HKEY_LOCAL_MACHINE,KeyPath,0,KEY_READ,&hKey[Index]))
1251            printf("OpenKey Success!\n");
1252 
1253        if( ERROR_SUCCESS==RegQueryValueEx(hKey[Index],L"DeviceDesc",NULL,&type_1,buffer,&cbData_1))
1254        
1255            printf("Get Buffer1 Success!\n");
1256 
1257        printf("%d\n",GetLastError());
1258        
1259        
1260        if( ERROR_SUCCESS==RegQueryValueEx(hKey[Index],L"Mfg",NULL,&type_1,buffer2,&cbData_1))
1261            printf("Get Buffer2 Success!\n");
1262        
1263        printf("%d\n",GetLastError());
1264 
1265        RegCloseKey(hKey[Index]);
1266 
1267        //搜索OEM文件
1268 
1269        if(NULL == (pSubStr = wcsstr((wchar_t*)buffer,L"oem")))
1270        {
1271            printf("Search SubString_buffer Fail!\n");
1272 
1273            if(NULL == (pSubStr = wcsstr((wchar_t*)buffer2,L"oem")))
1274            {
1275                printf("Search SubString_buffer2 Fail!\n");
1276 
1277                ZeroMemory(buffer,sizeof(BYTE)*512);
1278                ZeroMemory(buffer2,sizeof(BYTE)*512);
1279                ZeroMemory(SubKeyName,SizeSubKeyName);
1280                ZeroMemory(KeyPath,sizeof(WCHAR)*512);
1281                //KeyPath = NULL;
1282                continue;
1283            }
1284            else
1285            {
1286               // ZeroMemory(buffer,sizeof(BYTE)*512);
1287                //ZeroMemory(buffer2,sizeof(BYTE)*512);
1288                //ZeroMemory(SubKeyName,SizeSubKeyName);
1289                //ZeroMemory(KeyPath,sizeof(WCHAR)*512);
1290                //KeyPath = NULL;
1291                //continue;
1292 
1293                 printf("Search Success!\n");
1294 
1295                 
1296                
1297                pSubWork = pSubStr;
1298 
1299                while((*pSubWork) != 'f')
1300                {
1301                    pSubWork++;
1302                }
1303 
1304                pSubWork++;
1305 
1306                *pSubWork = '\0';
1307 
1308                WCHAR OemFileName1[128];
1309 
1310                wcscpy(OemFileName1,pSubStr);
1311 
1312                SP_DEVINFO_DATA spDevInfoData = {0};  
1313                HDEVINFO hDevInfo = 0L;  
1314                WORD wIdx, wCount = 0;  
1315 
1316                //得到设备信息结构的句柄  
1317                hDevInfo = SetupDiGetClassDevs(0L, 0L, 0L, DIGCF_ALLCLASSES | DIGCF_PRESENT);  
1318                if (hDevInfo == INVALID_HANDLE_VALUE)  
1319                {  
1320                    printf("Fail!\n"); 
1321                    return;  
1322                }  
1323 
1324                wIdx = 0;  
1325                while (TRUE)  
1326                {  
1327                    spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);  
1328                    //找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息  
1329                    if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))  
1330                    {  
1331                        char Buffer[2048] = {0};  
1332 
1333                        //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息  
1334                        if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,  
1335                            0L, (PBYTE)Buffer, 2048, 0L))  
1336                        {  
1337                            if (!lstrcmpi(theHardware, (LPTSTR)Buffer))  
1338                            {  
1339                                //从系统中删除一个注册的设备接口  
1340                                if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))  
1341                                    printf("Remove Fail is %d!\n",GetLastError()); 
1342                                //if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
1343                                //   printf("Remove Fail is %d!\n",GetLastError());
1344                                wCount++;  
1345                            }  
1346                        }  
1347                    }  
1348                    else  
1349                        break;  
1350                    wIdx++;  
1351                }  
1352 
1353                if (wCount != 0)  
1354                    _tprintf(_T("UnInstall Successed...\n")); 
1355 
1356                //getch();
1357 
1358                //wprintf("%s\n",(wchar_t*)pSubStr);
1359                if(SetupUninstallOEMInf(OemFileName1, SUOI_FORCEDELETE, NULL))
1360                    printf("Driver Package Has Deleted succced!\n");
1361 
1362                
1363 
1364                //销毁一个设备信息集合  
1365                SetupDiDestroyDeviceInfoList(hDevInfo);
1366 
1367               /* for(int i = 0; i <= Index; i++)
1368                {
1369                    RegCloseKey(hKey[i]);
1370                }*/
1371 
1372                /*if(ERROR_SUCCESS==RegDeleteTree(hKey[0],NULL))
1373                {
1374                    printf("Registry Has Delete Success!\n");
1375                    return ;
1376                }*/
1377 
1378                RegCloseKey(hKey[0]);
1379 
1380               DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath);
1381 
1382                 //printf("Registry Has Delete Su",GetLastError());
1383 
1384                return ;
1385            }
1386        }
1387        else
1388        {
1389           // ZeroMemory(buffer,sizeof(BYTE)*512);
1390            //ZeroMemory(buffer2,sizeof(BYTE)*512);
1391            //ZeroMemory(SubKeyName,SizeSubKeyName);
1392            //ZeroMemory(KeyPath,sizeof(WCHAR)*512);
1393            //KeyPath = NULL;
1394            //continue;
1395 
1396            printf("Search Success!\n");
1397            
1398            pSubWork = pSubStr;
1399 
1400            while((*pSubWork) != 'f')
1401            {
1402                pSubWork++;
1403            }
1404 
1405            pSubWork++;
1406 
1407            *pSubWork = '\0';
1408 
1409            WCHAR OemFileName2[128];
1410 
1411            wcscpy(OemFileName2,pSubStr);
1412 
1413            SP_DEVINFO_DATA spDevInfoData = {0};  
1414            HDEVINFO hDevInfo = 0L;  
1415            WORD wIdx, wCount = 0;  
1416 
1417            //得到设备信息结构的句柄  
1418            hDevInfo = SetupDiGetClassDevs(0L, 0L, 0L, DIGCF_ALLCLASSES | DIGCF_PRESENT);  
1419            if (hDevInfo == INVALID_HANDLE_VALUE)  
1420            {  
1421                printf("Fail!\n"); 
1422                return;  
1423            }  
1424 
1425            wIdx = 0;  
1426            while (TRUE)  
1427            {  
1428                spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);  
1429                //找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息  
1430                if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))  
1431                {  
1432                    char Buffer[2048] = {0};  
1433 
1434                   
1435 
1436                    //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息  
1437                    if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,  
1438                        0L, (PBYTE)Buffer, 2048, 0L))  
1439                    {  
1440                        
1441                        printf("SetupDiGetDeviceRegistryProperty Success!\n");
1442                        
1443                        if (!lstrcmpi(theHardware, (LPTSTR)Buffer))  
1444                        {  
1445                            
1446                            //从系统中删除一个注册的设备接口  
1447                            if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))  
1448                                printf("Remove Fail is %d!\n",GetLastError()); 
1449                            //if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
1450                            //   printf("Remove Fail is %d!\n",GetLastError());
1451                  
1452                            wCount++;  
1453                        } 
1454 
1455                       
1456                    }  
1457                }  
1458                else  
1459                    break;  
1460                wIdx++;  
1461            }  
1462 
1463            if (wCount != 0)  
1464                _tprintf(_T("UnInstall Successed...\n")); 
1465            
1466           // getch();
1467            //wprintf("%s\n",(wchar_t*)pSubStr);
1468            if(SetupUninstallOEMInf(OemFileName2, SUOI_FORCEDELETE, NULL))
1469                printf("Driver Package Has Deleted succced!\n");
1470 
1471            //销毁一个设备信息集合  
1472            SetupDiDestroyDeviceInfoList(hDevInfo);
1473 
1474            /*for(int i = 0; i <= Index; i++)
1475            {
1476                RegCloseKey(hKey[i]);
1477            }*/
1478             //
1479            /*if(ERROR_SUCCESS==RegDeleteTree(hKey[0],NULL))
1480            {
1481                printf("Registry Has Delete Success!\n");
1482                return;
1483            }*/
1484 
1485            RegCloseKey(hKey[0]);
1486 
1487            DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath);
1488 
1489            // printf("Registry Has Delete Fail! Error Code is %d\n",GetLastError());
1490 
1491 
1492            return;
1493        }
1494        
1495 
1496 
1497        
1498        
1499     }
1500 
1501     printf("Here is windows XP!\n");
1502    
1503     //getch();
1504     
1505     SP_DEVINFO_DATA spDevInfoData = {0};  
1506     HDEVINFO hDevInfo = 0L;  
1507     WORD wIdx, wCount = 0; 
1508     WCHAR oem_file_name[128] = {0};
1509     //GUID usb_guid = {36fc9e60,c465,11cf,8056,444553540000};
1510     //得到设备信息结构的句柄  
1511     hDevInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);  
1512     
1513     if (hDevInfo == INVALID_HANDLE_VALUE)  
1514     {  
1515         printf("Fail!\n");
1516         printf("SetupDiGetClassDevs Error Code is %d\n",GetLastError());
1517         return;  
1518     }  
1519 
1520     wIdx = 0; 
1521 
1522     printf("hDevInfo is %x\n",hDevInfo);
1523     
1524     while (TRUE)  
1525     {  
1526         spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);  
1527         //找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息  
1528         if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))  
1529         {  
1530 
1531              
1532              printf("SetupDiEnumDeviceInfo Success!\n");
1533             
1534              char Buffer[2048] = {0};  
1535 
1536             //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息  
1537             if (SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,  
1538                 0L, (PBYTE)Buffer, 2048, 0L))  
1539             {  
1540                 printf("SetupDiGetDeviceRegistryProperty Success!\n");
1541 
1542                 wprintf(L"Buffer is %s\n",Buffer);
1543                 
1544                 if (!lstrcmpi(theHardware, (LPTSTR)Buffer))  
1545                 {  
1546                     printf("theHardware is matched!\n");
1547                     
1548                     HKEY hDevKey;
1549                     BYTE buffer3[512] = {0};
1550                     DWORD buffer3_size = 512;
1551                     //打开有关设备注册表
1552                     hDevKey = SetupDiOpenDevRegKey(hDevInfo,&spDevInfoData, DICS_FLAG_GLOBAL,0,DIREG_DRV,KEY_ALL_ACCESS);
1553                     
1554                     if(hDevKey ==  INVALID_HANDLE_VALUE)
1555                     {
1556                         printf("SetupDiOpenRegKey Error Code is %d\n",GetLastError());
1557                     }
1558                     
1559                     if(ERROR_SUCCESS == RegQueryValueEx(hDevKey,L"InfPath",NULL,NULL,buffer3,&buffer3_size))
1560                     {
1561                        wprintf(L"Get Buffer3 Success! Buffer3 is %s\n",buffer3);
1562                     }
1563                     
1564                     wcscpy(oem_file_name,(wchar_t*)buffer3);
1565                     wprintf(oem_file_name);
1566                     printf("\n");
1567                     //getch();
1568                     RegCloseKey(hDevKey);
1569                     //从系统中删除一个注册的设备接口  
1570                     /*if (!SetupDiRemoveDevice(hDevInfo, &spDevInfoData))  
1571                     {
1572                         printf("Remove Fail is %d!\n",GetLastError());
1573                     }*/
1574                     
1575 
1576                     /*if(!SetupDiCallClassInstaller(DIF_REMOVE,hDevInfo,&spDevInfoData))
1577                       printf("Remove Fail is %d!\n",GetLastError());*/
1578                     SP_REMOVEDEVICE_PARAMS rmdParams;
1579                     SP_DEVINSTALL_PARAMS devParams;
1580 
1581                     rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
1582                     rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
1583                     rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
1584                     rmdParams.HwProfile = 0;
1585 
1586                     if(SetupDiSetClassInstallParams(hDevInfo, &spDevInfoData, &rmdParams.ClassInstallHeader, sizeof(rmdParams)) &&
1587                         SetupDiCallClassInstaller(DIF_REMOVE, hDevInfo, &spDevInfoData)) 
1588                     {
1589                         
1590                            
1591                         
1592                     }
1593                     wCount++;  
1594                 }  
1595 
1596 
1597                 
1598             }  
1599         }  
1600         else 
1601         {
1602             
1603            break;  
1604         }
1605             
1606         wIdx++;  
1607     }  
1608 
1609     if (wCount != 0)  
1610         _tprintf(_T(" UnInstall Successed on windows XP...\n")); 
1611 
1612     if(SetupUninstallOEMInf(oem_file_name, SUOI_FORCEDELETE, NULL))
1613         printf("Driver Package Has Deleted succced! on windows XP\n");
1614     
1615     
1616     //getch();
1617 
1618     //销毁一个设备信息集合  
1619     SetupDiDestroyDeviceInfoList(hDevInfo);
1620 
1621     
1622     //递归删除DeleteKeyPath下子键
1623     /*DeleteTree(HKEY_LOCAL_MACHINE,DeleteKeyPath);
1624     
1625     HKEY hKey2;//删除DeleteKeyPath键本身
1626     
1627     if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE,DeleteKeyPath,0,KEY_ALL_ACCESS,&hKey2))
1628     {
1629         printf("Can not Open Key!(Delete part!) Error Code is %d\n",GetLastError());
1630         return ;
1631     }
1632     
1633     RegDeleteKey(hKey2,DeleteKeyPath);
1634 
1635     RegCloseKey(hKey2);*/
1636 
1637     
1638     
1639     //InitialGlobalVar();  
1640     return;  
1641 }
1642 
1643 BOOL UnicodeToAnsi(LPCWSTR Source, const WORD wLen, LPSTR Destination, const WORD sLen)  
1644 {  
1645     return WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, Source, wLen, Destination, 
1646         sLen, 0L, 0L);  
1647 }  
1648 
1649 BOOL AnsiToUnicode(LPCSTR Source, const WORD sLen, LPWSTR Destination, const WORD wLen)  
1650 {  
1651     return MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Source, sLen, Destination, wLen);  
1652 }  
1653 
1654 
1655 /*BOOL GetINFData(FILE *pFile)  
1656 {  
1657     WORD wLoop;  
1658 
1659     if (!g_wVender || !g_wHardware)  
1660         InitialGlobalVar();  
1661     if (GetSectionData(pFile, "[Manufacturer]", TRUE) == FALSE)  
1662         return FALSE;  
1663 
1664     //rewind(pFile);
1665 
1666     for (wLoop = 0; wLoop < g_wVender; wLoop++)  
1667     {  
1668         CHAR szVender[64] = {0};  
1669         UnicodeToAnsi(g_strVender[wLoop], _tcslen(g_strVender[wLoop]), szVender, 64);  
1670         GetSectionData(pFile, "Device.NTamd64", FALSE);  
1671     }  
1672     if (g_wHardware != 0)  
1673     {  
1674         if (IsInstalled() == TRUE)//如果已经安装  
1675             return FALSE;  
1676         else  
1677             return TRUE;  
1678     }  
1679     return FALSE;  
1680 } */ 
1681 
1682 /*VOID InitialGlobalVar()  
1683 {  
1684     WORD wLoop;  
1685 
1686     g_wVender = g_wHardware = 0;  
1687     for (wLoop = 0; wLoop < 20; wLoop++)  
1688     {  
1689         RtlZeroMemory(g_strVender[wLoop], sizeof(TCHAR)*64);  
1690         RtlZeroMemory(g_strHardware[wLoop], sizeof(TCHAR)*64);  
1691     }  
1692 }  */
1693 
1694 VOID FindComma(LPSTR szData)  
1695 {  
1696     WORD wLen = (WORD)strlen(szData);  
1697     WORD wIdx;  
1698     WORD wLoop;   
1699     CHAR szTmp[128] = {0};  
1700 
1701     for (wIdx = 0, wLoop = 0; wLoop < wLen; wLoop++)  
1702     {  
1703         if (szData[wLoop] == ',')  
1704             szData[wLoop] = '.';  
1705         else if (szData[wLoop] == ' ')  
1706             continue;  
1707         szTmp[wIdx++] = szData[wLoop];  
1708     }  
1709     memcpy(szData, szTmp, wIdx*sizeof(char));  
1710     szData[wIdx] = 0;  
1711 }  
1712 
1713 VOID StrLTrim(LPSTR szData)  
1714 {  
1715     LPSTR ptr = szData;  
1716     //判断是否为空格  
1717     while (isspace(*ptr))  
1718         ptr++;  
1719 
1720     if (strcmp(ptr, szData))  
1721     {  
1722         WORD wLen = (WORD)(strlen(szData) - (ptr - szData));  
1723         memmove(szData, ptr, (wLen+1)*sizeof(char));  
1724     }  
1725 }  
1726 
1727 VOID StrRTrim(LPSTR szData)  
1728 {  
1729     LPSTR ptr  = szData;  
1730     LPSTR pTmp = NULL;  
1731 
1732     //debug模式下 使用isspace判断中文 需要设置编码  
1733 #if defined(WIN32) && defined(_DEBUG)  
1734     char* locale = setlocale( LC_ALL, ".OCP" );  
1735 #endif   
1736 
1737     while (*ptr != 0)  
1738     {  
1739         //判断是否为空格  
1740         if (isspace(*ptr))  
1741         {  
1742             if (!pTmp)  
1743                 pTmp = ptr;  
1744         }  
1745         else  
1746             pTmp = NULL;  
1747         ptr++;  
1748     }  
1749 
1750     if (pTmp)  
1751     {  
1752         *pTmp = 0;  
1753         memmove(szData, szData, strlen(szData) - strlen(pTmp));  
1754     }  
1755 }  
1756 
1757 //从字符串右边开始截取字符串  
1758 VOID StrRight(LPSTR szData, WORD wCount)  
1759 {  
1760     WORD wLen = (WORD)strlen(szData) - wCount;  
1761 
1762     if (wCount > 0x7FFF)//负数  
1763         wCount = 0;  
1764     if (wCount >= (WORD)strlen(szData))  
1765         return;  
1766 
1767     memmove(szData, szData + wLen, wCount * sizeof(char));  
1768     szData[wCount] = 0;  
1769 }  
1770 
1771 VOID ConvertGUIDToString(const GUID guid, LPSTR pData)  
1772 {  
1773     CHAR szData[30] = {0};  
1774     CHAR szTmp[3]   = {0};  
1775     WORD wLoop;  
1776 
1777     sprintf_s(pData, _countof(szData), "%04X-%02X-%02X-", guid.Data1, guid.Data2, guid.Data3);  
1778     for (wLoop = 0; wLoop < 8; wLoop++)  
1779     {  
1780         if (wLoop == 2)  
1781             strcat_s(szData, "-");  
1782         sprintf_s(szTmp, _countof(szTmp), "%02X", guid.Data4[wLoop]);  
1783         strcat_s(szData, szTmp);  
1784     }  
1785 
1786     memcpy(pData + strlen(pData), szData, strlen(szData));  
1787 }  
1788 
1789 /*BOOL IsInstalled()  
1790 {  
1791     HDEVINFO hDevInfo = 0L;  
1792     SP_DEVINFO_DATA spDevInfoData = {0L};  
1793     WORD wIdx;  
1794     BOOL bIsFound;  
1795 
1796     //得到设备信息结构的句柄  
1797     hDevInfo = SetupDiGetClassDevs(0L, 0, 0, DIGCF_ALLCLASSES | DIGCF_PRESENT);  
1798     if (hDevInfo == INVALID_HANDLE_VALUE)  
1799     {  
1800         printf("SetupDiGetClassDevs is %d",GetLastError());  
1801         return FALSE;  
1802     }  
1803 
1804     spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);  
1805     wIdx = 0;  
1806     bIsFound = 0;  
1807     while (++wIdx)  
1808     {  
1809         //找到所有的硬件设备,并且可以得到所有的硬件设备的详细信息  
1810         if (SetupDiEnumDeviceInfo(hDevInfo, wIdx, &spDevInfoData))  
1811         {  
1812             LPTSTR ptr;  
1813             LPBYTE pBuffer = NULL;  
1814             DWORD dwData  = 0L;  
1815             DWORD dwRetVal;  
1816             DWORD dwBufSize = 0L;  
1817 
1818             while (TRUE)  
1819             {  
1820                 //可以在前面得到的指向某一个具体设备信息集合的指针中取出某一项信息  
1821                 dwRetVal = SetupDiGetDeviceRegistryProperty(hDevInfo, &spDevInfoData, SPDRP_HARDWAREID,  
1822                     &dwData, (PBYTE)pBuffer, dwBufSize, &dwBufSize);  
1823                 if (!dwRetVal)  
1824                     dwRetVal = GetLastError();  
1825                 else  
1826                     break;  
1827                 if (dwRetVal == ERROR_INVALID_DATA)  
1828                     break;  
1829                 else if (dwRetVal == ERROR_INSUFFICIENT_BUFFER)  
1830                 {  
1831                     if (pBuffer)  
1832                         LocalFree(pBuffer);  
1833                     pBuffer = (LPBYTE)LocalAlloc(LPTR, dwBufSize);  
1834                 }  
1835                 else  
1836                 {  
1837                     printf("SetupDiGetDeviceRegistryProperty is %d",dwRetVal);  
1838                     //销毁一个设备信息集合  
1839                     SetupDiDestroyDeviceInfoList(hDevInfo);  
1840                     return FALSE;  
1841                 }  
1842             }  
1843 
1844             if (dwRetVal == ERROR_INVALID_DATA)   
1845                 continue;  
1846 
1847             for (ptr = (LPTSTR)pBuffer; *ptr && (ptr < (LPTSTR)&pBuffer[dwBufSize]); ptr += _tcslen(ptr) + sizeof(TCHAR))  
1848             {  
1849                 WORD wLoop;  
1850 
1851                 for (wLoop = 0; wLoop < g_wHardware; wLoop++)  
1852                 {  
1853                     if (!_tcscmp(g_strHardware[wLoop], ptr))  
1854                     {  
1855                         bIsFound = TRUE;  
1856                         break;  
1857                     }  
1858                 }  
1859             }  
1860             if (pBuffer)  
1861                 LocalFree(pBuffer);  
1862             if (bIsFound)  
1863                 break;  
1864         }  
1865     }  
1866     //销毁一个设备信息集合  
1867     SetupDiDestroyDeviceInfoList(hDevInfo);  
1868     return bIsFound;  
1869 }  */
1870 
1871 //寻找指定的节名 如果找到返回TRUE 反之返回FALSE  
1872 BOOL FindSectionName(FILE *pFile, const char *szKey)  
1873 {  
1874     char szData[256] = {0};  
1875 
1876     if (!pFile)  
1877         return FALSE;  
1878 
1879     //将文件内部的位置指针重新指向一个流(数据流/文件)的开头  
1880     rewind(pFile);  
1881     //循环读取文件内容  
1882     while (!feof(pFile))  
1883     {  
1884         //读取一行  
1885         fgets(szData, 255, pFile);  
1886         //去除前后空格  
1887         StrLTrim(szData);  
1888         StrRTrim(szData);  
1889 
1890         if (strcmp(szKey, szData) == 0)  
1891             return TRUE;          
1892     }  
1893     return FALSE;  
1894 }  
1895 
1896 //得到INF文件中节的数量  
1897 /*BOOL GetSectionData(FILE* pFile, const char* szKey, const char bIsVender)  
1898 {  
1899     char szData[128] = {0};  
1900 
1901     if (bIsVender)  
1902         strcpy_s(szData, szKey);  
1903     else  
1904         sprintf_s(szData, _countof(szData), "[%s]", szKey);  
1905 
1906     if (FindSectionName(pFile, szData) == FALSE)  
1907         return FALSE;  
1908 
1909     RtlZeroMemory(szData, sizeof(char)*128);  
1910     while (!feof(pFile))  
1911     {  
1912         char *str = NULL;  
1913         fgets(szData, 127, pFile);  
1914         szData[strlen(szData)-1] = 0;  
1915         StrLTrim(szData);  
1916         StrRTrim(szData);  
1917         if (!*szData)  
1918             continue;  
1919         if (szData[0] == ';')  
1920             continue;  
1921 
1922         if (strchr(szData, '['))  
1923         {  
1924             StrLTrim(szData);  
1925             if (szData[0] != ';')  
1926                 return 1;  
1927             else  
1928                 continue;  
1929         }  
1930 
1931         if (bIsVender)  
1932             str = strchr(szData, '=');  
1933         else  
1934             str = strchr(szData, ',');  
1935 
1936         if (*str)  
1937         {  
1938             char szTmp[128] = {0};  
1939             WORD pos = (WORD)(str - szData + 1);  
1940 
1941             StrRight(szData, (short)(strlen(szData)-pos));  
1942             StrLTrim(szData);  
1943             StrRTrim(szData);  
1944             FindComma(szData);  
1945             if (bIsVender)  
1946             {  
1947                 AnsiToUnicode(szData, strlen(szData), g_strVender[g_wVender++], 64);  
1948             }  
1949             else  
1950             {  
1951                 AnsiToUnicode(szData, strlen(szData), g_strHardware[g_wHardware++], 64);  
1952             }  
1953         } //end if   
1954     }  
1955     return TRUE;  
1956 }  */
1957 
1958 //实质性的安装驱动  
1959 BOOL InstallClassDriver(LPCTSTR theINFName)  
1960 {  
1961     GUID guid = {0};  
1962     SP_DEVINFO_DATA spDevData = {0};  
1963     HDEVINFO hDevInfo = 0L;  
1964     TCHAR className[MAX_CLASS_NAME_LEN] = {0};  
1965     LPTSTR pHID = NULL;  
1966     WORD wLoop;  
1967     BOOL bRebootRequired;  
1968 
1969     //取得此驱动的GUID值  ,className也是输出参数
1970     if (!SetupDiGetINFClass(theINFName, &guid, className, MAX_CLASS_NAME_LEN, 0))  
1971     {  
1972         printf( "SetupDiGetINFClass is %d\n",GetLastError());  
1973         return FALSE;  
1974     }  
1975 
1976     //创建设备信息块列表  
1977     hDevInfo = SetupDiCreateDeviceInfoList(&guid, 0);  
1978     if (hDevInfo == INVALID_HANDLE_VALUE)  
1979     {  
1980         printf("SetupDiCreateDeviceInfoList is %d\n",GetLastError());  
1981         return FALSE;  
1982     }  
1983 
1984     spDevData.cbSize = sizeof(SP_DEVINFO_DATA);  
1985     //创建设备信息块  
1986     if (!SetupDiCreateDeviceInfo(hDevInfo, className, &guid, 0L, 0L, DICD_GENERATE_ID, &spDevData))  
1987     {  
1988         printf("SetupDiCreateDeviceInfo is %d",GetLastError());  
1989         //销毁一个设备信息集合  
1990         SetupDiDestroyDeviceInfoList(hDevInfo);  
1991         return FALSE;  
1992     }  
1993 
1994     // for (wLoop = 0; wLoop < g_wHardware; wLoop++)  
1995     //{  
1996     if (pHID)  
1997         LocalFree(pHID);  
1998 
1999 
2000 
2001     pHID = (LPTSTR)LocalAlloc(LPTR, _tcslen(L"USB\\VID_0451&PID_AF32")*2*sizeof(TCHAR));  
2002     if (!pHID)  
2003     {  
2004         printf("LocalAlloc is %d",GetLastError());  
2005         //销毁一个设备信息集合  
2006         SetupDiDestroyDeviceInfoList(hDevInfo);  
2007         return FALSE;  
2008     }  
2009 
2010     _tcscpy_s(pHID, _tcslen(L"USB\\VID_0451&PID_AF32")*2, 
2011         L"USB\\VID_0451&PID_AF32");  
2012     //设定硬件ID  
2013     if (!SetupDiSetDeviceRegistryProperty(hDevInfo, &spDevData, SPDRP_HARDWAREID, (PBYTE)pHID,  
2014         (DWORD)(_tcslen(L"USB\\VID_0451&PID_AF32")*2*sizeof(TCHAR))))  
2015     {  
2016         printf("SetupDiSetDeviceRegistryProperty is %d",GetLastError());  
2017         //销毁一个设备信息集合  
2018         SetupDiDestroyDeviceInfoList(hDevInfo);  
2019         LocalFree(pHID);  
2020         return FALSE;  
2021     }  
2022     //调用相应的类程序来注册设备  
2023     if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, hDevInfo, &spDevData))  
2024     {  
2025         printf("SetupDiCallClassInstaller is %d", GetLastError());  
2026         //销毁一个设备信息集合  
2027         SetupDiDestroyDeviceInfoList(hDevInfo);  
2028         LocalFree(pHID);  
2029         return FALSE;  
2030     }  
2031 
2032     bRebootRequired = FALSE;  
2033     //安装更新和硬件ID相匹配的驱动程序  
2034     if (!UpdateDriverForPlugAndPlayDevices(0L, L"USB\\VID_0451&PID_AF32"
2035         , theINFName,   
2036         INSTALLFLAG_FORCE, &bRebootRequired))  
2037     {  
2038         DWORD dwErrorCode = GetLastError();  
2039         //调用相应的类程序来移除设备  
2040         if (!SetupDiCallClassInstaller(DIF_REMOVE, hDevInfo, &spDevData))  
2041             printf("SetupDiCallClassInstaller(Remove) is %d",GetLastError());  
2042         printf("UpdateDriverForPlugAndPlayDevices is %d",(WORD)dwErrorCode);  
2043         //销毁一个设备信息集合  
2044         SetupDiDestroyDeviceInfoList(hDevInfo);  
2045         LocalFree(pHID);
2046 
2047         //getch();
2048         return FALSE;  
2049     }  
2050     LocalFree(pHID);  
2051     pHID = NULL;  
2052 
2053     // }  
2054     //销毁一个设备信息集合  
2055     SetupDiDestroyDeviceInfoList(hDevInfo);  
2056     _tprintf(_T("Install Successed\n"));  
2057     return TRUE;  
2058 }  
2059 
2060 // 安装WDM驱动的测试工作  
2061 BOOL StartInstallWDMDriver(LPCTSTR theInfName)  
2062 {  
2063     HDEVINFO hDevInfo = 0L;  
2064     GUID guid = {0L};  
2065     SP_DEVINSTALL_PARAMS spDevInst = {0L};  
2066     TCHAR strClass[MAX_CLASS_NAME_LEN] = {0L};  
2067 
2068     //取得此驱动的GUID值  
2069     if (!SetupDiGetINFClass(theInfName, &guid, strClass, MAX_CLASS_NAME_LEN, 0))  
2070     {  
2071         printf("SetupDiGetINFClass is %d",GetLastError());  
2072         return FALSE;  
2073     }  
2074 
2075     //得到设备信息结构的句柄  
2076     hDevInfo = SetupDiGetClassDevs(&guid, 0L, 0L, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_PROFILE);  
2077     if (!hDevInfo)  
2078     {  
2079         printf("SetupDiGetClassDevs is %d",GetLastError());  
2080         return FALSE;  
2081     }  
2082 
2083 
2084     spDevInst.cbSize = sizeof(SP_DEVINSTALL_PARAMS);  
2085     //获得指定设备的安装信息  
2086     if (!SetupDiGetDeviceInstallParams(hDevInfo, 0L, &spDevInst))  
2087     {  
2088         printf("SetupDiGetDeviceInstallParams is %d",GetLastError());  
2089         return FALSE;  
2090     }  
2091 
2092     spDevInst.Flags   = DI_ENUMSINGLEINF;  
2093     spDevInst.FlagsEx = DI_FLAGSEX_ALLOWEXCLUDEDDRVS;  
2094     _tcscpy_s(spDevInst.DriverPath, _countof(spDevInst.DriverPath), theInfName);  
2095 
2096     //为设备信息集或者是一个实际的设备信息单元设置或清除类安装参数  
2097     if (!SetupDiSetDeviceInstallParams(hDevInfo, 0, &spDevInst))  
2098     {  
2099 
2100         printf("SetupDiSetDeviceInstallParams is %d",GetLastError());  
2101         return FALSE;  
2102     }  
2103 
2104     //获取这个设备的驱动程序信息列表  
2105     if (!SetupDiBuildDriverInfoList(hDevInfo, 0, SPDIT_CLASSDRIVER))  
2106     {  
2107 
2108         printf("SetupDiDeviceInstallParams is %d",GetLastError());
2109         return FALSE;  
2110     }  
2111 
2112     //销毁一个设备信息集合  
2113     SetupDiDestroyDeviceInfoList(hDevInfo);  
2114 
2115     //进入安装设备驱动函数  
2116     return InstallClassDriver(theInfName);  
2117 }  
2118 
2119 BOOL FindExistingDevice(IN LPTSTR HardwareId)
2120 {
2121     HDEVINFO DeviceInfoSet;
2122     SP_DEVINFO_DATA DeviceInfoData;
2123     DWORD i,err;
2124     BOOL Found;
2125 
2126     //
2127     // Create a Device Information Set with all present devices.
2128     //
2129     DeviceInfoSet = SetupDiGetClassDevs(NULL, // All Classes
2130         0,
2131         0,
2132         DIGCF_ALLCLASSES | DIGCF_PRESENT ); // All devices present on system
2133 
2134     if (DeviceInfoSet == INVALID_HANDLE_VALUE)
2135     {
2136         return printf("GetClassDevs(All Present Devices)");
2137 
2138 
2139     }
2140 
2141     //_tprintf(TEXT("Search for Device ID: [%s]/n"),HardwareId);
2142 
2143     //
2144     //  Enumerate through all Devices.
2145     //
2146     Found = FALSE;
2147     DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
2148     for (i=0;SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData);i++)
2149     {
2150         DWORD DataT;
2151         LPTSTR p,buffer = NULL;
2152         DWORD buffersize = 0;
2153 
2154         //
2155         // We won't know the size of the HardwareID buffer until we call
2156         // this function. So call it with a null to begin with, and then
2157         // use the required buffer size to Alloc the nessicary space.
2158         // Keep calling we have success or an unknown failure.
2159         //
2160         while (!SetupDiGetDeviceRegistryProperty(
2161             DeviceInfoSet,
2162             &DeviceInfoData,
2163             SPDRP_HARDWAREID,
2164             &DataT,
2165             (PBYTE)buffer,
2166             buffersize,
2167             &buffersize))
2168         {
2169             if (GetLastError() == ERROR_INVALID_DATA)
2170             {
2171                 //
2172                 // May be a Legacy Device with no HardwareID. Continue.
2173                 //
2174                 break;
2175             }
2176             else if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
2177             {
2178                 //
2179                 // We need to change the buffer size.
2180                 //
2181                 if (buffer)
2182                     LocalFree(buffer);
2183                 buffer = (LPTSTR)LocalAlloc(LPTR,buffersize);
2184             }
2185             else
2186             {
2187                 //
2188                 // Unknown Failure.
2189                 //
2190                 printf("GetDeviceRegistryProperty");
2191                 goto cleanup_DeviceInfo;
2192             }
2193         }
2194 
2195         if (GetLastError() == ERROR_INVALID_DATA)
2196             continue;
2197 
2198         //
2199         // Compare each entry in the buffer multi-sz list with our HardwareID.
2200 
2201 
2202         //
2203         for (p=buffer;*p&&(p<&buffer[buffersize]);p+=lstrlen(p)+sizeof(TCHAR))
2204 
2205 
2206         {
2207             //_tprintf(TEXT("Compare device ID: [%s]/n"),p);
2208 
2209             if (!_tcscmp(HardwareId,p))
2210             {
2211                 //_tprintf(TEXT("Found! [%s]/n"),p);
2212                 Found = TRUE;
2213                 break;
2214             }
2215         }
2216 
2217         if (buffer) LocalFree(buffer);
2218         if (Found) break;
2219     }
2220 
2221     if (GetLastError() != NO_ERROR)
2222     {
2223         printf("EnumDeviceInfo");
2224     }
2225 
2226     //
2227     //  Cleanup.
2228     //
2229 cleanup_DeviceInfo:
2230     err = GetLastError();
2231     SetupDiDestroyDeviceInfoList(DeviceInfoSet);
2232     SetLastError(err);
2233 
2234     return err == NO_ERROR; //???
2235 }
2236 
2237 BOOL ConfigRight(WCHAR* szPath)
2238 {
2239     if (szPath == NULL)
2240     {
2241         return FALSE;
2242     }
2243     /*BOOL bRet = TRUE;
2244 
2245     SE_OBJECT_TYPE objectType;
2246     PACL newDACL;
2247     objectType = SE_REGISTRY_KEY;
2248 
2249     if (SetEntriesInAclW(0, NULL, NULL, &newDACL) != ERROR_SUCCESS)
2250     {
2251         return FALSE;
2252     }
2253 
2254     DWORD dwRet = 0;
2255 
2256     EXPLICIT_ACCESSW ea;
2257     memset(&ea, 0, sizeof(EXPLICIT_ACCESS));
2258 
2259     BuildExplicitAccessWithNameW(&ea,L"Everyone", KEY_ALL_ACCESS, SET_ACCESS, SUB_CONTAINERS_AND_OBJECTS_INHERIT);
2260 
2261     if (SetEntriesInAclW(1, &ea, NULL, &newDACL) != ERROR_SUCCESS)
2262     {
2263         bRet = FALSE;
2264         goto Clean_Up;
2265     }
2266     DWORD ret;
2267 
2268     //调用失败,访问被拒绝
2269     if (ERROR_SUCCESS!= (ret = SetNamedSecurityInfoW(szPath, objectType, DACL_SECURITY_INFORMATION, NULL, NULL, newDACL, NULL)))
2270     {
2271         bRet = FALSE;
2272         printf("ret value is %d\n",ret);
2273         goto Clean_Up;
2274     }
2275 
2276 Clean_Up:
2277     if (newDACL != NULL)
2278     {
2279         LocalFree((HLOCAL)newDACL);
2280     }*/
2281     PACL pOldDacl=NULL;
2282     PACL pNewDacl=NULL;
2283     DWORD dRet;
2284     EXPLICIT_ACCESS eia;
2285     PSECURITY_DESCRIPTOR pSID=NULL;
2286     
2287     dRet = GetNamedSecurityInfo(szPath,SE_REGISTRY_KEY,DACL_SECURITY_INFORMATION,NULL,NULL,&pOldDacl,NULL,&pSID);// 获取SAM主键的DACL  
2288     
2289     if(dRet!=ERROR_SUCCESS)
2290     {
2291         return 0;
2292     }
2293     //创建一个ACE,允许Everyone组成员完全控制对象,并允许子对象继承此权限
2294     ZeroMemory(&eia,sizeof(EXPLICIT_ACCESS));
2295     BuildExplicitAccessWithName(&eia,L"SYSTEM",KEY_ALL_ACCESS,SET_ACCESS,SUB_CONTAINERS_AND_OBJECTS_INHERIT);
2296     // 将新的ACE加入DACL  
2297     dRet = SetEntriesInAcl(1,&eia,pOldDacl,&pNewDacl);
2298     if(dRet!=ERROR_SUCCESS)
2299     {
2300         return 0;
2301     }
2302     // 更新SAM主键的DACL  
2303     dRet = SetNamedSecurityInfo(szPath,SE_REGISTRY_KEY,DACL_SECURITY_INFORMATION,NULL,NULL,pNewDacl,NULL);
2304     
2305     if(dRet!=ERROR_SUCCESS)
2306     {
2307         printf("%d\n",dRet);
2308         return 0;
2309     }
2310     //return bRet;
2311 }
2312 
2313 
2314 DWORD DeleteTree(HKEY RootKey, const WCHAR *pSubKey)
2315 {
2316 
2317     HKEY hKey;
2318     DWORD nRet;
2319     DWORD NameCnt,NameMaxLen;
2320     DWORD KeyCnt,KeyMaxLen,MaxDateLen;
2321     //static WCHAR sFormat[256] = L"";
2322     //wcscat(sFormat, L"----");
2323 
2324     static int dwDeep = -1;
2325     dwDeep++;
2326 
2327     nRet=RegOpenKeyEx(RootKey,pSubKey,0,KEY_ALL_ACCESS,&hKey);
2328     if(nRet!=ERROR_SUCCESS)
2329     {
2330         printf("Can not Open Key!(Delete part!) Error Code is %d\n",GetLastError());
2331         return 0;
2332     }
2333 
2334 
2335     nRet = RegQueryInfoKey(hKey,NULL,NULL,NULL,&KeyCnt,&KeyMaxLen,NULL,&NameCnt,
2336         &NameMaxLen,&MaxDateLen,NULL,NULL);
2337     
2338     if(nRet == ERROR_SUCCESS)
2339     {
2340         printf("RegQueryInfoKey Success!\n");
2341         
2342         for(int dwIndex = KeyCnt - 1; dwIndex >= 0; dwIndex--) //枚举键值
2343         {
2344             WCHAR sKeyName[256] = {0};
2345             RegEnumKey(hKey, dwIndex, sKeyName, sizeof(sKeyName));
2346 
2347             HKEY hKeySub;
2348             DWORD KeyCntSub;
2349             WCHAR pSubKeyTemp[256] = {0};
2350             wcscpy(pSubKeyTemp, pSubKey);
2351             wcscat(pSubKeyTemp, L"\\");
2352             wcscat(pSubKeyTemp, sKeyName);
2353 
2354             nRet = RegOpenKeyEx(RootKey,pSubKeyTemp,0,KEY_ALL_ACCESS,&hKeySub);
2355             
2356             if(nRet == ERROR_SUCCESS)
2357             {
2358                 printf("RegOpenKeyEx Success!\n");
2359                 
2360                 nRet = RegQueryInfoKey(hKeySub,NULL,NULL,NULL,&KeyCntSub,&KeyMaxLen,NULL,&NameCnt,
2361                     &NameMaxLen,&MaxDateLen,NULL,NULL);
2362                 
2363                 if(nRet == ERROR_SUCCESS)
2364                 {
2365                     if (KeyCntSub != 0)
2366                     {
2367                         DeleteTree(RootKey, pSubKeyTemp);
2368                     }
2369                     
2370                     RegCloseKey(hKeySub);
2371                 }
2372             }
2373 
2374             // cout << sFormat << sKeyName << endl;
2375 
2376             RegDeleteKey(RootKey ,pSubKeyTemp);
2377         }
2378 
2379         RegCloseKey(hKey);
2380     }
2381 
2382     // sFormat[strlen(sFormat) - 4] = 0;
2383 
2384     if (dwDeep == 0)
2385     {
2386         RegDeleteKey(RootKey ,pSubKey);
2387     }
2388 
2389     return 0;
2390 }
2391 
2392 VOID SearchRegistryHardID(PWCHAR pHardIDBuffer)
2393 {
2394     const PWCHAR pReg = L"SYSTEM\\CurrentControlSet\\Enum\\USB";
2395     HKEY hKey;
2396     
2397     if(ERROR_SUCCESS !=RegOpenKeyEx(HKEY_LOCAL_MACHINE,pReg,0,KEY_ALL_ACCESS,&hKey))
2398         printf("in SearchOpenKey Fail! error code is %d\n",GetLastError());
2399     
2400     DWORD Index = 0;
2401     WCHAR SubKeyName[215] = {0};
2402 
2403     while(ERROR_SUCCESS == RegEnumKey(hKey,Index,SubKeyName,sizeof(WCHAR)*215))
2404     {
2405         if(!lstrcmpi(SubKeyName,L"VID_0451&PID_AF32"))
2406         {
2407             wcscpy(pHardIDBuffer,L"VID_0451&PID_AF32");
2408             RegCloseKey(hKey);
2409             return;
2410         }
2411 
2412         else if(!lstrcmpi(SubKeyName,L"VID_04B41&PID_8613"))
2413         {
2414            wcscpy(pHardIDBuffer,L"VID_04B41&PID_8613");
2415            RegCloseKey(hKey);
2416             return;
2417         }
2418 
2419         else if(!lstrcmpi(SubKeyName,L"VID_0547&PID_1002"))
2420         {
2421             wcscpy(pHardIDBuffer,L"VID_0547&PID_1002");
2422             RegCloseKey(hKey);
2423             return;
2424         }
2425 
2426         ZeroMemory(SubKeyName,sizeof(WCHAR)*215);
2427         
2428         Index++;
2429     }
2430 
2431 }
Setup.cpp


 

  1 // InstallWDFDriver.cpp : Defines the entry point for the console application.
  2 //
  3 
  4 #include "stdafx.h"
  5 #include "setup.h"
  6 #include "Shlwapi.h"
  7 
  8 
  9 #pragma  comment(lib,"Shlwapi.lib")
 10 
 11 BOOL SystemShutdown();
 12 
 13 int _tmain(int argc, _TCHAR* argv[])
 14 {
 15     WCHAR Wlp_USB_PATH[] = L"C:\\Windows\\System32\\drivers\\WLP_USB_Driver.sys";
 16     //WCHAR Wdf_USB_PATH[] = L"C:\\Windows\\System32\\drivers\\CYUSB3.sys";
 17     WCHAR New_Inf_Path[] = L"D:\\wlp driver\\WDF Driver _new\\win7\\x64\\cyusb3.inf";
 18     WCHAR InfFileName[] = L"\\cyusb3.inf";
 19     CHAR szInfPath[215] = {0}; 
 20     FILE *fp = NULL;
 21 
 22     WCHAR CurrentDirBuffer[215] = {0};
 23     WCHAR OutCurrentDirBuffer[215] = {0};
 24 
 25 
 26     GetModuleFileName(NULL,CurrentDirBuffer,_countof(CurrentDirBuffer));
 27     //GetCurrentDirectory(215,CurrentDirBuffer);
 28     //lstrcat(CurrentDirBuffer, InfFileName);
 29     _wsplitpath_s(CurrentDirBuffer,NULL,0,OutCurrentDirBuffer,_countof(OutCurrentDirBuffer),
 30         NULL,0,NULL,0);
 31     printf("This Process is Driver Installtion Program...\n");
 32 
 33 
 34    //getch();
 35     //WCHAR HIDBuffer[128] = {0};
 36 
 37 
 38 
 39     if(PathFileExists(Wlp_USB_PATH))
 40     {
 41         printf("Exists WLP_USB_Driver.sys!\n");
 42 
 43         //SearchRegistryHardID(HIDBuffer);
 44 
 45         //WCHAR HardID[215] = L"USB\\";
 46 
 47         //wcscat(HardID,HIDBuffer);
 48         //getch();
 49 
 50         UninstallWDMDriver(L"USB\\VID_0451&PID_AF32&REV_0000");
 51 
 52 
 53 
 54 
 55         if(DeleteFile(Wlp_USB_PATH))
 56         {
 57             printf("WLP_USB_Driver.sys File has Deleted!\n");
 58         }
 59 
 60          // getch();
 61 
 62         /* if(FindExistingDevice(L"USB\\VID_0451&PID_AF32&REV_0000"))
 63         {
 64         printf("找打了!\n");
 65 
 66         getch();
 67         }
 68         else
 69         {
 70         printf("没找到!\n");
 71         getch();
 72         }*/
 73 
 74         printf("Get Started Install the New DLF Driver...\n");
 75 
 76         //  RemoveDriver(L"USB\\VID_0451&PID_AF32&REV_0000");
 77         while(IsDeviceInstallInProgress())
 78         {
 79             printf("Has Driver Installtion Program is Processing!\n");
 80         }
 81 
 82         printf("Get Started analyse inf File!\n");
 83 
 84 
 85 
 86         UnicodeToAnsi(New_Inf_Path, _tcslen(New_Inf_Path), szInfPath, 215); 
 87 
 88         FindAllInfFiles(OutCurrentDirBuffer/* L"D:\\wlp driver\\WDF Driver _new\\win7\\x64"*/);
 89 
 90         for(int i = 0; i < g_nHIDCount; i++)
 91             g_HIDInfo[i]->bNeedUpdate = false;
 92 
 93         for(int i = 0; i < g_nInfCount; i++)
 94             g_InfList[i]->bWillBeInstall = false;
 95 
 96         int SearchInfIndex = 0;
 97 
 98         while(SearchInfIndex < g_nInfCount)
 99         {
100             if(g_InfList[SearchInfIndex] != NULL)
101             {
102                 g_InfList[SearchInfIndex]->bWillBeInstall = TRUE;
103             }
104 
105             SearchInfIndex++;
106         }
107 
108 
109         InstallDriver();
110 
111         
112         //UpdateDriver();
113         printf("Install Successed!\n");
114         //if ((fopen_s(&fp, szInfPath, "r"))!=0)  
115         //{  
116         //  _tprintf(_T("can not open file %s\n"), CurrentDirBuffer);  
117         //return 0;  
118         //}  
119 
120         // GetINFData(fp);  
121         // fclose(fp);  
122 
123         // 安装WDM驱动  
124 
125         /*if (StartInstallWDMDriver(New_Inf_Path) == FALSE)  
126         {  
127         _tprintf(_T("Start Install WDF Driver failed\n")); 
128         getch();
129         return 0;  
130         }  */
131 
132         /*if(IDOK == MessageBox(NULL,L"Need to Restart the System to Complete Installation!",
133             L"Tip",MB_OK))
134         {
135            if(SystemShutdown())
136            {
137               printf("ShutDown the System And Restart the System!\n");
138            }
139           
140         }*/
141 
142         //getch();
143 
144         printf("Press any key to continue!\n");
145 
146 
147 
148 
149     }
150     else
151     {
152         printf("No Exists WLP_USB_Driver.sys!\n");
153 
154         //getch();
155 
156         UninstallWDMDriver(L"USB\\VID_0451&PID_AF32&REV_0000");
157 
158 
159 
160         printf("Get Started Install the New DLF Driver...\n");
161 
162 
163         printf("Get Started analyse inf File!\n");
164 
165         UnicodeToAnsi(New_Inf_Path, _tcslen(New_Inf_Path), szInfPath, 215); 
166 
167         /*if ((fopen_s(&fp, szInfPath, "r"))!=0)  
168         {  
169         _tprintf(_T("can not open file %s\n"), CurrentDirBuffer);  
170         return 0;  
171         }  */
172 
173         // GetINFData(fp);  
174         //fclose(fp);  
175 
176         // 安装WDM驱动  
177 
178         /*if (StartInstallWDMDriver(New_Inf_Path) == FALSE)  
179         {  
180         _tprintf(_T("Start Install WDF Driver failed\n")); 
181         getch();
182         return 0;  
183         }  */
184 
185         FindAllInfFiles( OutCurrentDirBuffer/*L"D:\\wlp driver\\WDF Driver _new\\win7\\x64"*/);
186 
187         for(int i = 0; i < g_nHIDCount; i++)
188             g_HIDInfo[i]->bNeedUpdate = false;
189 
190         for(int i = 0; i < g_nInfCount; i++)
191             g_InfList[i]->bWillBeInstall = false;
192 
193         int SearchInfIndex = 0;
194 
195         while(SearchInfIndex < g_nInfCount)
196         {
197             if(g_InfList[SearchInfIndex] != NULL)
198             {
199                 g_InfList[SearchInfIndex]->bWillBeInstall = TRUE;
200             }
201 
202             SearchInfIndex++;
203         }
204 
205 
206         InstallDriver();
207 
208 
209         printf("Install Successed!\n"); 
210 
211         /*if(IDOK == MessageBox(NULL,L"Need to Restart the System to Complete Installation!",
212             L"Tip",MB_OK))
213         {
214             if(SystemShutdown())
215             {
216                 printf("ShutDown the System And Restart the System!\n");
217             }
218             
219         }*/
220 
221         //getch();
222 
223         printf("Press any key to continue!\n");
224 
225 
226 
227 
228     }
229 
230     
231     
232     
233 
234     return 0;
235 }
236 
237 BOOL SystemShutdown()
238 {
239     HANDLE hToken;
240     
241     TOKEN_PRIVILEGES tkp;
242     /* OpenProcessToken() 这个函数的作用是打开一个进程的访问令牌
243     GetCurrentProcess() 函数的作用是得到本进程的句柄*/
244     if (!OpenProcessToken(GetCurrentProcess(),
245         TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hToken))
246         return FALSE;
247     // LookupPrivilegeValue() 的作用是修改进程的权限
248     LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,
249         &tkp.Privileges[0].Luid);
250     tkp.PrivilegeCount = 1; // one privilege to set 赋给本进程特权
251     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
252     // AdjustTokenPrivileges()的作用是通知Windows NT修改本进程的权利
253     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
254         (PTOKEN_PRIVILEGES)NULL, 0);
255     
256     if (GetLastError() != ERROR_SUCCESS) //失败
257         return FALSE;
258     
259     if (!ExitWindowsEx(EWX_REBOOT, 0)) //参数在这里设置。强行退出WINDOWS(EWX_FORCE)。
260         return FALSE;
261     return TRUE;
262 }
main.cpp

 

 附加产物:

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

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

posted @ 2013-12-09 09:54  foo__hack  阅读(3084)  评论(0编辑  收藏  举报