Что нового

Не отрабатывает кнопка "Обновить" у скрипта по выводу оборудования без драйверов

saavaage

Знающий
Сообщения
171
Репутация
17
Собственно, проблемы:
1. не происходит обновление списка оборудования без драйверов при нажатии на кнопку "Обновить". Поля ListView и TreeView очищаются, а их повторное заполнение списком оборудования не происходит. :(

Код:

Код:
#include <GuiConstantsEx.au3>
#include <GuiTreeView.au3>
#include <TreeViewConstants.au3>
#Include <GuiListView.au3>
#include <WindowsConstants.au3>
#include <GuiImageList.au3>
#include "DeviceAPI.au3"

Global $aAssoc[1][2]

$GUI = GUICreate("Device Management API - GUI Example", 800, 500)
$Refresh_Button = GUICtrlCreateButton("Обновить", 705, 465, 85, 33)
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = _GUICtrlTreeView_Create($GUI, 5, 5, 300, 450, $iStyle, $WS_EX_STATICEDGE )
$hListView = GUICtrlCreateListView ("Key|Value", 310, 5, 485,450)
GUISetState()

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
_BuildListDevice()

While 1
	Switch GUIGetMsg()
		Case $GUI_EVENT_CLOSE
			ExitLoop
		Case $Refresh_Button
			GUICtrlSetState($Refresh_Button, $GUI_DISABLE)
	        _GUICtrlTreeView_DeleteAll($hTreeView)
	        _GUICtrlListView_DeleteAllItems($hListView)
	        sleep(1000)
	        _BuildListDevice()
		    sleep(1000)
            GUICtrlSetState($Refresh_Button, $GUI_ENABLE)
	EndSwitch
WEnd

Func _BuildListDevice()
	;Assign image list to treeview
   _GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())

   Dim $total_devices = 0

   _DeviceAPI_GetClasses()

  While _DeviceAPI_EnumClasses()

	;Get icon index from image list for given class
	$Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)

	;Build list of devices within current class, if class doesn't contain any devices it will be skipped

	_DeviceAPI_GetClassDevices($p_currentGUID)

	;Skip classes without devices or devices have  drivers
	If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then


		;Add parent class to treeview
		$parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)

		;Loop through all devices by index
		While _DeviceAPI_EnumDevices()

			$description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
			$friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)

			;If a friendly name is available, use it instead of description
			If $friendly_name <> "" Then
			  $description = $friendly_name
		    EndIf


			;Add device to treeview below parent
			$handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)

			If $total_devices > 0 Then
				ReDim $aAssoc[$total_devices+1][2]
			EndIf

			;Add treeview item handle to array along with device Unique Instance Id (For lookup)
			$aAssoc[$total_devices][0] = $handle
			$aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()

			;Update running total count of devices
			$total_devices += 1
		WEnd
	EndIf
  WEnd

