Имя пользователя:
Пароль:
 | Правила  

Компьютерный форум OSzone.net » Программирование, базы данных и автоматизация действий » AutoIt » [решено] Несколько WM_NOTIFY в одном скрипте

Ответить
Настройки темы
[решено] Несколько WM_NOTIFY в одном скрипте

Ветеран


Сообщения: 904
Благодарности: 162


Конфигурация

Профиль | Отправить PM | Цитировать


Изменения
Автор: saavaage
Дата: 07-09-2010
Вложения
Тип файла: 7z DeviceAPI.7z
(5.3 Kb, 20 просмотров)
Собственно, вопросы:
1. можно ли в одном скрипте (форма с Tab) применить несколько WM_NOTIFY
2. частный случай - не получается совместить работу двух WM_NOTIFY в скрипте следующего типа:

читать дальше »
Код: Выделить весь код
#include <Constants.au3>
#include <EditConstants.au3>
#include <Encoding.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>

; ErrorLogs
Global $hMain_GUI, $nErrorRenew_Button, $hInput, $hInputAll, $ListViewEv, $hListViewEv, $aErrorsNew

; DriversErrors
Global $aAssoc[1][2]


Opt("GUIOnEventMode", 1)

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

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)
;;;; EventErrors ;;;;
Dim $aToList = __ErrorLog()
$EventErrors = GUICtrlCreateTabItem("EventErrors")
$nErrorRenew_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
GUICtrlSetOnEvent($nErrorRenew_Button, "ErrorRenew_Button")

GUICtrlCreateGroup("Расшифровка кода ошибки", 16, 65, 585, 63)
$hInput = GUICtrlCreateEdit('', 24, 80, 570, 39, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))
$ListViewEv = GUICtrlCreateListView('Список Errors логов системы', 16, 133, 585, 169, -1, $LVS_EX_GRIDLINES)
GUICtrlSetState(-1, $GUI_FOCUS)
GUICtrlCreateGroup("Полное описание выделенной ошибки", 16, 305, 585, 82)
$hInputAll = GUICtrlCreateEdit('', 24, 320, 570, 59, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))

GUIRegisterMsg($WM_NOTIFY, 'WM_NOTIFY_Ev')

$hListViewEv = GUICtrlGetHandle($ListViewEv)
_GUICtrlListView_SetColumnWidth($hListViewEv, 0, 2000)
If $aToList <> 0 Then
    _GUICtrlListView_AddColumn($hListViewEv, '')
    For $i = 1 To UBound($aToList) - 1
        _GUICtrlListView_AddItem($hListViewEv, $aToList[$i])
    Next
    _GUICtrlListView_SetItemSelected($hListViewEv, 0)
EndIf


;;; DriversErrors ;;;
$DriverErrors = GUICtrlCreateTabItem("DriversErrors")
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = GUICtrlCreateTreeView(14, 45, 253, 337, $iStyle, $WS_EX_STATICEDGE)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 45, 332, 337)

;GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY_Dr")

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

Dim $total_devices = 0

_DeviceAPI_GetClasses()
While _DeviceAPI_EnumClasses()

	;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
	If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then


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

		;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)

			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

;Cleanup image list
_DeviceAPI_DestroyClassImageList()

_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure


GUICtrlCreateTabItem("")

GUISetState()

While 1
    Sleep(100)
WEnd


Func CLOSEClicked()
  Exit
EndFunc


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;      MAIN FUNCTIONS    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; ErrorsLog Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func ErrorRenew_Button()
	        GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
			_GUICtrlListView_DeleteAllItems($hListViewEv)
			GUICtrlSetData($hInput, '')
            GUICtrlSetData($hInputAll, '')
            $aErrorsNew = __ErrorLog()
            If $aErrorsNew <>0 Then
                For $i = 1 To UBound($aErrorsNew) - 1
				_GUICtrlListView_AddItem($hListViewEv, $aErrorsNew[$i])
                Next
                _GUICtrlListView_SetItemSelected($hListViewEv, 0)
			EndIf
            sleep(1000)
			GUICtrlSetState($nErrorRenew_Button, $GUI_ENABLE)
            GUICtrlSetState($ListViewEv, $GUI_FOCUS)
EndFunc

Func WM_NOTIFY_Ev($EventErrors, $iMsg, $wParam, $lParam)
    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')
    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

