windows driver 枚举串口

//枚举串口
	NTSTATUS status;
	HANDLE hKey = NULL;
	OBJECT_ATTRIBUTES oa;
	UNICODE_STRING strPath = RTL_CONSTANT_STRING(L"\\Registry\\Machine\\HARDWARE\\DEVICEMAP\\SERIALCOMM");//
	ULONG ResultLength = 0;

	PKEY_FULL_INFORMATION PKFI;
	PKEY_VALUE_PARTIAL_INFORMATION pkvpi;
	UNICODE_STRING strOutPut;
	wchar_t strTemp[ArrayLength] = {0};

	ULONG i = 0;
	ULONG nSubKeys = 0;

	RtlInitEmptyUnicodeString(&strOutPut, strTemp, ArrayLength);

	InitializeObjectAttributes(&oa, &strPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
	status = ZwOpenKey(&hKey, KEY_ALL_ACCESS, &oa);
	if (!NT_SUCCESS(status)){
		KdPrint(("ZwOpenKey failed"));
		return status;
	}
	
	ZwQueryKey(hKey, KeyFullInformation, NULL, 0, &ResultLength);
	PKFI = (PKEY_FULL_INFORMATION)ExAllocatePool(PagedPool, ResultLength);
	if (PKFI == NULL){
		KdPrint(("ExAllocatePool failed"));
		ZwClose(hKey);
		ExFreePool(PKFI);
		return STATUS_INSUFFICIENT_RESOURCES;
	}
	status = ZwQueryKey(hKey, KeyFullInformation, PKFI, ResultLength, &ResultLength);
	if (!NT_SUCCESS(status)){
		KdPrint(("ZwEnumerateKey failed with error %I32X", status));
		ZwClose(hKey);
		ExFreePool(PKFI);
		return status;
	}

	nSubKeys = PKFI->Values;
	KdPrint(("子键个数: %I32d", PKFI->Values));
	ExFreePool(PKFI);
	
	for (; i < nSubKeys; i++){
		ZwEnumerateValueKey(hKey, i,  KeyValuePartialInformation, NULL, 0, &ResultLength);
		pkvpi = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePool(PagedPool, ResultLength);
		if (pkvpi == NULL){
			KdPrint(("ExAllocatePoolWithTag failed"));
			ZwClose(hKey);
			ExFreePool(pkvpi);
			return STATUS_INSUFFICIENT_RESOURCES ;
		}
		
		status = ZwEnumerateValueKey(hKey, i, KeyValuePartialInformation, pkvpi, ResultLength, &ResultLength);
		if (!NT_SUCCESS(status)){
			KdPrint(("ZwEnumerateValueKey failed with error %I32X", status));
			ZwClose(hKey);
			ExFreePool(pkvpi);
			return status;
		}

		RtlStringCbPrintfW(strOutPut.Buffer, ArrayLength, L"%s", pkvpi->Data);
		KdPrint(("%ws", strOutPut.Buffer));
		ExFreePool(pkvpi);
	}

	ZwClose(hKey);
	return STATUS_SUCCESS;

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2014-11-13 20:23  QQ76211822  阅读(313)  评论(0编辑  收藏  举报