EndFunc

Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $iMsg, $iwParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

	$hWndTreeview = $hTreeView
	If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hWndTreeview
			Switch $iCode
				Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
					RefreshDeviceProperties()
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
	Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

	;Don't do anything if a class name (root item) was clicked
	If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then Return

	;Lookup treeview item handle in global array
	For $X = 0 to Ubound($aAssoc)-1

		If $hSelected = $aAssoc[$X][0] Then
			;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

			;Build list of ALL device classes
			_DeviceAPI_GetClassDevices()

			;Loop through all devices by index
			While _DeviceAPI_EnumDevices()
				If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

					;Empty listview
					_GUICtrlListView_DeleteAllItems($hListView)

					GUICtrlCreateListViewItem ("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView )
					GUICtrlCreateListViewItem ("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView )
					GUICtrlCreateListViewItem ("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView )
					GUICtrlCreateListViewItem ("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView )
					GUICtrlCreateListViewItem ("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView )
					GUICtrlCreateListViewItem ("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView )
					GUICtrlCreateListViewItem ("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView )
					GUICtrlCreateListViewItem ("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView )
					GUICtrlCreateListViewItem ("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView )

					;Resize columns to fit text
					_GUICtrlListView_SetColumnWidth($hListView, 0,$LVSCW_AUTOSIZE)
					_GUICtrlListView_SetColumnWidth($hListView, 1,$LVSCW_AUTOSIZE)
				EndIf
			WEnd
		EndIf
	Next
EndFunc

;Cleanup image list
_DeviceAPI_DestroyClassImageList()
_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure

PS если у Вас все драйвера стоят, то проверить работу скрипта можно, заменив строку
Код:
If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then

на
Код:
If _DeviceAPI_GetDeviceCount() > 0  Then


2. Почему-то с функцией DeviceAPI.au3 некоректно отрабатывает Organize Includes ( http://www.autoitscript.com/forum/index.php?showtopic=111554 )
PS версия autoit 3.3.6.1 Необходима функция DeviceAPI.au3
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8 472
Репутация
2 401
Помоему автор библиотеки немного промахнулся, тут явно нужна функция для обнуления библиотеки:

Код:
#include <GuiConstantsEx.au3>
#include <GuiTreeView.au3>
#include <TreeViewConstants.au3>
#include <GuiListView.au3>
#include <WindowsConstants.au3>
#include <GuiImageList.au3>
#include "DeviceAPI.au3"

Global $aAssoc[1][2]

$GUI = GUICreate("Device Management API - GUI Example", 800, 500)
$Refresh_Button = GUICtrlCreateButton("Обновить", 705, 465, 85, 33)
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = _GUICtrlTreeView_Create($GUI, 5, 5, 300, 450, $iStyle, $WS_EX_STATICEDGE)
$hListView = GUICtrlCreateListView("Key|Value", 310, 5, 485, 450)
GUISetState()

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
_BuildListDevice()

While 1
	Switch GUIGetMsg()
		Case $GUI_EVENT_CLOSE
			ExitLoop
		Case $Refresh_Button
			GUICtrlSetState($Refresh_Button, $GUI_DISABLE)
			
			_GUICtrlTreeView_DeleteAll($hTreeView)
			_GUICtrlListView_DeleteAllItems($hListView)
			
			Dim $aAssoc[1][2]
			
			_DeviceAPI_ResetLibrary()
			_BuildListDevice()
			
			GUICtrlSetState($Refresh_Button, $GUI_ENABLE)
	EndSwitch
WEnd

;Cleanup image list
_DeviceAPI_DestroyClassImageList()
_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure

Func _DeviceAPI_ResetLibrary()
	$hDevInfo = ""
	
	$aGUID = 0 ;Handle to GUID array structure
	$paGUID = DllStructGetPtr($aGUID) ;Pointer to GUID array structure
	$p_currentGUID = 0 ;Pointer to specific element in GUID array structure
	
	;Create an SP_DEVINFO_DATA structure
	$DEVINFO_DATA = _DeviceAPI_CreateDeviceDataStruct()
	$pSP_DEVINFO_DATA = DllStructGetPtr($DEVINFO_DATA) ;Get pointer to previous structure
	
	;Create SP_CLASSIMAGELIST_DATA structure
	$SP_CLASSIMAGELIST_DATA = _DeviceAPI_CreateClassImageListStruct()
	$pSP_CLASSIMAGELIST_DATA = DllStructGetPtr($SP_CLASSIMAGELIST_DATA) ;Get pointer to previous structure
	
	$iEnumClassInfoCursor = 0
	$iEnumDeviceInfoCursor = 0
EndFunc

Func _BuildListDevice()
	;Assign image list to treeview
	_GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())

	Dim $total_devices = 0
	
	_DeviceAPI_GetClasses()
	
	While _DeviceAPI_EnumClasses()
		;Get icon index from image list for given class
		$Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)
		
		;Build list of devices within current class, if class doesn't contain any devices it will be skipped
		_DeviceAPI_GetClassDevices($p_currentGUID)
		
		;Skip classes without devices or devices have  drivers
		If _DeviceAPI_GetDeviceCount() > 0 And _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then
			;Add parent class to treeview
			$parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)

			;Loop through all devices by index
			While _DeviceAPI_EnumDevices()
				$description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
				$friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)

				;If a friendly name is available, use it instead of description
				If $friendly_name <> "" Then
					$description = $friendly_name
				EndIf


				;Add device to treeview below parent
				$handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)

				If $total_devices > 0 Then
					ReDim $aAssoc[$total_devices + 1][2]
				EndIf
				
				;Add treeview item handle to array along with device Unique Instance Id (For lookup)
				$aAssoc[$total_devices][0] = $handle
				$aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()

				;Update running total count of devices
				$total_devices += 1
			WEnd
		EndIf
	WEnd
EndFunc   ;==>_BuildListDevice

;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
	Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

	;Don't do anything if a class name (root item) was clicked
	If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then Return

	;Lookup treeview item handle in global array
	For $X = 0 To UBound($aAssoc) - 1

		If $hSelected = $aAssoc[$X][0] Then
			;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

			;Build list of ALL device classes
			_DeviceAPI_GetClassDevices()

			;Loop through all devices by index
			While _DeviceAPI_EnumDevices()
				If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

					;Empty listview
					_GUICtrlListView_DeleteAllItems($hListView)

					GUICtrlCreateListViewItem("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView)
					GUICtrlCreateListViewItem("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView)
					GUICtrlCreateListViewItem("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView)
					GUICtrlCreateListViewItem("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView)
					GUICtrlCreateListViewItem("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView)
					GUICtrlCreateListViewItem("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView)
					GUICtrlCreateListViewItem("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView)

					;Resize columns to fit text
					_GUICtrlListView_SetColumnWidth($hListView, 0, $LVSCW_AUTOSIZE)
					_GUICtrlListView_SetColumnWidth($hListView, 1, $LVSCW_AUTOSIZE)
				EndIf
			WEnd
		EndIf
	Next
EndFunc   ;==>RefreshDeviceProperties

Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $iMsg, $iwParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

	$hWndTreeview = $hTreeView
	If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hWndTreeview
			Switch $iCode
				Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
					RefreshDeviceProperties()
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY


хотя этих двух строчек вполне хватает для обнуления:
Код:
$iEnumClassInfoCursor = 0
	$iEnumDeviceInfoCursor = 0
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
Re: Не отрабатывает кнопка \\\"Обновить\\\" у скрипта по выводу оборудования без драйверов

Тема решена. Спасибо Большое.
Как всегда, где CreatoR - там победа! :smile:


Добавлено:
Сообщение автоматически объединено:

CreatoR, насчет "хотя этих двух строчек вполне хватает для обнуления:...."
Я правильно Вас понял, что достаточно было прописать код следующим образом:
Код:
#include <GuiConstantsEx.au3>
#include <GuiTreeView.au3>
#include <TreeViewConstants.au3>
#include <GuiListView.au3>
#include <WindowsConstants.au3>
#include <GuiImageList.au3>
#include "DeviceAPI.au3"

Global $aAssoc[1][2]

$GUI = GUICreate("Device Management API - GUI Example", 800, 500)
$Refresh_Button = GUICtrlCreateButton("Обновить", 705, 465, 85, 33)
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = _GUICtrlTreeView_Create($GUI, 5, 5, 300, 450, $iStyle, $WS_EX_STATICEDGE)
$hListView = GUICtrlCreateListView("Key|Value", 310, 5, 485, 450)
GUISetState()

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
_BuildListDevice()

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            ExitLoop
        Case $Refresh_Button
            GUICtrlSetState($Refresh_Button, $GUI_DISABLE)
            $iEnumClassInfoCursor = 0
            $iEnumDeviceInfoCursor = 0
            _GUICtrlTreeView_DeleteAll($hTreeView)
            _GUICtrlListView_DeleteAllItems($hListView)

            _BuildListDevice()

            GUICtrlSetState($Refresh_Button, $GUI_ENABLE)
    EndSwitch
WEnd

;Cleanup image list
_DeviceAPI_DestroyClassImageList()
_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure

Func _BuildListDevice()
    ;Assign image list to treeview
    _GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())

    Dim $total_devices = 0

    _DeviceAPI_GetClasses()

    While _DeviceAPI_EnumClasses()
        ;Get icon index from image list for given class
        $Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)

        ;Build list of devices within current class, if class doesn't contain any devices it will be skipped
        _DeviceAPI_GetClassDevices($p_currentGUID)

        ;Skip classes without devices or devices have  drivers
        If _DeviceAPI_GetDeviceCount() > 0 And _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then
            ;Add parent class to treeview
            $parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)

            ;Loop through all devices by index
            While _DeviceAPI_EnumDevices()
                $description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
                $friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)

                ;If a friendly name is available, use it instead of description
                If $friendly_name <> "" Then
                    $description = $friendly_name
                EndIf


                ;Add device to treeview below parent
                $handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)

                If $total_devices > 0 Then
                    ReDim $aAssoc[$total_devices + 1][2]
                EndIf

                ;Add treeview item handle to array along with device Unique Instance Id (For lookup)
                $aAssoc[$total_devices][0] = $handle
                $aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()

                ;Update running total count of devices
                $total_devices += 1
            WEnd
        EndIf
    WEnd
EndFunc   ;==>_BuildListDevice

;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
    Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

    ;Don't do anything if a class name (root item) was clicked
    If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then Return

    ;Lookup treeview item handle in global array
    For $X = 0 To UBound($aAssoc) - 1

        If $hSelected = $aAssoc[$X][0] Then
            ;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

            ;Build list of ALL device classes
            _DeviceAPI_GetClassDevices()

            ;Loop through all devices by index
            While _DeviceAPI_EnumDevices()
                If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

                    ;Empty listview
                    _GUICtrlListView_DeleteAllItems($hListView)

                    GUICtrlCreateListViewItem("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView)
                    GUICtrlCreateListViewItem("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView)
                    GUICtrlCreateListViewItem("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView)
                    GUICtrlCreateListViewItem("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView)
                    GUICtrlCreateListViewItem("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView)
                    GUICtrlCreateListViewItem("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView)
                    GUICtrlCreateListViewItem("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView)
                    GUICtrlCreateListViewItem("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView)
                    GUICtrlCreateListViewItem("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView)

                    ;Resize columns to fit text
                    _GUICtrlListView_SetColumnWidth($hListView, 0, $LVSCW_AUTOSIZE)
                    _GUICtrlListView_SetColumnWidth($hListView, 1, $LVSCW_AUTOSIZE)
                EndIf
            WEnd
        EndIf
    Next
EndFunc   ;==>RefreshDeviceProperties

Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
    #forceref $hWnd, $iMsg, $iwParam
    Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

    $hWndTreeview = $hTreeView
    If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

    $tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
    $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
    $iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
    $iCode = DllStructGetData($tNMHDR, "Code")
    Switch $hWndFrom
        Case $hWndTreeview
            Switch $iCode
                Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
                    RefreshDeviceProperties()
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY


Добавлено:
Сообщение автоматически объединено:

я там откорректировал в сase строки. Новый код:
Код:
While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            ExitLoop
        Case $Refresh_Button
            GUICtrlSetState($Refresh_Button, $GUI_DISABLE)
            $iEnumClassInfoCursor = 0
            $iEnumDeviceInfoCursor = 0
            _GUICtrlTreeView_DeleteAll($hTreeView)
            _GUICtrlListView_DeleteAllItems($hListView)

            _BuildListDevice()

            GUICtrlSetState($Refresh_Button, $GUI_ENABLE)
    EndSwitch
WEnd


и убрал функцию _DeviceAPI_ResetLibrary()

Это правильно?
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
Попробовал. Нет обновления в этом случае. Вы наверно имели ввиду удалить эту строку:
Код:
$iEnumDeviceInfoCursor = 0
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
CreatoR, обнаружил одну странность в работе скрипта (все действия выполнял последовательно):

1. Если отрабатывает скрипт с условием "показывать только оборудование без драйверов"
Код:
If _DeviceAPI_GetDeviceCount() > 0 And _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then
, то показывается все нормально (у меня отрублены дрова dial-up модема).

2. После изменений скрипта на условие "показывать оборудование только с драйверами"
Код:
If _DeviceAPI_GetDeviceCount() > 0 And _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then
, скрипт выводит все оборудование (включая модем), причем у модема в поле "Driver" стоит обозначение драйвера (хотя у модема дрова отрублены).

3. После возвращения настроек к условию п.1, скрипт выводит пустой список (хотя у модема дрова отрублены)
Весьма странно...
PS проверял через Панель Управления -> Система -> Оборудование -> Диспетчер Устройств. У модема драйвер удален, на вкладке "Драйвер" в соответствующих полях стоит "нет данных".
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8 472
Репутация
2 401
saavaage [?]
обнаружил одну странность в работе скрипта
Не уверен что могу нормально проверить, у меня подключён сканер и драйверов к нему я не ставил, вот так у меня распознаёт разные режимы (все устройства, без драйверов, или только с драйверами):

Код:
#include <GuiConstantsEx.au3>
#include <GuiTreeView.au3>
#include <TreeViewConstants.au3>
#include <GuiListView.au3>
#include <WindowsConstants.au3>
#include <GuiImageList.au3>
#include "DeviceAPI.au3"

Global $iAllDevicesMode = 1 ;1 - All devices, 2 - All with drivers, 3 - All without drivers
Global $aAssoc[1][2]
Global $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)

$GUI = GUICreate("Device Management API - GUI Example", 800, 500)
$Refresh_Button = GUICtrlCreateButton("Обновить", 705, 465, 85, 33)
$hTreeView = _GUICtrlTreeView_Create($GUI, 5, 5, 300, 450, $iStyle, $WS_EX_STATICEDGE)
$hListView = GUICtrlCreateListView("Key|Value", 310, 5, 485, 450)

$nShowAllDevices_Radio = GUICtrlCreateRadio("Показывать все", 20, 470)
GUICtrlSetState(-1, $GUI_CHECKED)
$nShowDevicesWithDrivers_Radio = GUICtrlCreateRadio("Показывать только с драйверами", 160, 470)
$nShowDevicesWithoutDrivers_Radio = GUICtrlCreateRadio("Показывать только без драйверов", 380, 470)

GUISetState(@SW_SHOW, $GUI)
GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
_BuildListDevice()

While 1
	$nMsg = GUIGetMsg()
	
	Switch $nMsg
		Case $GUI_EVENT_CLOSE
			ExitLoop
		Case $nShowAllDevices_Radio, $nShowDevicesWithDrivers_Radio, $nShowDevicesWithoutDrivers_Radio
			$iAllDevicesMode = $nMsg - 4
			ContinueCase
		Case $Refresh_Button
			GUICtrlSetState($Refresh_Button, $GUI_DISABLE)
			
			_GUICtrlTreeView_DeleteAll($hTreeView)
			_GUICtrlListView_DeleteAllItems($hListView)
			
			Dim $aAssoc[1][2]
			
			_DeviceAPI_ResetLibrary()
			_BuildListDevice()
			
			GUICtrlSetState($Refresh_Button, $GUI_ENABLE)
	EndSwitch
WEnd

;Cleanup image list
_DeviceAPI_DestroyClassImageList()
_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure

Func _DeviceAPI_ResetLibrary()
;~ 	$hDevInfo = ""
;~ 	
;~ 	$aGUID = 0 ;Handle to GUID array structure
;~ 	$paGUID = DllStructGetPtr($aGUID) ;Pointer to GUID array structure
;~ 	$p_currentGUID = 0 ;Pointer to specific element in GUID array structure
;~ 	
;~ 	;Create an SP_DEVINFO_DATA structure
;~ 	$DEVINFO_DATA = _DeviceAPI_CreateDeviceDataStruct()
;~ 	$pSP_DEVINFO_DATA = DllStructGetPtr($DEVINFO_DATA) ;Get pointer to previous structure
;~ 	
;~ 	;Create SP_CLASSIMAGELIST_DATA structure
;~ 	$SP_CLASSIMAGELIST_DATA = _DeviceAPI_CreateClassImageListStruct()
;~ 	$pSP_CLASSIMAGELIST_DATA = DllStructGetPtr($SP_CLASSIMAGELIST_DATA) ;Get pointer to previous structure
;~ 	
;~ 	$iEnumDeviceInfoCursor = 0
	$iEnumClassInfoCursor = 0
EndFunc

Func _BuildListDevice()
	;Assign image list to treeview
	_GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())

	Dim $total_devices = 0
	
	_DeviceAPI_GetClasses()
	
	While _DeviceAPI_EnumClasses()
		;Get icon index from image list for given class
		$Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)
		
		;Build list of devices within current class, if class doesn't contain any devices it will be skipped
		_DeviceAPI_GetClassDevices($p_currentGUID)
		
		If _DeviceAPI_GetDeviceCount() = 0 Then
			ContinueLoop
		EndIf
		
		;Skip classes of...
		Switch $iAllDevicesMode
			Case 1 ;All devices
				;Do nothing, continue the enum process
			Case 2 ;All devices with drivers
				If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) == '' Then
					ContinueLoop
				EndIf
			Case 3 ;All devices without drivers
				If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then
					ContinueLoop
				EndIf
		EndSwitch
		
		;Add parent class to treeview
		$parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)
		
		;Loop through all devices by index
		While _DeviceAPI_EnumDevices()
			$description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
			$friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)
			
			;If a friendly name is available, use it instead of description
			If $friendly_name <> "" Then
				$description = $friendly_name
			EndIf
			
			;Add device to treeview below parent
			$handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)
			
			If $total_devices > 0 Then
				ReDim $aAssoc[$total_devices + 1][2]
			EndIf
			
			;Add treeview item handle to array along with device Unique Instance Id (For lookup)
			$aAssoc[$total_devices][0] = $handle
			$aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()
			
			;Update running total count of devices
			$total_devices += 1
		WEnd
	WEnd
EndFunc   ;==>_BuildListDevice

;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
	Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

	;Don't do anything if a class name (root item) was clicked
	If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then
		_GUICtrlListView_DeleteAllItems($hListView)
		Return
	EndIf
	
	;Lookup treeview item handle in global array
	For $X = 0 To UBound($aAssoc) - 1
		If $hSelected = $aAssoc[$X][0] Then
			;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

			;Build list of ALL device classes
			_DeviceAPI_GetClassDevices()

			;Loop through all devices by index
			While _DeviceAPI_EnumDevices()
				If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

					;Empty listview
					_GUICtrlListView_DeleteAllItems($hListView)

					GUICtrlCreateListViewItem("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView)
					GUICtrlCreateListViewItem("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView)
					GUICtrlCreateListViewItem("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView)
					GUICtrlCreateListViewItem("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView)
					GUICtrlCreateListViewItem("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView)
					GUICtrlCreateListViewItem("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView)
					GUICtrlCreateListViewItem("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView)
					
					;Resize columns to fit text
					_GUICtrlListView_SetColumnWidth($hListView, 0, $LVSCW_AUTOSIZE)
					_GUICtrlListView_SetColumnWidth($hListView, 1, $LVSCW_AUTOSIZE)
				EndIf
			WEnd
		EndIf
	Next
EndFunc   ;==>RefreshDeviceProperties

Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $iMsg, $iwParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

	$hWndTreeview = $hTreeView
	If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hWndTreeview
			Switch $iCode
				Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
					RefreshDeviceProperties()
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
CreatoR, сейчас не могу проверить. Сегодня ближе к вечеру отпишусь о результатах.

Спасибо.
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
CreatoR, пока тест скрипта не выявил прежних проблем.
У меня параллельно возник один вопрос: не объясните смысл кода (в case):
Код:
Case $nShowAllDevices_Radio, $nShowDevicesWithDrivers_Radio, $nShowDevicesWithoutDrivers_Radio
            $iAllDevicesMode = $nMsg - 4
            ContinueCase

Я предполагаю (скорее всего неверно), что суть - присвоение $iAllDevicesMode при нажатии на конкретный радио значений 1, 2 , 3. Но не понимаю,как программа обсчитывает выражение
Код:
$iAllDevicesMode = $nMsg - 4
, а именно, чему равен $nMsg и почему?
Заранее извиняюсь за косноязычие...
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
CreatoR, в последнем Вашем скрипте все работает безупречно. Проблемы с некорректным выводом оборудования больше нет. Выкладываю адаптацию Вашего скрипта к форме с Tab + GUIOnEventMode:

Код:
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
#include <GuiTreeView.au3>
#include <ListViewConstants.au3>
#include <StructureConstants.au3>
#include <TreeViewConstants.au3>
#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
#include <GuiTreeView.au3>
#include <ListViewConstants.au3>
#include <StructureConstants.au3>
#include <TreeViewConstants.au3>
#include <WindowsConstants.au3>
#include "DeviceAPI.au3"

; Devices-Drivers
Global $aAssoc[1][2]
Global $hTreeView, $nR
Global $iAllDevicesMode = 3 ;1 - All devices, 2 - All with drivers, 3 - All without drivers
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)

Opt("GUIOnEventMode", 1)

$hMain_GUI = GUICreate("Диагностика и Настройка XP SP3", 619, 442, 189, 122)
GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked")

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)

;;; Devices-Drivers ;;;
$DriverErrors = GUICtrlCreateTabItem("Devices-Drivers")

GUICtrlCreateGroup("Оборудование без драйверов", 14, 40, 255, 345)
$hTreeView = GUICtrlCreateTreeView(15, 55, 253, 327, $iStyle)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 46, 332, 255)

$nShowAllDevices_Radio = GUICtrlCreateRadio("Все девайсы", 290, 310, 100, 33)
  GUICtrlSetOnEvent($nShowAllDevices_Radio, "_MainGUI_Events")
$nShowDevicesWithDrivers_Radio = GUICtrlCreateRadio("С драйверами", 390, 310, 90, 33)
  GUICtrlSetOnEvent($nShowDevicesWithDrivers_Radio, "_MainGUI_Events")
$nShowDevicesWithoutDrivers_Radio = GUICtrlCreateRadio("Без драйверов", 495, 310, 100, 33)
  GUICtrlSetState(-1, $GUI_CHECKED)
  GUICtrlSetOnEvent($nShowDevicesWithoutDrivers_Radio, "_MainGUI_Events")

; получение статуса из реестра (показывать скрытые устройства в диспетчере)
$cParamHid1 = RegRead('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES')
IF $cParamHid1 > 0 Then
	$cParamHid2 =1
Else
	$cParamHid2 =0
EndIf
; создание чекбокса для "показывать скрытые устройства в диспетчере" и работа с ним
$CheckboxHid = GUICtrlCreateCheckbox("Отображать скрытые устройства", 290, 350, 140, 30, $BS_MULTILINE)
  GUICtrlSetTip(-1, 'Отображать скрытые устройсва в Диспетчере Устройств')
  GUICtrlSetState(-1, BitOR($GUI_CHECKED * $cParamHid2, $GUI_UNCHECKED * (Not $cParamHid2)))
  GUICtrlSetOnEvent($CheckboxHid, "_CheckboxHid")
; получение статуса из реестра (показывать детальную инфо в диспетчере)
$cParamDet1 = RegRead('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS')
IF $cParamDet1 > 0 Then
	$cParamDet2 =1
Else
	$cParamDet2 =0
EndIf
; создание чекбокса для "показывать детальную инфо в диспетчере" и работа с ним
$CheckboxDet = GUICtrlCreateCheckbox('Отображать подробную информацию', 450, 350, 140, 30, $BS_MULTILINE)
  GUICtrlSetTip(-1, 'Отображать подробную информацию в Диспетчере устройств')
  GUICtrlSetState(-1, BitOR($GUI_CHECKED * $cParamDet2, $GUI_UNCHECKED * (Not $cParamDet2)))
  GUICtrlSetOnEvent($CheckboxDet, "_CheckboxDet")

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
_BuildListDevice()


$DrRefresh_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
   GUICtrlSetOnEvent($DrRefresh_Button, "_DrRefresh_Button")

GUICtrlCreateTabItem("")

;;;; Common Buttons ;;;;
$nExit_Button = GUICtrlCreateButton("Выйти", 535, 400, 70, 33)
  GUICtrlSetOnEvent($nExit_Button, "_MainGUI_Events")

GUISetState()

While 1
    Sleep(100)
WEnd

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;    FUNCTIONS OF COMMON BUTTONS   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func CLOSEClicked()
  Exit
EndFunc


Func _MainGUI_Events()
	Switch @GUI_CtrlId
        Case $nExit_Button
            Exit
		Case $nShowAllDevices_Radio
			$nR= 1
			_Radio()
		Case $nShowDevicesWithDrivers_Radio
			$nR= 2
			_Radio()
		Case $nShowDevicesWithoutDrivers_Radio
			$nR= 3
			_Radio()
	EndSwitch
EndFunc


Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
    #forceref $hWnd, $iMsg, $iwParam
    Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

    $hWndTreeview = $hTreeView
    If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

    $tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
    $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
    $iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
    $iCode = DllStructGetData($tNMHDR, "Code")
    Switch $hWndFrom
        Case $hWndTreeview
            Switch $iCode
                Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
                    RefreshDeviceProperties()
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

Func _DrRefresh_Button()
	       GUICtrlSetState($nShowAllDevices_Radio, $GUI_DISABLE)
		   GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_DISABLE)
           GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_DISABLE)

            _GUICtrlTreeView_DeleteAll($hTreeView)
            _GUICtrlListView_DeleteAllItems($hListView)

            ;Dim $aAssoc[1][2]

            $iEnumClassInfoCursor = 0

			_BuildListDevice()

            GUICtrlSetState($nShowAllDevices_Radio, $GUI_ENABLE)
			GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_ENABLE)
			GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_ENABLE)
EndFunc

Func _Radio()
           GUICtrlSetState($nShowAllDevices_Radio, $GUI_DISABLE)
		   GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_DISABLE)
           GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_DISABLE)

			_GUICtrlTreeView_DeleteAll($hTreeView)
            _GUICtrlListView_DeleteAllItems($hListView)

            ;Dim $aAssoc[1][2]

            $iEnumClassInfoCursor = 0
            $iAllDevicesMode = $nR
			_BuildListDevice()

            GUICtrlSetState($nShowAllDevices_Radio, $GUI_ENABLE)
			GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_ENABLE)
			GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_ENABLE)
EndFunc

Func _BuildListDevice()

    ;Assign image list to treeview
    _GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())

    Dim $total_devices = 0

    _DeviceAPI_GetClasses()

    While _DeviceAPI_EnumClasses()
        ;Get icon index from image list for given class
        $Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)

        ;Build list of devices within current class, if class doesn't contain any devices it will be skipped
        _DeviceAPI_GetClassDevices($p_currentGUID)

        If _DeviceAPI_GetDeviceCount() = 0 Then
            ContinueLoop
        EndIf

        ;Skip classes of...
        Switch $iAllDevicesMode
            Case 1 ;All devices
                ;Do nothing, continue the enum process
            Case 2 ;All devices without drivers
                If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) == '' Then
                    ContinueLoop
                EndIf
            Case 3 ;All devices with drivers
                If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then
                    ContinueLoop
                EndIf
        EndSwitch

        ;Add parent class to treeview
        $parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)

        ;Loop through all devices by index
        While _DeviceAPI_EnumDevices()
            $description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
            $friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)

            ;If a friendly name is available, use it instead of description
            If $friendly_name <> "" Then
                $description = $friendly_name
            EndIf

            ;Add device to treeview below parent
            $handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)

            If $total_devices > 0 Then
                ReDim $aAssoc[$total_devices + 1][2]
            EndIf

            ;Add treeview item handle to array along with device Unique Instance Id (For lookup)
            $aAssoc[$total_devices][0] = $handle
            $aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()

            ;Update running total count of devices
            $total_devices += 1
        WEnd
    WEnd
    ;Cleanup image list
    _DeviceAPI_DestroyClassImageList()
    _DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure
EndFunc   ;==>_BuildListDevice


;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
        Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

    ;Don't do anything if a class name (root item) was clicked
    If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then
        _GUICtrlListView_DeleteAllItems($hListView)
        Return
    EndIf

    ;Lookup treeview item handle in global array
    For $X = 0 To UBound($aAssoc) - 1
        If $hSelected = $aAssoc[$X][0] Then
            ;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

            ;Build list of ALL device classes
            _DeviceAPI_GetClassDevices()

            ;Loop through all devices by index
            While _DeviceAPI_EnumDevices()
                If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

                    ;Empty listview
                    _GUICtrlListView_DeleteAllItems($hListView)

                    GUICtrlCreateListViewItem("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView)
                    GUICtrlCreateListViewItem("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView)
                    GUICtrlCreateListViewItem("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView)
                    GUICtrlCreateListViewItem("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView)
                    GUICtrlCreateListViewItem("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView)
                    GUICtrlCreateListViewItem("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView)
                    GUICtrlCreateListViewItem("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView)
                    GUICtrlCreateListViewItem("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView)
                    GUICtrlCreateListViewItem("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView)

                    ;Resize columns to fit text
                    _GUICtrlListView_SetColumnWidth($hListView, 0, $LVSCW_AUTOSIZE)
                    _GUICtrlListView_SetColumnWidth($hListView, 1, $LVSCW_AUTOSIZE)
                EndIf
            WEnd
        EndIf
    Next
EndFunc   ;==>RefreshDeviceProperties

Func _CheckboxHid()
	IF GUICtrlRead($CheckboxHid) = $GUI_CHECKED Then
		RegWrite('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES', 'REG_DWORD', '1')
	Else
		RegDelete('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES')
	EndIf
EndFunc

Func _CheckboxDet()
	IF GUICtrlRead($CheckboxDet) = $GUI_CHECKED Then
		RegWrite('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS', 'REG_DWORD', '1')
	Else
		RegDelete('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS')
	EndIf
EndFunc

Если не сложно, проверьте, пожалуйста, на корректность. Кроме того, есть одна проблема: при загрузке скрипта не происходит прорисовка иконок. Только после нажатия на кнопку "Обновить" или переключение радио-кнопок, иконки прорисовываются. С чем это может быть связано?
 

CreatoR

Must AutoIt!
Команда форума
Администратор
Сообщения
8 472
Репутация
2 401
saavaage [?]
Я предполагаю (скорее всего неверно)
Всё верно :smile:

чему равен $nMsg и почему?
Равен тому что возвращает GUIGetMsg, а именно CtrlID текущего события. В нашем случае это Radio-кнопки, а отнимаем от них 4 т.к нам нужен 1, 2 или 3, что является вариантами перчитывания устройств. Первый Radio это 5 (это и есть идентификатор/CtrlID элемента), второй это 6, ну и третьий 7, соот-венно отнимаем от них 4 получаем 1, 2 и 3.
Но это конечно неправильный и ленивый (хотя скорее экономный) подход, правильнее проверять все элементы, как ты это и сделал в последнем скрипте.

[?]
есть одна проблема: при загрузке скрипта не происходит прорисовка иконок
А зачем каждый раз удалять ImageList?

Код:
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
#include <GuiTreeView.au3>
#include <ListViewConstants.au3>
#include <StructureConstants.au3>
#include <TreeViewConstants.au3>
#include <WindowsConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiListView.au3>
#include <GuiTreeView.au3>
#include <ListViewConstants.au3>
#include <StructureConstants.au3>
#include <TreeViewConstants.au3>
#include <WindowsConstants.au3>
#include "DeviceAPI.au3"

; Devices-Drivers
Global $aAssoc[1][2]
Global $hTreeView
Global $iAllDevicesMode = 3 ;1 - All devices, 2 - All with drivers, 3 - All without drivers
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)

Opt("GUIOnEventMode", 1)

$hMain_GUI = GUICreate("Диагностика и Настройка XP SP3", 619, 442, 189, 122)
GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked")

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)

;;; Devices-Drivers ;;;
$DriverErrors = GUICtrlCreateTabItem("Devices-Drivers")

GUICtrlCreateGroup("Оборудование без драйверов", 14, 40, 255, 345)
$hTreeView = GUICtrlCreateTreeView(15, 55, 253, 327, $iStyle)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 46, 332, 255)

$nShowAllDevices_Radio = GUICtrlCreateRadio("Все девайсы", 290, 310, 100, 33)
GUICtrlSetOnEvent($nShowAllDevices_Radio, "_MainGUI_Events")
$nShowDevicesWithDrivers_Radio = GUICtrlCreateRadio("С драйверами", 390, 310, 90, 33)
GUICtrlSetOnEvent($nShowDevicesWithDrivers_Radio, "_MainGUI_Events")
$nShowDevicesWithoutDrivers_Radio = GUICtrlCreateRadio("Без драйверов", 495, 310, 100, 33)
GUICtrlSetState(-1, $GUI_CHECKED)
GUICtrlSetOnEvent($nShowDevicesWithoutDrivers_Radio, "_MainGUI_Events")

; получение статуса из реестра (показывать скрытые устройства в диспетчере)
$cParamHid1 = RegRead('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES')

If $cParamHid1 > 0 Then
	$cParamHid2 = 1
Else
	$cParamHid2 = 0
EndIf
; создание чекбокса для "показывать скрытые устройства в диспетчере" и работа с ним
$CheckboxHid = GUICtrlCreateCheckbox("Отображать скрытые устройства", 290, 350, 140, 30, $BS_MULTILINE)
GUICtrlSetTip(-1, 'Отображать скрытые устройсва в Диспетчере Устройств')
GUICtrlSetState(-1, BitOR($GUI_CHECKED * $cParamHid2, $GUI_UNCHECKED * (Not $cParamHid2)))
GUICtrlSetOnEvent($CheckboxHid, "_CheckboxHid")
; получение статуса из реестра (показывать детальную инфо в диспетчере)
$cParamDet1 = RegRead('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS')
If $cParamDet1 > 0 Then
	$cParamDet2 = 1
Else
	$cParamDet2 = 0
EndIf
; создание чекбокса для "показывать детальную инфо в диспетчере" и работа с ним
$CheckboxDet = GUICtrlCreateCheckbox('Отображать подробную информацию', 450, 350, 140, 30, $BS_MULTILINE)
GUICtrlSetTip(-1, 'Отображать подробную информацию в Диспетчере устройств')
GUICtrlSetState(-1, BitOR($GUI_CHECKED * $cParamDet2, $GUI_UNCHECKED * (Not $cParamDet2)))
GUICtrlSetOnEvent($CheckboxDet, "_CheckboxDet")

$DrRefresh_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
GUICtrlSetOnEvent($DrRefresh_Button, "_DrRefresh_Button")

GUICtrlCreateTabItem("")

;;;; Common Buttons ;;;;
$nExit_Button = GUICtrlCreateButton("Выйти", 535, 400, 70, 33)
GUICtrlSetOnEvent($nExit_Button, "_MainGUI_Events")

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
;Assign image list to treeview
_GUICtrlTreeView_SetNormalImageList($hTreeView, _DeviceAPI_GetClassImageList())
_BuildListDevice()

GUISetState()

While 1
	Sleep(100)
WEnd

Func _BuildListDevice()
	Dim $total_devices = 0

	_DeviceAPI_GetClasses()

	While _DeviceAPI_EnumClasses()
		;Get icon index from image list for given class
		$Icon_Index = _DeviceAPI_GetClassImageIndex($p_currentGUID)

		;Build list of devices within current class, if class doesn't contain any devices it will be skipped
		_DeviceAPI_GetClassDevices($p_currentGUID)

		If _DeviceAPI_GetDeviceCount() = 0 Then
			ContinueLoop
		EndIf

		;Skip classes of...
		Switch $iAllDevicesMode
			Case 1 ;All devices
				;Do nothing, continue the enum process
			Case 2 ;All devices without drivers
				If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) == '' Then
					ContinueLoop
				EndIf
			Case 3 ;All devices with drivers
				If _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then
					ContinueLoop
				EndIf
		EndSwitch

		;Add parent class to treeview
		$parent = _GUICtrlTreeView_Add($hTreeView, 0, _DeviceAPI_GetClassDescription($p_currentGUID), $Icon_Index, $Icon_Index)

		;Loop through all devices by index
		While _DeviceAPI_EnumDevices()
			$description = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DEVICEDESC)
			$friendly_name = _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME)

			;If a friendly name is available, use it instead of description
			If $friendly_name <> "" Then
				$description = $friendly_name
			EndIf

			;Add device to treeview below parent
			$handle = _GUICtrlTreeView_AddChild($hTreeView, $parent, $description, $Icon_Index, $Icon_Index)

			If $total_devices > 0 Then
				ReDim $aAssoc[$total_devices + 1][2]
			EndIf

			;Add treeview item handle to array along with device Unique Instance Id (For lookup)
			$aAssoc[$total_devices][0] = $handle
			$aAssoc[$total_devices][1] = _DeviceAPI_GetDeviceId()

			;Update running total count of devices
			$total_devices += 1
		WEnd
	WEnd
	
	;Cleanup image list
	;_DeviceAPI_DestroyClassImageList()
	_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure
EndFunc   ;==>_BuildListDevice

Func _CheckboxDet()
	If GUICtrlRead($CheckboxDet) = $GUI_CHECKED Then
		RegWrite('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS', 'REG_DWORD', '1')
	Else
		RegDelete('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_DETAILS')
	EndIf
EndFunc   ;==>_CheckboxDet

Func _CheckboxHid()
	If GUICtrlRead($CheckboxHid) = $GUI_CHECKED Then
		RegWrite('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES', 'REG_DWORD', '1')
	Else
		RegDelete('HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'DEVMGR_SHOW_NONPRESENT_DEVICES')
	EndIf
EndFunc   ;==>_CheckboxHid

Func _DrRefresh_Button()
	GUICtrlSetState($nShowAllDevices_Radio, $GUI_DISABLE)
	GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_DISABLE)
	GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_DISABLE)

	_GUICtrlTreeView_DeleteAll($hTreeView)
	_GUICtrlListView_DeleteAllItems($hListView)

	;Dim $aAssoc[1][2]

	$iEnumClassInfoCursor = 0

	_BuildListDevice()

	GUICtrlSetState($nShowAllDevices_Radio, $GUI_ENABLE)
	GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_ENABLE)
	GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_ENABLE)