Func __ErrorLog()
    GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
    Local $sLog = '', $hError, $aErrorsTemp, $i
    Dim $aErrors[1]
    $hError = Run('CSCRIPT.exe ' & @SystemDir & '\eventquery.vbs /v /fi "Type eq ERROR" /fo TABLE /NH', '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hError)
        If @error Then ExitLoop
       ; Sleep(10)
    WEnd
    If Not $sLog Then Return 0
    $aErrorsTemp = StringSplit(_Encoding_866To1251($sLog), @LF)
    If Not IsArray($aErrorsTemp) Then Return 0
	Dim $aErrors[$aErrorsTemp[0]]
    For $i = 1 To $aErrorsTemp[0]
        If StringInStr($aErrorsTemp[$i], "ошибка") Then
            $aErrors[0] += 1
            $aErrors[$aErrors[0]] = StringStripWS(StringStripCR($aErrorsTemp[$i]), 7)
        EndIf
    Next
    If $aErrors[0] < 1 Then Return 0
	ReDim $aErrors[$aErrors[0]+1]
    Return $aErrors
EndFunc   ;==>__ErrorLog


Func _ErrorHelp($Index)
    Local $iNumberError, $hHelp, $sLog = ''
    GUICtrlSetState($hListViewEv, $GUI_DISABLE)
	$sItemText = _GUICtrlListView_GetItemText($hListViewEv, $Index)
    $iNumberError = StringRegExpReplace($sItemText, "(?s).*?ошибка (.*?)\s+?.*", '\1')
    $hHelp = Run('net helpmsg ' & $iNumberError, '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hHelp)
        If @error Then ExitLoop
        ;Sleep(10)
    WEnd
    $sLog = StringStripWS(StringStripCR(_Encoding_866To1251($sLog)), 7)
    GUICtrlSetData($hInput, 'Ошибка № ' & $iNumberError & '  -  ' & $sLog)
	GUICtrlSetData($hInputAll, $sItemText)
    GUICtrlSetState($hListViewEv, $GUI_ENABLE)
EndFunc   ;==>_ErrorHelp

;; End ErrorLog Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; DriverErrors Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func WM_NOTIFY_Dr($DriverErrors, $iMsg1, $iwParam1, $ilParam1)
	#forceref $DriverErrors, $iMsg1, $iwParam1
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeview

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

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam1)
	$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
;; End DriverErrors Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Проблема - текущий вариант позволяет работать скрипту на вкладке EventErrors (при выделении в listview строки в верхнем и нижнем полях автоматически выдается полное наименование и расшифровка ошибки) и блокирует работу скрипта на вкладке DriverErrors (при "раскрытии плюса" конкретного оборудования без драйверов нельзя в правом поле просмотреть детальную информацию по этому оборудованию).
В случае, когда я убираю комментирование строки
Код: Выделить весь код
;GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY_Dr")
блокируется работа полей подсказок на первой вкладке (EventErrors) и начинает корректно работать скрипт на DriverErrors

PS версия autoit 3.3.6.1

-------
мы рождены, чтоб сказку сделать былью


Отправлено: 11:26, 07-09-2010

 

Аватара для Creat0R

Must AutoIt


Сообщения: 3054
Благодарности: 1009

Профиль | Сайт | Отправить PM | Цитировать


Обычно совмещают код в одной функций, но можно и такой трюк проделать:

Код: Выделить весь код
Func WM_NOTIFY_Ev($EventErrors, $iMsg, $wParam, $lParam)
    WM_NOTIFY_Dr($EventErrors, $iMsg, $wParam, $lParam)

    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')
    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc
т.е вызывать вторую функцию сообщения из первой (регистрировать нужно только первую).

-------
“Сделай так просто, как возможно, но не проще этого.”... “Ты никогда не решишь проблему, если будешь думать так же, как те, кто её создал.”

Альберт Эйнштейн

P.S «Не оказываю техподдержку через ПМ/ICQ, и по email - для этого есть форум. ©»

http://creator-lab.ucoz.ru/Images/Icons/autoit_icon.png Русское сообщество AutoIt | http://creator-lab.ucoz.ru/Images/Ic...eator_icon.png CreatoR's Lab | http://creator-lab.ucoz.ru/Images/Icons/oac_icon.png Opera AC Community

Это сообщение посчитали полезным следующие участники:

Отправлено: 14:56, 07-09-2010 | #2



Для отключения данного рекламного блока вам необходимо зарегистрироваться или войти с учетной записью социальной сети.

Если же вы забыли свой пароль на форуме, то воспользуйтесь данной ссылкой для восстановления пароля.


Ветеран


Сообщения: 904
Благодарности: 162

Профиль | Отправить PM | Цитировать


Creat0R,
Цитата Creat0R:
Func WM_NOTIFY_Ev($EventErrors, $iMsg, $wParam, $lParam)
WM_NOTIFY_Dr($EventErrors, $iMsg, $wParam, $lParam) »
почему и в одной и в другой функциях параметр $EventErrors. Имхо, вторая разве не должна быть записана так:
Код: Выделить весь код
WM_NOTIFY_Dr($DriverErrors, $iMsg1, $iwParam1, $ilParam1)

-------
мы рождены, чтоб сказку сделать былью


Отправлено: 17:59, 07-09-2010 | #3


Аватара для Creat0R

Must AutoIt


Сообщения: 3054
Благодарности: 1009

Профиль | Сайт | Отправить PM | Цитировать


Цитата saavaage:
почему и в одной и в другой функциях параметр $EventErrors »
А я знал что будет такой вопрос

Функций «WM_NOTIFY_Dr» будет передан параметр $hWnd, что такое $EventErrors или $DriverErrors я не знаю.

Цитата saavaage:
вторая разве не должна быть записана так »
И что, работает? а откуда берётся переменная $DriverErrors?

Код: Выделить весь код
Func WM_NOTIFY_Ev($hWnd, $iMsg, $wParam, $lParam)
    WM_NOTIFY_Dr($hWnd, $iMsg, $wParam, $lParam)

-------
“Сделай так просто, как возможно, но не проще этого.”... “Ты никогда не решишь проблему, если будешь думать так же, как те, кто её создал.”

Альберт Эйнштейн

P.S «Не оказываю техподдержку через ПМ/ICQ, и по email - для этого есть форум. ©»

http://creator-lab.ucoz.ru/Images/Icons/autoit_icon.png Русское сообщество AutoIt | http://creator-lab.ucoz.ru/Images/Ic...eator_icon.png CreatoR's Lab | http://creator-lab.ucoz.ru/Images/Icons/oac_icon.png Opera AC Community


Отправлено: 22:48, 07-09-2010 | #4


Ветеран


Сообщения: 904
Благодарности: 162

Профиль | Отправить PM | Цитировать


Creat0R, не работает, конечно.
Вопрос по
Цитата Creat0R:
Обычно совмещают код в одной функций »
:совмещение происходит через case? Приблизительно так?:

Код: Выделить весь код
Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
	#forceref $hWnd, $iMsg, $iwParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR
    $hWndListViewEv = $hListViewEv
	$hWndTreeViewDr = $hTreeViewDr
	If Not IsHWnd($hTreeViewDr) Then $hWndTreeviewDr = GUICtrlGetHandle($hTreeViewDr)

	$tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
	$hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
	$iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
	$iCode = DllStructGetData($tNMHDR, "Code")
	Switch $hWndFrom
		Case $hWndTreeviewDr
			Switch $iCode
				Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
					RefreshDeviceProperties()
			EndSwitch

		Case $hWndListViewEv
            Switch $iCode
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMHDR, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMHDR, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMHDR, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($iIDFrom)
                    EndIf
		     EndSwitch
	EndSwitch
	Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

-------
мы рождены, чтоб сказку сделать былью


Отправлено: 23:41, 07-09-2010 | #5


Ветеран


Сообщения: 904
Благодарности: 162

Профиль | Отправить PM | Цитировать


Creat0R, изменил скрипт в шапке в соответствии с Вашим советом, но вкладка DriverErrors по прежнему не работает .
Вот, что у меня получилось:
читать дальше »
Код: Выделить весь код
#include <Constants.au3>
#include <EditConstants.au3>
#include <Encoding.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>

; ErrorLogs
Global $hMain_GUI, $nErrorRenew_Button, $hInput, $hInputAll, $ListViewEv, $hListViewEv, $aErrorsNew

; DriversErrors
Global $aAssoc[1][2]
;Global $hTreeView

Opt("GUIOnEventMode", 1)

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

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)
;;;; EventErrors ;;;;
Dim $aToList = __ErrorLog()
$EventErrors = GUICtrlCreateTabItem("EventErrors")
$nErrorRenew_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
GUICtrlSetOnEvent($nErrorRenew_Button, "ErrorRenew_Button")

