Что нового

Действие с несколькими файлами

saraconor

Новичок
Сообщения
420
Репутация
3
В папке 4 файла, из них выделено 2, как скопировать путь этих двух файлов?
Если 1 файл то не проблема:
Код:
Send("{F2}")
$text= WinGetText("[ACTIVE]", "")
$array = StringSplit($text,Chr(10))

и дальше расплетаем массив до нужного текста, а с 2 файлами как быть? как вообще дать понять программе что выделено 2 объекта в папке, и вытянуть из каждого его информацию (вес, путь, свойства, итп) ?
 
Автор
S

saraconor

Новичок
Сообщения
420
Репутация
3
Мало того что я давным давно использовала наработки из той темы, так еще я повторюсь что речь идет о 2х файлах.
 

WSWR

AutoIT Гуру
Сообщения
941
Репутация
363
saraconor
Какая операционная система? Если XP, то не трудно сделать, а вот если Win 7, то сложнее...
На эту тему: http://autoit-script.ru/index.php/topic,3499.45.html

В принципе, пример от KaFu с офф форума вроде работает на Win 7, показывает выделенные объекты...
Код:
#include <Array.au3>

$aWinList = WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
For $i = 1 To UBound($aWinList) - 1
    $aSelection = _WindowsExplorer_ExtractSelectedDirAndFiles($aWinList[$i][1])
    _ArrayDisplay($aSelection, "Explorer Instance #" & $i & " / " & WinGetTitle($aWinList[$i][1]))
Next

; ===================================================================================================================
; Name...........: _WindowsExplorer_ExtractSelectedDirAndFiles
; Description....: Function to extract LocationURL and selected files from a "Windows Explorer" Window
; Syntax.........: _WindowsExplorer_ExtractSelectedDirAndFiles($hWnd)
; Parameters.....: $hWnd - Windows handle of an "Windows Explorer" Window
; AutoIt Version.: 3.3.6.1
; Return values..: Success  -   Array
;                               Array[0] = Number of files selected in right-hand Listview
;                               Array[1] = LocationURL - selected in left-hand Treeview or Window Rebar
;                               Array[2] - Array[n] = URL of selected files in right-hand Listview
;                  Failure  -   Array
;                               Array[0] = 0
;                               Array[1] = ""
;                               Sets the @error flag to non-zero.
;                               @error = 1 - $hwnd is not a valid window handle
;                               @error = 2 - $hwnd is not a window handle for an "Windows Explorer" Window
;                               @error = 3 - "Shell.Application" object could not be created
;                               @error = 4 - "$oShellApp.Windows()" object could not be created
; Author.........: Ascend4nt, KaFu, klaus.s
; ===================================================================================================================