EndFunc   ;==>_DrRefresh_Button


Func _MainGUI_Events()
	Switch @GUI_CtrlId
		Case $nExit_Button
			Exit
		Case $nShowAllDevices_Radio
			_Radio(1)
		Case $nShowDevicesWithDrivers_Radio
			_Radio(2)
		Case $nShowDevicesWithoutDrivers_Radio
			_Radio(3)
	EndSwitch
EndFunc   ;==>_MainGUI_Events

Func _Radio($iDvcMode)
	GUICtrlSetState($nShowAllDevices_Radio, $GUI_DISABLE)
	GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_DISABLE)
	GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_DISABLE)

	_GUICtrlTreeView_DeleteAll($hTreeView)
	_GUICtrlListView_DeleteAllItems($hListView)

	;Dim $aAssoc[1][2]

	$iEnumClassInfoCursor = 0
	$iAllDevicesMode = $iDvcMode
	_BuildListDevice()

	GUICtrlSetState($nShowAllDevices_Radio, $GUI_ENABLE)
	GUICtrlSetState($nShowDevicesWithDrivers_Radio, $GUI_ENABLE)
	GUICtrlSetState($nShowDevicesWithoutDrivers_Radio, $GUI_ENABLE)
EndFunc   ;==>_Radio

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;    FUNCTIONS OF COMMON BUTTONS   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func CLOSEClicked()
	Exit