GUICtrlCreateGroup("Расшифровка кода ошибки", 16, 65, 585, 63)
$hInput = GUICtrlCreateEdit('', 24, 80, 570, 39, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))
$ListViewEv = GUICtrlCreateListView('Список Errors логов системы', 16, 133, 585, 169, -1, $LVS_EX_GRIDLINES)
GUICtrlSetState(-1, $GUI_FOCUS)
GUICtrlCreateGroup("Полное описание выделенной ошибки", 16, 305, 585, 82)
$hInputAll = GUICtrlCreateEdit('', 24, 320, 570, 59, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))

GUIRegisterMsg($WM_NOTIFY, 'WM_NOTIFY_Ev')

$hListViewEv = GUICtrlGetHandle($ListViewEv)
_GUICtrlListView_SetColumnWidth($hListViewEv, 0, 2000)
If $aToList <> 0 Then
    _GUICtrlListView_AddColumn($hListViewEv, '')
    For $i = 1 To UBound($aToList) - 1
        _GUICtrlListView_AddItem($hListViewEv, $aToList[$i])
    Next
    _GUICtrlListView_SetItemSelected($hListViewEv, 0)
EndIf


;;; DriversErrors ;;;
$DriverErrors = GUICtrlCreateTabItem("DriversErrors")
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = GUICtrlCreateTreeView(14, 45, 253, 337, $iStyle, $WS_EX_STATICEDGE)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 45, 332, 337)

GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY_Ev")

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

Dim $total_devices = 0

_DeviceAPI_GetClasses()
While _DeviceAPI_EnumClasses()

	;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
	If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then


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

		;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)

			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

;Cleanup image list
_DeviceAPI_DestroyClassImageList()

_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure


GUICtrlCreateTabItem("")

GUISetState()

While 1
    Sleep(100)
WEnd


Func CLOSEClicked()
  Exit
EndFunc


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;      MAIN FUNCTIONS    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; ErrorsLog Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func ErrorRenew_Button()
	        GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
			_GUICtrlListView_DeleteAllItems($hListViewEv)
			GUICtrlSetData($hInput, '')
            GUICtrlSetData($hInputAll, '')
            $aErrorsNew = __ErrorLog()
            If $aErrorsNew <>0 Then
                For $i = 1 To UBound($aErrorsNew) - 1
				_GUICtrlListView_AddItem($hListViewEv, $aErrorsNew[$i])
                Next
                _GUICtrlListView_SetItemSelected($hListViewEv, 0)
			EndIf
            sleep(1000)
			GUICtrlSetState($nErrorRenew_Button, $GUI_ENABLE)
            GUICtrlSetState($ListViewEv, $GUI_FOCUS)
EndFunc

Func WM_NOTIFY_Ev($hWnd, $iMsg, $wParam, $lParam)
	 WM_NOTIFY_Dr($hWnd, $iMsg, $wParam, $lParam)
    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')
    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc

Func __ErrorLog()
    GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
    Local $sLog = '', $hError, $aErrorsTemp, $i
    Dim $aErrors[1]
    $hError = Run('CSCRIPT.exe ' & @SystemDir & '\eventquery.vbs /v /fi "Type eq ERROR" /fo TABLE /NH', '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hError)
        If @error Then ExitLoop
       ; Sleep(10)
    WEnd
    If Not $sLog Then Return 0
    $aErrorsTemp = StringSplit(_Encoding_866To1251($sLog), @LF)
    If Not IsArray($aErrorsTemp) Then Return 0
	Dim $aErrors[$aErrorsTemp[0]]
    For $i = 1 To $aErrorsTemp[0]
        If StringInStr($aErrorsTemp[$i], "ошибка") Then
            $aErrors[0] += 1
            $aErrors[$aErrors[0]] = StringStripWS(StringStripCR($aErrorsTemp[$i]), 7)
        EndIf
    Next
    If $aErrors[0] < 1 Then Return 0
	ReDim $aErrors[$aErrors[0]+1]
    Return $aErrors
EndFunc   ;==>__ErrorLog


Func _ErrorHelp($Index)
    Local $iNumberError, $hHelp, $sLog = ''
    GUICtrlSetState($hListViewEv, $GUI_DISABLE)
	$sItemText = _GUICtrlListView_GetItemText($hListViewEv, $Index)
    $iNumberError = StringRegExpReplace($sItemText, "(?s).*?ошибка (.*?)\s+?.*", '\1')
    $hHelp = Run('net helpmsg ' & $iNumberError, '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hHelp)
        If @error Then ExitLoop
        ;Sleep(10)
    WEnd
    $sLog = StringStripWS(StringStripCR(_Encoding_866To1251($sLog)), 7)
    GUICtrlSetData($hInput, 'Ошибка № ' & $iNumberError & '  -  ' & $sLog)
	GUICtrlSetData($hInputAll, $sItemText)
    GUICtrlSetState($hListViewEv, $GUI_ENABLE)
EndFunc   ;==>_ErrorHelp

;; End ErrorLog Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; DriverErrors Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func WM_NOTIFY_Dr($hWnd, $iMsg, $wParam, $lParam)
	;#forceref $hWnd, $iMsg, $wParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeView

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

	$tNMHDR = DllStructCreate($tagNMHDR, $lParam)
	$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
;; End DriverErrors Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Где я накосячил, сэнсей?

-------
мы рождены, чтоб сказку сделать былью


Отправлено: 23:58, 07-09-2010 | #6


Аватара для Creat0R

Must AutoIt


Сообщения: 3054
Благодарности: 1009

Профиль | Сайт | Отправить PM | Цитировать


Цитата saavaage:
Где я накосячил »
Я не могу проверить, у меня нет «DeviceAPI.au3». ...

Цитата saavaage:
вкладка DriverErrors по прежнему не работает »
Что именно должно работать?

Цитата saavaage:
совмещение происходит через case? Приблизительно так? »
Да.

Код: Выделить весь код
Func WM_NOTIFY_Ev($hWnd, $iMsg, $wParam, $lParam)

    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')

    Local $hWndTreeview = $hTreeView
    If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)
    Local $tNMHDR = DllStructCreate($tagNMHDR, $lParam)
    Local $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
    Local $iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
    Local $iCode = DllStructGetData($tNMHDR, "Code")

    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
        Case $hWndTreeview
            Switch $iCode
                Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
                    RefreshDeviceProperties()
            EndSwitch
    EndSwitch

    Return $GUI_RUNDEFMSG
EndFunc

-------
“Сделай так просто, как возможно, но не проще этого.”... “Ты никогда не решишь проблему, если будешь думать так же, как те, кто её создал.”

Альберт Эйнштейн

P.S «Не оказываю техподдержку через ПМ/ICQ, и по email - для этого есть форум. ©»

http://creator-lab.ucoz.ru/Images/Icons/autoit_icon.png Русское сообщество AutoIt | http://creator-lab.ucoz.ru/Images/Ic...eator_icon.png CreatoR's Lab | http://creator-lab.ucoz.ru/Images/Icons/oac_icon.png Opera AC Community

Это сообщение посчитали полезным следующие участники:

Отправлено: 00:16, 08-09-2010 | #7


Ветеран


Сообщения: 904
Благодарности: 162

Профиль | Отправить PM | Цитировать


Creat0R, Прошу прощение. Племяш, оказывается, переустановил дрова. Я специально удалял пару для теста. Вобщем, естественно, у меня поля вкладки DriverErrors были пусты. Столько времени убить!
Спасибо Вам за помощь. Все работает.

рабочий код (для проверки сделал вывод всего оборудования, для которого есть дрова)

через case:

читать дальше »
Код: Выделить весь код
#include <Constants.au3>
#include <EditConstants.au3>
#include <Encoding.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>

; ErrorLogs
Global $hMain_GUI, $nErrorRenew_Button, $hInput, $hInputAll, $ListViewEv, $hListViewEv, $aErrorsNew

; DriversErrors
Global $aAssoc[1][2]
Global $hTreeView

Opt("GUIOnEventMode", 1)

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

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)
;;;; EventErrors ;;;;
Dim $aToList = __ErrorLog()
$EventErrors = GUICtrlCreateTabItem("EventErrors")
$nErrorRenew_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
GUICtrlSetOnEvent($nErrorRenew_Button, "ErrorRenew_Button")

GUICtrlCreateGroup("Расшифровка кода ошибки", 16, 65, 585, 63)
$hInput = GUICtrlCreateEdit('', 24, 80, 570, 39, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))
$ListViewEv = GUICtrlCreateListView('Список Errors логов системы', 16, 133, 585, 169, -1, $LVS_EX_GRIDLINES)
GUICtrlSetState(-1, $GUI_FOCUS)
GUICtrlCreateGroup("Полное описание выделенной ошибки", 16, 305, 585, 82)
$hInputAll = GUICtrlCreateEdit('', 24, 320, 570, 59, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))

GUIRegisterMsg($WM_NOTIFY, 'WM_NOTIFY_Ev')

$hListViewEv = GUICtrlGetHandle($ListViewEv)
_GUICtrlListView_SetColumnWidth($hListViewEv, 0, 2000)
If $aToList <> 0 Then
    _GUICtrlListView_AddColumn($hListViewEv, '')
    For $i = 1 To UBound($aToList) - 1
        _GUICtrlListView_AddItem($hListViewEv, $aToList[$i])
    Next
    _GUICtrlListView_SetItemSelected($hListViewEv, 0)