Func _WindowsExplorer_ExtractSelectedDirAndFiles($hWnd)
    Local $aExplorerSelectedFiles[2] = [0, ""]
    If Not IsHWnd($hWnd) Then Return SetError(1, 0, $aExplorerSelectedFiles)
    Local $aWinList = WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
    While 1
        For $i = 1 To UBound($aWinList) - 1
            If $hWnd = $aWinList[$i][1] Then ExitLoop 2
        Next
        Return SetError(2, 0, $aExplorerSelectedFiles)
    WEnd
    Local $oShellApp = ObjCreate("Shell.Application")
    If Not IsObj($oShellApp) Then Return SetError(3, 0, $aExplorerSelectedFiles)
    Local $oShellApp_Windows = $oShellApp.Windows()
    If Not IsObj($oShellApp_Windows) Then Return SetError(4, 0, $aExplorerSelectedFiles)
    For $oShellApp_Inst In $oShellApp_Windows
        If $oShellApp_Inst.hwnd = $hWnd Then ExitLoop
    Next
    Local $oShellApp_Inst_SelectedItems_Count = $oShellApp_Inst.document.SelectedItems.Count
    Local $oShellApp_Inst_LocationURL = $oShellApp_Inst.LocationURL
    Local $aHexCodes = StringRegExp($oShellApp_Inst_LocationURL, '%([[:xdigit:]]{2})', 3)
    If Not @error Then
        ; Change all the '%xx' values into ';'s (invalid path character)
        $oShellApp_Inst_LocationURL = StringRegExpReplace($oShellApp_Inst_LocationURL, '%([[:xdigit:]]{2})', ';')
        ; Then go through 1 by 1 and replace each ';' in left-to-right order (same as array order)
        For $i = 0 To UBound($aHexCodes) - 1
            $oShellApp_Inst_LocationURL = StringReplace($oShellApp_Inst_LocationURL, ';', ChrW('0x' & $aHexCodes[$i]), 1) ; only the 1st occurrence for each rep!
        Next
    EndIf
    $oShellApp_Inst_LocationURL = StringReplace($oShellApp_Inst_LocationURL, 'file:///', '')
    $aExplorerSelectedFiles[0] = $oShellApp_Inst_SelectedItems_Count
    $aExplorerSelectedFiles[1] = StringReplace($oShellApp_Inst_LocationURL, '/', '\')
    ReDim $aExplorerSelectedFiles[$aExplorerSelectedFiles[0] + 2]
    $oShellApp_Inst_SelectedItems = $oShellApp_Inst.document.SelectedItems
    Local $iCounter = 2
    For $oShellApp_Inst_SelectedItem In $oShellApp_Inst_SelectedItems
        $aExplorerSelectedFiles[$iCounter] = $oShellApp_Inst_SelectedItem.path
        $iCounter += 1
    Next
    $oShellApp = 0
    $oShellApp_Windows = 0
    Return $aExplorerSelectedFiles
EndFunc   ;==>_WindowsExplorer_ExtractSelectedDirAndFiles
 
Автор
S

saraconor

Новичок
Сообщения
420
Репутация
3
Семерка. :smile:
Есть програмка CopyFileName.exe вот в ней подобная функция реализована отлично, при выделении нескольких файлов, она может вставить в буфер обмена сразу все пути каждого файла, вот бы в autoit сделать нечто подобное...
 

WSWR

AutoIT Гуру
Сообщения
941
Репутация
363
saraconor
Ну, выше приведенный код вроде получает пути, соответственно, кинуть их в буфер не проблема.
Вот пример скрипта, по нажатию клавиши "Pause" отображает выделенные файлы-папки (можно закомментировать) из активного окна, и помещает пути до них в буфер, разделенные "|".

Код:
#include <Array.au3>
#include <WinAPI.au3>

HotKeySet('{Pause}', '_Selected')

While 1
	Sleep(10)
WEnd

Func _Selected()
	Local $hWnd = WinGetHandle('[ACTIVE]', '')
	If _WinAPI_IsClassName($hWnd, 'CabinetWClass') Then
		$aSelection = _WindowsExplorer_ExtractSelectedDirAndFiles($hWnd)
		ClipPut(_ArrayToString($aSelection, '|', 2))
		_ArrayDisplay($aSelection)
	EndIf
EndFunc   ;==>_Selected

; ===================================================================================================================
; Name...........: _WindowsExplorer_ExtractSelectedDirAndFiles
; Description....: Function to extract LocationURL and selected files from a "Windows Explorer" Window
; Syntax.........: _WindowsExplorer_ExtractSelectedDirAndFiles($hWnd)
; Parameters.....: $hWnd - Windows handle of an "Windows Explorer" Window
; AutoIt Version.: 3.3.6.1
; Return values..: Success  -   Array
;                               Array[0] = Number of files selected in right-hand Listview
;                               Array[1] = LocationURL - selected in left-hand Treeview or Window Rebar
;                               Array[2] - Array[n] = URL of selected files in right-hand Listview
;                  Failure  -   Array
;                               Array[0] = 0
;                               Array[1] = ""
;                               Sets the @error flag to non-zero.
;                               @error = 1 - $hwnd is not a valid window handle
;                               @error = 2 - $hwnd is not a window handle for an "Windows Explorer" Window
;                               @error = 3 - "Shell.Application" object could not be created
;                               @error = 4 - "$oShellApp.Windows()" object could not be created
; Author.........: Ascend4nt, KaFu, klaus.s
; ===================================================================================================================

Func _WindowsExplorer_ExtractSelectedDirAndFiles($hWnd)
    Local $aExplorerSelectedFiles[2] = [0, ""]
    If Not IsHWnd($hWnd) Then Return SetError(1, 0, $aExplorerSelectedFiles)
    Local $aWinList = WinList("[REGEXPCLASS:(Explore|Cabinet)WClass]")
    While 1
        For $i = 1 To UBound($aWinList) - 1
            If $hWnd = $aWinList[$i][1] Then ExitLoop 2
        Next
        Return SetError(2, 0, $aExplorerSelectedFiles)
    WEnd
    Local $oShellApp = ObjCreate("Shell.Application")
    If Not IsObj($oShellApp) Then Return SetError(3, 0, $aExplorerSelectedFiles)
    Local $oShellApp_Windows = $oShellApp.Windows()
    If Not IsObj($oShellApp_Windows) Then Return SetError(4, 0, $aExplorerSelectedFiles)
    For $oShellApp_Inst In $oShellApp_Windows
        If $oShellApp_Inst.hwnd = $hWnd Then ExitLoop
    Next
    Local $oShellApp_Inst_SelectedItems_Count = $oShellApp_Inst.document.SelectedItems.Count
    Local $oShellApp_Inst_LocationURL = $oShellApp_Inst.LocationURL
    Local $aHexCodes = StringRegExp($oShellApp_Inst_LocationURL, '%([[:xdigit:]]{2})', 3)
    If Not @error Then
        ; Change all the '%xx' values into ';'s (invalid path character)
        $oShellApp_Inst_LocationURL = StringRegExpReplace($oShellApp_Inst_LocationURL, '%([[:xdigit:]]{2})', ';')
        ; Then go through 1 by 1 and replace each ';' in left-to-right order (same as array order)
        For $i = 0 To UBound($aHexCodes) - 1
            $oShellApp_Inst_LocationURL = StringReplace($oShellApp_Inst_LocationURL, ';', ChrW('0x' & $aHexCodes[$i]), 1) ; only the 1st occurrence for each rep!
        Next
    EndIf
    $oShellApp_Inst_LocationURL = StringReplace($oShellApp_Inst_LocationURL, 'file:///', '')
    $aExplorerSelectedFiles[0] = $oShellApp_Inst_SelectedItems_Count
    $aExplorerSelectedFiles[1] = StringReplace($oShellApp_Inst_LocationURL, '/', '\')
    ReDim $aExplorerSelectedFiles[$aExplorerSelectedFiles[0] + 2]
    $oShellApp_Inst_SelectedItems = $oShellApp_Inst.document.SelectedItems
    Local $iCounter = 2
    For $oShellApp_Inst_SelectedItem In $oShellApp_Inst_SelectedItems
        $aExplorerSelectedFiles[$iCounter] = $oShellApp_Inst_SelectedItem.path
        $iCounter += 1
    Next
    $oShellApp = 0
    $oShellApp_Windows = 0
    Return $aExplorerSelectedFiles
EndFunc   ;==>_WindowsExplorer_ExtractSelectedDirAndFiles

Если нужно получить какие-то конкретные части путей до файла, то можно использовать функции отсюда: http://autoit-script.ru/index.php?topic=316.0
 

InnI

AutoIT Гуру
Сообщения
4,982
Репутация
1,460
saraconor [?]
В папке 4 файла, из них выделено 2, как скопировать путь этих двух файлов?
Код:
HotKeySet("^{F2}", "CopyPath")

Do
  Sleep(1000)
Until 0

Func CopyPath()
  Send("^{INS}")
  MsgBox(0, "Path", ClipGet())
;~   ClipPut("")
EndFunc
 
Верх