EndFunc   ;==>CLOSEClicked


;Triggered when a device is selected in the treeview
Func RefreshDeviceProperties()
	Local $hSelected = _GUICtrlTreeView_GetSelection($hTreeView)

	;Don't do anything if a class name (root item) was clicked
	If _GUICtrlTreeView_Level($hTreeView, $hSelected) = 0 Then
		_GUICtrlListView_DeleteAllItems($hListView)
		Return
	EndIf

	;Lookup treeview item handle in global array
	For $X = 0 To UBound($aAssoc) - 1
		If $hSelected = $aAssoc[$X][0] Then
			;MsgBox(0,"", "Handle: " & $aAssoc[$X][0] & @CRLF & "Unique Instance Id: " & $aAssoc[$X][1])

			;Build list of ALL device classes
			_DeviceAPI_GetClassDevices()

			;Loop through all devices by index
			While _DeviceAPI_EnumDevices()
				If $aAssoc[$X][1] = _DeviceAPI_GetDeviceId() Then

					;Empty listview
					_GUICtrlListView_DeleteAllItems($hListView)

					GUICtrlCreateListViewItem("Hardware ID: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_HARDWAREID), $hListView)
					GUICtrlCreateListViewItem("Unique Instance ID: |" & _DeviceAPI_GetDeviceId(), $hListView)
					GUICtrlCreateListViewItem("Manufacturer: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_MFG), $hListView)
					GUICtrlCreateListViewItem("Driver: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER), $hListView)
					GUICtrlCreateListViewItem("Friendly Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_FRIENDLYNAME), $hListView)
					GUICtrlCreateListViewItem("Physical Device Object Name: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_PHYSICAL_DEVICE_OBJECT_NAME), $hListView)
					GUICtrlCreateListViewItem("Upper Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_UPPERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Lower Filters: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_LOWERFILTERS), $hListView)
					GUICtrlCreateListViewItem("Enumerator: |" & _DeviceAPI_GetDeviceRegistryProperty($SPDRP_ENUMERATOR_NAME), $hListView)

					;Resize columns to fit text
					_GUICtrlListView_SetColumnWidth($hListView, 0, $LVSCW_AUTOSIZE)
					_GUICtrlListView_SetColumnWidth($hListView, 1, $LVSCW_AUTOSIZE)
				EndIf
			WEnd
		EndIf
	Next
EndFunc   ;==>RefreshDeviceProperties


Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $iMsg, $iwParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

	$hWndTreeview = $hTreeView
	If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hWndTreeview
			Switch $iCode
				Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
					RefreshDeviceProperties()
			EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY
 
Автор
S

saavaage

Знающий
Сообщения
171
Репутация
17
Спасибо, CreatoR. "Слона то я и не заметил!" Тема решена.
 
Верх