EndIf


;;; DriversErrors ;;;
$DriverErrors = GUICtrlCreateTabItem("DriversErrors")
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = GUICtrlCreateTreeView(14, 45, 253, 337, $iStyle, $WS_EX_STATICEDGE)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 45, 332, 337)

Dim $total_devices = 0

_DeviceAPI_GetClasses()
While _DeviceAPI_EnumClasses()

	;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
	If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then


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

		;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)

			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


_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure


GUICtrlCreateTabItem("")

GUISetState()

While 1
    Sleep(100)
WEnd


Func CLOSEClicked()
  Exit
EndFunc


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;      MAIN FUNCTIONS    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; ErrorsLog Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func ErrorRenew_Button()
	        GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
			_GUICtrlListView_DeleteAllItems($hListViewEv)
			GUICtrlSetData($hInput, '')
            GUICtrlSetData($hInputAll, '')
            $aErrorsNew = __ErrorLog()
            If $aErrorsNew <>0 Then
                For $i = 1 To UBound($aErrorsNew) - 1
				_GUICtrlListView_AddItem($hListViewEv, $aErrorsNew[$i])
                Next
                _GUICtrlListView_SetItemSelected($hListViewEv, 0)
			EndIf
            sleep(1000)
			GUICtrlSetState($nErrorRenew_Button, $GUI_ENABLE)
            GUICtrlSetState($ListViewEv, $GUI_FOCUS)
EndFunc

Func WM_NOTIFY_Ev($hWnd, $iMsg, $wParam, $lParam)

    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')

    Local $hWndTreeview = $hTreeView
    If Not IsHWnd($hTreeView) Then $hWndTreeview = GUICtrlGetHandle($hTreeView)
    Local $tNMHDR = DllStructCreate($tagNMHDR, $lParam)
    Local $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
    Local $iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
    Local $iCode = DllStructGetData($tNMHDR, "Code")

    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
        Case $hWndTreeview
            Switch $iCode
                Case $TVN_SELCHANGEDA, $TVN_SELCHANGEDW
                    RefreshDeviceProperties()
            EndSwitch
    EndSwitch

    Return $GUI_RUNDEFMSG
EndFunc

