<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
	<link rel="self" href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=810&amp;type=atom" />
	<updated>2011-08-24T22:01:24Z</updated>
	<generator>PunBB</generator>
	<id>http://forum.script-coding.com/viewtopic.php?id=810</id>
		<entry>
			<title type="html"><![CDATA[Re: AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=50861#p50861" />
			<content type="html"><![CDATA[<p>Для демонстрации возможностей <a href="http://www.autohotkey.com/forum/topic34070.html"><strong>AHK_L</strong></a>, создание новой папки в окнах <em>CabinetWClass</em> или <em>ExploreWClass</em> через <strong>COM</strong>:<br /></p><div class="codebox"><pre><code>F7::
   SetBatchLines, -1
   WinGet, ID,, A
   WinGetClass, Class, A
   if !(Class ~= &quot;(Cabinet|Explore)WClass&quot;)
      Return

   oShell := ComObjCreate(&quot;Shell.Application&quot;)
   Loop
   {
      oIE := oShell.Windows.Item(A_Index - 1)
      Sleep, 10
   } Until oIE.HWND = ID   ; получаем объект InternetExplorer для активного окна
 
   oShellFolderView := oIE.Document
   oFolder := oShellFolderView.Folder
   if !(oFolder.Self.IsFileSystem)   ; если родительская папка не является частью файловой системы
   {
      MsgBox, % &quot;Папка &quot;&quot;&quot; oFolder.Self.Name &quot;&quot;&quot; не является частью файловой системы`
            ,`nсоздание новой папки в ней невозможно!&quot;
      oShell := oIE := oShellFolderView := oFolder := &quot;&quot;
      Return
   }
 
   Loop   ; определяем имя новой папки в зависимости
   {      ; от существования других объектов с названием &quot;Новая папка (i)&quot;
      Sleep, 10
      FolderName := &quot;Новая папка&quot; . (A_Index = 1 ? &quot;&quot; : &quot; (&quot; . A_Index . &quot;)&quot;)
   } Until !IsObject(oFolder.ParseName(FolderName))

   Count := oFolder.Items.Count    ; перед созданием новой папки определяем количество видимых объектов
   oFolder.NewFolder(FolderName)   ; создаём новую папку
   While (Count = oFolder.Items.Count)    ; ждём, пока новая папка не станет видимой
      Sleep, 50                           ; и общее количество объектов не изменится

   oShellFolderView.SelectItem(oFolder.ParseName(FolderName), 1|3|4|8)
   oShell := oIE := oShellFolderView := oFolder := &quot;&quot;   ; удаляем объекты из памяти
   Return</code></pre></div><p>Не сработает на Десктопе, сработает в Моих Документах.</p><p>Справочная информация: <a href="http://www.autohotkey.com/forum/topic61509.html"><strong>COM Object Reference [AutoHotkey_L]</strong></a><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="http://www.autohotkey.com/forum/viewtopic.php?&amp;p=384523#384523"><strong>COM Object: Shell.Application</strong></a><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="http://msdn.microsoft.com/en-us/library/bb773938%28VS.85%29.aspx"><strong>Shell Objects for Scripting</strong></a><br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="http://msdn.microsoft.com/en-us/library/bb774094%28VS.85%29.aspx"><strong>Shell Object</strong></a><br /><a href="http://forum.script-coding.com/viewtopic.php?id=6145"><strong>Тема</strong></a> для обсуждения на форуме.</p>]]></content>
			<author>
				<name><![CDATA[teadrinker]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=24515</uri>
			</author>
			<updated>2011-08-24T22:01:24Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=50861#p50861</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=14181#p14181" />
			<content type="html"><![CDATA[<p>Ещё более усовершенствованный вариант скрипта. В контекстном меню иконки в трее есть возможности:<br />+ использовать диалог (переключатель);<br />+ использовать буфер обмена (переключатель);<br />+ отображать уведомления об успехе/неуспехе (переключатель);<br />+ поместить скрипт в автозагрузку (переключатель).<br />Имя папки может редактироваться непосредственно в Проводнике, точно так же, как это происходит при обычном создании папки без скриптов.<br /></p><div class="codebox"><pre><code>#SingleInstance Force
#MaxThreadsPerHotkey 5

SplitPath, A_ScriptName, , , , strIniFileName
strIniFileName = %strIniFileName%.ini

Menu, Tray, Icon, Shell32.dll, 4
Menu, Tray, Tip , Press F7 in Explorer to create New folder

Menu, Tray, NoStandard

Menu, Tray, Add, Use dialog, mhUseDialog
IniRead, boolUseDialog, %A_ScriptDir%\%strIniFileName%, Main, UseDialog, %False%
If (boolUseDialog)
    Menu, Tray, Check, Use dialog
Else
    Menu, Tray, Uncheck, Use dialog

Menu, Tray, Add, Use clipboard, mhUseClipboard
IniRead, boolUseClipboard, %A_ScriptDir%\%strIniFileName%, Main, UseClipboard, %True%
If (boolUseClipboard)
    Menu, Tray, Check, Use clipboard
Else
    Menu, Tray, Uncheck, Use clipboard

Menu, Tray, Add, Show notification, mhShowNotification
IniRead, boolShowNotification, %A_ScriptDir%\%strIniFileName%, Main, ShowNotification, %True%
If (boolShowNotification)
    Menu, Tray, Check, Show notification
Else
    Menu, Tray, Uncheck, Show notification

;Menu, Tray, Add, Change folder, mhChangeFolder
;IniRead, boolChangeFolder, %A_ScriptDir%\%strIniFileName%, Main, ChangeFolder, %True%
;If (boolChangeFolder)
;    Menu, Tray, Check, Change folder
;Else
;    Menu, Tray, Uncheck, Change folder
;Menu, Tray, Disable, Change folder
    
Menu, Tray, Add

Menu, Tray, Add, Start with &amp;Windows, mhAutorun
IniRead, boolAutorun, %A_ScriptDir%\%strIniFileName%, Main, Autorun, %False%
If (boolAutorun)
{
    Menu, Tray, Check, Start with &amp;Windows
    RegWrite, REG_SZ, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Run, F7, &quot;%A_ScriptFullPath%&quot;
}
Else
{
    Menu, Tray, Uncheck, Start with &amp;Windows
    RegDelete, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Run, F7
}

Menu, Tray, Add

Menu, Tray, Add, Quit, mhQuit
Menu, Tray, Default , Quit

If boolShowNotification
{
    TrayTip, ,Press F7 in Explorer to create New folder, 3, 1
    Sleep, 3 * 1000
    TrayTip,
}
;=============================================================================

;=============================================================================
#IfWinActive, ahk_class CabinetWClass
F7::
#IfWinActive, ahk_class ExploreWClass
F7::

WinGet, intHWND, ID, A
WinGet, strProcessName, ProcessName, ahk_id %intHWND%

IfEqual, strProcessName, explorer.exe
{
    ControlGetText, strParentFolder, Edit1, ahk_id %intHWND%
    IfExist, %strParentFolder%
    {
        If boolUseClipboard
        {
            StringReplace, strFolder, Clipboard, &quot; , , All
            SplitPath, strFolder , strFolder
        }
        Else
        {
            Loop
            {
                If A_Index = 1
                    strFolder = Новая папка
                Else 
                    strFolder = Новая папка (%A_Index%)
                
                IfNotExist, %strParentFolder%\%strFolder%
                    Break
            }
        }
        
        If boolUseDialog
        {
            InputBox, strFolder, Создание папки, Создать папку, , , 120, , , , , %strFolder%
            IfEqual, ErrorLevel, 0
                IfNotEqual, strFolder,
                    Gosub, subCreateFolder
        }
        Else
        {
            Gosub, subCreateFolder
        }
    }
}

Return
;=============================================================================

;=============================================================================
mhUseDialog:
    boolUseDialog := Not boolUseDialog
    Menu, Tray, ToggleCheck, Use dialog
    IniWrite, %boolUseDialog%, %A_ScriptDir%\%strIniFileName%, Main, UseDialog
Return
;=============================================================================

;=============================================================================
mhUseClipboard:
    boolUseClipboard := Not boolUseClipboard
    Menu, Tray, ToggleCheck, Use clipboard
    IniWrite, %boolUseClipboard%, %A_ScriptDir%\%strIniFileName%, Main, UseClipboard
Return
;=============================================================================

;=============================================================================
mhShowNotification:
    boolShowNotification := Not boolShowNotification
    Menu, Tray, ToggleCheck, Show notification
    IniWrite, %boolShowNotification%, %A_ScriptDir%\%strIniFileName%, Main, ShowNotification
Return
;=============================================================================

;=============================================================================
;mhChangeFolder:
;    boolChangeFolder := Not boolChangeFolder
;    Menu, Tray, ToggleCheck, Change folder
;    IniWrite, %boolChangeFolder%, %A_ScriptDir%\%strIniFileName%, Main, ChangeFolder
;Return
;=============================================================================

;=============================================================================
mhAutorun:
    boolAutorun := Not boolAutorun
    Menu, Tray, ToggleCheck, Start with &amp;Windows
    IniWrite, %boolAutorun%, %A_ScriptDir%\%strIniFileName%, Main, Autorun
    
    If (boolAutorun)
        RegWrite, REG_SZ, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Run, F7, &quot;%A_ScriptFullPath%&quot;
    Else
        RegDelete, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Run, F7
Return
;=============================================================================

;=============================================================================
mhQuit:
    ExitApp, 0
Return
;=============================================================================

;=============================================================================
subCreateFolder:
    IfNotExist, %strParentFolder%\%strFolder%
    {
        ControlGet, intOldItemsCount, List, Count, SysListView321, ahk_id %intHWND%
        FileCreateDir, %strParentFolder%\%strFolder%
        
        If (ErrorLevel = 0) And (FileExist(strParentFolder . &quot;\&quot; . strFolder))
        {
            Loop, 1000
            {
                ControlGet, intNewItemsCount, List, Count, SysListView321, ahk_id %intHWND%
                
                If Not (intNewItemsCount == (intOldItemsCount + 1))
                    Sleep, 10
                Else
                    Break
            }
            ControlFocus, SysListView321, ahk_id %intHWND%
            Send, {End}
            
            ControlGet, strSelected, List, Selected Col1, SysListView321, ahk_id %intHWND%
            If (strSelected == strFolder)
                Send, {F2}
            Gosub, subSuccesInfo
            
        }
        Else
            Gosub, subShowError
    }
    Else
        Gosub, subShowError
Return
;=============================================================================

;=============================================================================
subSuccesInfo:
    If boolShowNotification
    {
        TrayTip, Folder [%strFolder%] created successfully, in [%strParentFolder%], 3, 1
        Sleep, 3 * 1000
        TrayTip,
    }
Return
;=============================================================================

;=============================================================================
subShowError:
    TrayTip, Can&#039;t create folder [%strFolder%], in [%strParentFolder%], 5, 3
    Sleep, 5 * 1000
    TrayTip,
Return
;=============================================================================</code></pre></div><p>Автор скрипта - <strong>alexii</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-09-22T07:59:00Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=14181#p14181</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=13760#p13760" />
			<content type="html"><![CDATA[<p>Усовершенствованный вариант того же скрипта. Теперь в контекстном меню иконки в трее есть два варианта - генерировать имя автоматически или выдавать диалог для задания имени папки.<br /></p><div class="codebox"><pre><code>;***************************************************
; AutoHotkey Version:    1.0.46.06+
; Авторы:                 Resager,alexii
; Имя скрипта:           FolderCreater 2.5.ahk
;**************************************************

; ========== НАСТРОЙКИ ПОЛЬЗОВАТЕЛЯ ============================================
#SingleInstance force                              ; перезагрузить скрипт, если он уже запущен
Menu, Tray, Icon, Shell32.dll, 4                   ;иконка, используемая в трее
Menu, Tray, Tip , Press F7 to create New folder    ;подсказка, выплывающаа при наведении курсора на значок программы в трее
#NoEnv                                             ; запрещаем имена переменных как у переменных окружения
SendMode Input                                     ; режим высылки без задержки и повышенной надежности
neu=fno                                            ; установка режима по умолчанию (в данном случае по умолчанию автоматически случайное имя папки
;Имена пунктов меню в трее:
pmenu1= Вводить своё имя папки
pmenu2= Генерировать имя по маске
; ========== КОНЕЦ НАСТРОЕК ПОЛЬЗОВАТЕЛЯ =======================================

; ========== СОЗДАНИЕ МЕНЮ В ТРЕЕ ==============================================
Menu, Tray, NoStandard ; не использовать стандартное меню
Menu, Tray, Add,%pmenu1%, Menu_fyes
Menu, Tray, Add,%pmenu2%, Menu_fno
Menu, Tray, Add ; разделитель
Menu, Tray, Add, В&amp;ыход, Exit_Script ; выйти из скрипта
; расставляем галочки
If neu=fyes
    Menu, Tray, Check,%pmenu1%; поставить галочку в меню
If neu=fno
    Menu, Tray, Check,%pmenu2%
    ;поставить галочку в меню
Return ; закончить автовыполняющуюся часть
; ========== КОНЕЦ СОЗДАНИЯ МЕНЮ В ТРЕЕ ========================================

; ========== ПОДПРОГРАММЫ ДЛЯ МЕНЮ В ТРЕЕ ======================================
Menu_fyes: ; подпрограмма реагирования на выбор пункта меню
    Menu, Tray, Check,%pmenu1%
    ; поставить галочку в меню
    Menu, Tray, Uncheck,%pmenu2%
    ; снять галочку в меню
    neu=fyes
Return ; конец подпрограммы

Menu_fno: ; подпрограмма реагирования на выбор пункта меню
    Menu, Tray, Check,%pmenu2%
    ; поставить галочку в меню
    Menu, Tray, Uncheck,%pmenu1%
    ; снять галочку в меню
    neu=fno
    Return ; конец подпрограммы

Exit_Script:
    
    ExitApp ; выйти из скрипта
; ========== КОНЕЦ ПОДПРОГРАММ МЕНЮ В ТРЕЕ =====================================

; ========== ПРОГРАММА СОДАНИЯ ПАПОК С ЗАВИСЯЩИМ ОТ НАСТРОЕК ПОЛЬЗОВАТЕЛЯ ИМЕНЕМ ===================
#IfWinActive, ahk_class CabinetWClass  ;Создает контекстно-зависимые вызывающие клавиши и (hotstrings). Такие вызывающие клавиши выполняют различное действие (или несколько действий) в зависимости от типа окна, которое является активным или существует.
;CabinetWClass - ипользовать обработку нажатияя клавиши только &quot;в папках проводника&quot;
F7::
WinGet, intHWND, ID, A ;Отыскивает уникальный логин указанного окна, логин процесса, название{имя} процесса, или список его управлений. Это может также отыскать список всех окон, соответствующих указанным критериям.
WinGet, strProcessName, ProcessName, ahk_id %intHWND% 

;(здесь, сравнивает две переменные (например var и value), анологично выражению if var = value
IfEqual, strProcessName, explorer.exe 
{
    ControlGetText, strParentFolder, Edit1, ahk_id %intHWND%
    IfExist, %strParentFolder%
    {
        Loop
        {
            If A_Index = 1
                strFolder = NewFolder
            Else 
                strFolder = NewFolder(%A_Index%)
            
            IfNotExist, %strParentFolder%\%strFolder%
                Break
        }
        ;InputBox, strFolder, Создание папки, Создать папку, , , 120, , , , , %strFolder%
        ;IfEqual ErrorLevel, 0
        if neu = fyes 
           {
            Gui, Color, FFFFFF
            ;WinSet, TransColor, EEAA99
            ;Gui, Add, Picture , w33 h29, C:\WORKW\pchealth\helpctr\System\images\Centers\Uabrand.gif
            Gui, Add, Text,ym, Foldrer name:
            Gui, Add, Edit, vstrFolder ym ; Опция ym начинает новую колонку элементов управления.
            ;Gui, Add, Text,yn, 
            Gui, Add, Button, default ym, OK ; Метка ButtonOK (если она существует) будет запущена при нажатии кнопки.
            ;Gui, Add, Button,, Cencel ;
            Gui, Show,, Введите имя папки
            f12::
            if okk=0
         {
          Gui, Submit ; Сохраняем входные данные пользователя в ассоциированной переменной каждого элемента управления.
          Gui, Destroy ;уничтожаем созданное нами окно, чтобы в дальнейшем мы смогли заново его перестроить
          }
return
            return ; Окончание секции авто-выполнения. Скрипт ожидает каких-нибудь действий пользователя.
            Gui, Destroy
           }
        if neu = fno   
            IfNotEqual, strFolder,
                IfNotExist, %strParentFolder%\%strFolder%
                {
                    FileCreateDir, %strParentFolder%\%strFolder%
                    ;MsgBox Была создана папка [%strFolder%] в [%strParentFolder%].
                }
        IfEqual, strFolder,
            {
             Random, strFolder, 0, 2147483647 
             IfNotExist, %strParentFolder%\%strFolder%
                    {
                          FileCreateDir, %strParentFolder%\%strFolder%
                          ;MsgBox Была создана папка [%strFolder%] в [%strParentFolder%].
                    }
            }        
    }
}
return
; ========== КОНЕЦ ПРОГРАММЫ СОДАНИЯ ПАПОК С ЗАВИСЯЩИМ ОТ НАСТРОЕК ПОЛЬЗОВАТЕЛЯ ИМЕНЕМ ===================

;++++++++++++метка выполнения действий выполняемых при нажатии кнопки ОК в окне запроса имени папки++++++++++++++++
ButtonOK:
         Gui, Submit ; Сохраняем входные данные пользователя в ассоциированной переменной каждого элемента управления.
         Gui, Destroy ;уничтожаем созданное нами окно, чтобы в дальнейшем мы смогли заново его перестроить
             IfNotExist, %strParentFolder%\%strFolder%
                {
                      FileCreateDir, %strParentFolder%\%strFolder%
                }    
         okk=1                
;+++++++++++++конец метки .... клавиши ок..++++++++++++++++++
;++++++++++++метка выполнения действий выполняемых при нажатии кнопки Cencel в окне запроса имени папки++++++++++++++++
ButtonCencel:
         if okk&lt;&gt;1
         {
          Gui, Submit ; Сохраняем входные данные пользователя в ассоциированной переменной каждого элемента управления.
          Gui, Destroy ;уничтожаем созданное нами окно, чтобы в дальнейшем мы смогли заново его перестроить
         }
return
;+++++++++++++конец метки .... клавиши Cencel..++++++++++++++++++
GuiClose:
GuiEscape:
          Gui, Submit ; Сохраняем входные данные пользователя в ассоциированной переменной каждого элемента управления.
          Gui, Destroy ;уничтожаем созданное нами окно, чтобы в дальнейшем мы смогли заново его перестроить</code></pre></div><p>Автор скрипта - <strong>Resager</strong>, использованы идеи <strong>alexii</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-09-03T14:18:54Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=13760#p13760</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=13318#p13318" />
			<content type="html"><![CDATA[<p>Вариант предыдущего скрипта, добавляет к имени создаваемой папки (&quot;newdir&quot;) случайную комбинацию цифр. Это позволяет в текущем каталоге создавать не одну папку, а неограниченное их количество подряд. Если вам нужен значок в трее, уберите первую строчку скрипта.<br /></p><div class="codebox"><pre><code>#NoTrayIcon 
F7::
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
Random, rann, 0, 2147483647 
isedit = % InStr(A_LoopField, &quot;Edit&quot;)
    if (isedit &lt;&gt; 0)
    {
    ControlGetText, OutputVar , %A_LoopField%, A
        IfExist, %OutputVar%
        {
            FileCreateDir, %OutputVar%\newdir%rann%
        }
    }
}
return</code></pre></div><p>Автор примера - <strong>Resager</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-08-16T17:32:23Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=13318#p13318</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[AutoHotkey: создание новой папки в Проводнике по горячей клавише]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=5834#p5834" />
			<content type="html"><![CDATA[<p>По нажатию F7 скрипт ищет в активном окне элемент управления, в имени которого есть &quot;Edit&quot; и проверяет, существует ли такой путь. Если путь существует, в нём создаётся папка. Не понимает специальные папки вроде &quot;Мои документы&quot; и т.п. Работает в Проводнике, ACDSee, Блокноте и т.д.<br /></p><div class="codebox"><pre><code>F7::
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
isedit = % InStr(A_LoopField, &quot;Edit&quot;)
    if (isedit &lt;&gt; 0)
    {
    ControlGetText, OutputVar , %A_LoopField%, A
        IfExist, %OutputVar%
        {
            FileCreateDir, %OutputVar%\newdir
        }
    }
}
return</code></pre></div><p>Автор примера - <strong>dw</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2007-11-03T09:16:13Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=5834#p5834</id>
		</entry>
</feed>