Func __ErrorLog()
    GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
    Local $sLog = '', $hError, $aErrorsTemp, $i
    Dim $aErrors[1]
    $hError = Run('CSCRIPT.exe ' & @SystemDir & '\eventquery.vbs /v /fi "Type eq ERROR" /fo TABLE /NH', '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hError)
        If @error Then ExitLoop
       ; Sleep(10)
    WEnd
    If Not $sLog Then Return 0
    $aErrorsTemp = StringSplit(_Encoding_866To1251($sLog), @LF)
    If Not IsArray($aErrorsTemp) Then Return 0
	Dim $aErrors[$aErrorsTemp[0]]
    For $i = 1 To $aErrorsTemp[0]
        If StringInStr($aErrorsTemp[$i], "ошибка") Then
            $aErrors[0] += 1
            $aErrors[$aErrors[0]] = StringStripWS(StringStripCR($aErrorsTemp[$i]), 7)
        EndIf
    Next
    If $aErrors[0] < 1 Then Return 0
	ReDim $aErrors[$aErrors[0]+1]
    Return $aErrors
EndFunc   ;==>__ErrorLog


Func _ErrorHelp($Index)
    Local $iNumberError, $hHelp, $sLog = ''
    GUICtrlSetState($hListViewEv, $GUI_DISABLE)
	$sItemText = _GUICtrlListView_GetItemText($hListViewEv, $Index)
    $iNumberError = StringRegExpReplace($sItemText, "(?s).*?ошибка (.*?)\s+?.*", '\1')
    $hHelp = Run('net helpmsg ' & $iNumberError, '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hHelp)
        If @error Then ExitLoop
        ;Sleep(10)
    WEnd
    $sLog = StringStripWS(StringStripCR(_Encoding_866To1251($sLog)), 7)
    GUICtrlSetData($hInput, 'Ошибка № ' & $iNumberError & '  -  ' & $sLog)
	GUICtrlSetData($hInputAll, $sItemText)
    GUICtrlSetState($hListViewEv, $GUI_ENABLE)
EndFunc   ;==>_ErrorHelp

;; End ErrorLog Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; DriverErrors Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;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
;; End DriverErrors Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


через "трюк" (запуск одного WM_NOTIFY из другого WM_NOTIFY):

читать дальше »
Код: Выделить весь код
#include <Constants.au3>
#include <EditConstants.au3>
#include <Encoding.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>

; ErrorLogs
Global $hMain_GUI, $nErrorRenew_Button, $hInput, $hInputAll, $ListViewEv, $hListViewEv, $aErrorsNew

; DriversErrors
Global $aAssoc[1][2]
Global $hTreeView

Opt("GUIOnEventMode", 1)

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

$Tab1 = GUICtrlCreateTab(8, 16, 601, 377)
;;;; EventErrors ;;;;
Dim $aToList = __ErrorLog()
$EventErrors = GUICtrlCreateTabItem("EventErrors")
$nErrorRenew_Button = GUICtrlCreateButton("Обновить", 440, 400, 85, 33)
GUICtrlSetOnEvent($nErrorRenew_Button, "ErrorRenew_Button")

GUICtrlCreateGroup("Расшифровка кода ошибки", 16, 65, 585, 63)
$hInput = GUICtrlCreateEdit('', 24, 80, 570, 39, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))
$ListViewEv = GUICtrlCreateListView('Список Errors логов системы', 16, 133, 585, 169, -1, $LVS_EX_GRIDLINES)
GUICtrlSetState(-1, $GUI_FOCUS)
GUICtrlCreateGroup("Полное описание выделенной ошибки", 16, 305, 585, 82)
$hInputAll = GUICtrlCreateEdit('', 24, 320, 570, 59, BitOR($ES_READONLY, $ES_MULTILINE, $WS_VSCROLL))

GUIRegisterMsg($WM_NOTIFY, 'WM_NOTIFY_Ev')

$hListViewEv = GUICtrlGetHandle($ListViewEv)
_GUICtrlListView_SetColumnWidth($hListViewEv, 0, 2000)
If $aToList <> 0 Then
    _GUICtrlListView_AddColumn($hListViewEv, '')
    For $i = 1 To UBound($aToList) - 1
        _GUICtrlListView_AddItem($hListViewEv, $aToList[$i])
    Next
    _GUICtrlListView_SetItemSelected($hListViewEv, 0)
EndIf


;;; DriversErrors ;;;
$DriverErrors = GUICtrlCreateTabItem("DriversErrors")
Dim $iStyle = BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS)
$hTreeView = GUICtrlCreateTreeView(14, 45, 253, 337, $iStyle, $WS_EX_STATICEDGE)
GUICtrlSetState(-1, $GUI_FOCUS)
$hListView = GUICtrlCreateListView("Key|Value", 272, 45, 332, 337)

Dim $total_devices = 0

_DeviceAPI_GetClasses()
While _DeviceAPI_EnumClasses()

	;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
	If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then


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

		;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)

			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

_DeviceAPI_DestroyDeviceInfoList() ;Cleanup for good measure


GUICtrlCreateTabItem("")

GUISetState()

While 1
    Sleep(100)
WEnd


Func CLOSEClicked()
  Exit
EndFunc


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;      MAIN FUNCTIONS    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; ErrorsLog Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Func ErrorRenew_Button()
	        GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
			_GUICtrlListView_DeleteAllItems($hListViewEv)
			GUICtrlSetData($hInput, '')
            GUICtrlSetData($hInputAll, '')
            $aErrorsNew = __ErrorLog()
            If $aErrorsNew <>0 Then
                For $i = 1 To UBound($aErrorsNew) - 1
				_GUICtrlListView_AddItem($hListViewEv, $aErrorsNew[$i])
                Next
                _GUICtrlListView_SetItemSelected($hListViewEv, 0)
			EndIf
            sleep(1000)
			GUICtrlSetState($nErrorRenew_Button, $GUI_ENABLE)
            GUICtrlSetState($ListViewEv, $GUI_FOCUS)
EndFunc

Func WM_NOTIFY_Ev($hWnd, $iMsg, $wParam, $lParam)
	 WM_NOTIFY_Dr($hWnd, $iMsg, $wParam, $lParam)
    Local $tNMITEMACTIVATE = DllStructCreate($tagNMITEMACTIVATE, $lParam)
    Local $hFrom = DllStructGetData($tNMITEMACTIVATE, 'hWndFrom')
    Local $Index = DllStructGetData($tNMITEMACTIVATE, 'Index')
    Local $ID = DllStructGetData($tNMITEMACTIVATE, 'Code')
    Switch $hFrom
        Case $hListViewEv
            Switch $ID
                Case $LVN_ITEMCHANGED
                    If (BitAND(DllStructGetData($tNMITEMACTIVATE, 'Changed'), $LVIF_STATE)) And _
                            (BitAND(DllStructGetData($tNMITEMACTIVATE, 'NewState'), $LVIS_SELECTED)) _
                            And (Not BitAND(DllStructGetData($tNMITEMACTIVATE, 'OldState'), $LVIS_FOCUSED)) Then
                        _ErrorHelp($Index)
                    EndIf
            EndSwitch
    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc

Func __ErrorLog()
    GUICtrlSetState($nErrorRenew_Button, $GUI_DISABLE)
    Local $sLog = '', $hError, $aErrorsTemp, $i
    Dim $aErrors[1]
    $hError = Run('CSCRIPT.exe ' & @SystemDir & '\eventquery.vbs /v /fi "Type eq ERROR" /fo TABLE /NH', '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hError)
        If @error Then ExitLoop
       ; Sleep(10)
    WEnd
    If Not $sLog Then Return 0
    $aErrorsTemp = StringSplit(_Encoding_866To1251($sLog), @LF)
    If Not IsArray($aErrorsTemp) Then Return 0
	Dim $aErrors[$aErrorsTemp[0]]
    For $i = 1 To $aErrorsTemp[0]
        If StringInStr($aErrorsTemp[$i], "ошибка") Then
            $aErrors[0] += 1
            $aErrors[$aErrors[0]] = StringStripWS(StringStripCR($aErrorsTemp[$i]), 7)
        EndIf
    Next
    If $aErrors[0] < 1 Then Return 0
	ReDim $aErrors[$aErrors[0]+1]
    Return $aErrors
EndFunc   ;==>__ErrorLog


Func _ErrorHelp($Index)
    Local $iNumberError, $hHelp, $sLog = ''
    GUICtrlSetState($hListViewEv, $GUI_DISABLE)
	$sItemText = _GUICtrlListView_GetItemText($hListViewEv, $Index)
    $iNumberError = StringRegExpReplace($sItemText, "(?s).*?ошибка (.*?)\s+?.*", '\1')
    $hHelp = Run('net helpmsg ' & $iNumberError, '', @SW_HIDE, $STDOUT_CHILD)
    While 1
        $sLog &= StdoutRead($hHelp)
        If @error Then ExitLoop
        ;Sleep(10)
    WEnd
    $sLog = StringStripWS(StringStripCR(_Encoding_866To1251($sLog)), 7)
    GUICtrlSetData($hInput, 'Ошибка № ' & $iNumberError & '  -  ' & $sLog)
	GUICtrlSetData($hInputAll, $sItemText)
    GUICtrlSetState($hListViewEv, $GUI_ENABLE)
EndFunc   ;==>_ErrorHelp

;; End ErrorLog Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; DriverErrors Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Func WM_NOTIFY_Dr($hWnd, $iMsg, $wParam, $lParam)
	;#forceref $hWnd, $iMsg, $wParam
	Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndTreeView

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

	$tNMHDR = DllStructCreate($tagNMHDR, $lParam)
	$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
;; End DriverErrors Section  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


для вывода оборудования с отсутствующими драйверами заменить сроку
Код: Выделить весь код
If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) <> '' Then
на
Код: Выделить весь код
If _DeviceAPI_GetDeviceCount() > 0 and _DeviceAPI_GetDeviceRegistryProperty($SPDRP_DRIVER) = '' Then
Тема решена.

-------
мы рождены, чтоб сказку сделать былью


Последний раз редактировалось saavaage, 08-09-2010 в 15:28.


Отправлено: 00:45, 08-09-2010 | #8



Компьютерный форум OSzone.net » Программирование, базы данных и автоматизация действий » AutoIt » [решено] Несколько WM_NOTIFY в одном скрипте

Участник сейчас на форуме Участник сейчас на форуме Участник вне форума Участник вне форума Автор темы Автор темы Шапка темы Сообщение прикреплено

Похожие темы
Название темы Автор Информация о форуме Ответов Последнее сообщение
MSFT SQL Server - Несколько СУБД на одном сервере СаркозаН Программирование и базы данных 8 03-05-2010 13:13
Несколько операционных систем на одном PC treiber Хочу все знать 9 27-06-2007 11:10
Несколько фильмов на одном диске alexra Видео и аудио: обработка и кодирование 4 11-04-2006 18:46
несколько ОС на одном HDD Guest Хочу все знать 7 19-10-2004 07:17
Несколько OS Linux + WinXp на одном PC jem Общий по Linux 6 09-06-2004 22:35




 
Переход