1 (изменено: DD, 2013-02-02 09:41:08)

Тема: AHK: Коллекция скриптов для комфортной работы в одном

Здравствуйте!
   Ревниво хочу предложить прописавшийся в моей автозагрузке скрипт. Немало здесь надёрганного, но есть также вещи "совершенно оригинальные".

|-------------------------------------------------------------------------------------------------
|         КЛАВИШИ                      АКТИВЕН                           ЭФФЕКТ
|------------------------------------------------------------------------------------------------
|  Средняя кнопка мыши                                       закрыть окно, удерживаемая - меню
|-------------------------------------------------------------------------------------------------
|  Левая + Правая мышь       Проводники,IExplorer,Справка,               вперед
|  Правая + Левая мышь       Mozilla,Opera,AvantBrowser                  назад
|-------------------------------------------------------------------------------------------------
|          F1                          Opera                     Сохранить как HTML-файл
|          F2                         Opera                Сохранить как HTML-файл с избражениями
|                                                              в папка-со-скриптом\Web_Save
|-------------------------------------------------------------------------------------------------
|     Правая мышь +         IExplorer,Справка,AvantBrowser,               Поиск
|  Средняя кнопка мыши        MSOfficeWord,RegEdit,Opera
|-------------------------------------------------------------------------------------------------
|  Alt + Буква диска                   Трей                  Копирование дисков (в скрытую папку
|  (ADEFGHIJKLMN)                                                папка-со-скриптом\Pack\)
|-------------------------------------------------------------------------------------------------
|  Ctrl + Буква диска                  Трей                  Копирование по расширению(стоит txt)
|-------------------------------------------------------------------------------------------------
|     Alt + Escape                     Трей                          Остановка копирования
|------------------------------------------------------------------------------------------------
|   etc. Основные - в Справке (в трее).

   Будьте внимательны с горячими клавишами, ибо можно обжечься.

   (Форум не поддерживает сообщений больше 64-х kb, поэтому желающим его пользовать придется объединить в один ahk три нижеследующих кода).

;

my_folder = %A_ScriptDir%\Web_Save


;----------/1myTips=====================================================
CoordMode,Mouse,Screen
;ToolTipOptions:="B0000FF F00FF00 t200 I1 M1"
ToolTipOptions:="t240 I1 M1"
;----------1myTips/=====================================================


;!!Копирование/перемещение <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
;---------------------- USER CONFIGURATION SECTION STARTS --------------------
; CONFIG: CHOOSE DIRECTORY TO HOLD SHORTCUTS
; Set the following variable to the folder name to hold all your shortcuts.
; It will be created if it does not exist. The suggested place is
; %HOMEPATH%\My Documents\Favorites for easy access from other apps.
reference_to = ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
f_quick_fldr = #Quick#
f_system_fldr = #System#
f_shortcuts_folder = %A_ScriptDir%\Favorites
QuickRunMenu = %f_shortcuts_folder%\QMenu.ini
f_myquick_folder = %A_ScriptDir%\Favorites\%f_quick_fldr%
f_mysystem_folder = %A_ScriptDir%\Favorites\%f_system_fldr%
f_quicklnk = %A_ScriptDir%\Favorites\%f_quick_fldr%\*.lnk
f_systemlnk = %A_ScriptDir%\Favorites\%f_system_fldr%\*.lnk

; CONFIG: CHOOSE RELOADING
; Set the following variable to 'y' to always reload the menu and 'n' to
; disable automatic reloading. Keep this 'y' unless you have a really
; long list, because it harldy takes any time to load. But if you
; don't change your list very often, then you may want to keep it 'n'.
; Enter y or n
f_AlwaysReload = y

; CONFIG: CHOOSE WHEN TO SHOW THE MENU
; Setting the following variable to 'n' tells the script to avoid showing
; the menu for unsupported window types.
; Setting the following variable to 'y' tells the script to always
; display the menu; and upon selecting a favorite while an unsupported
; window type is active, the default action will be performed on the
; selected shortcut.   Enter y or n
f_AlwaysShowMenu = y

; CONFIG: CHOOSE YOUR HOTKEYS
; If your mouse has more than 3 buttons, you could try using
; XButton1 (the 4th) or XButton2 (the 5th) instead of MButton.
; You could also use a modified mouse button (such as ^MButton) or
; a keyboard hotkey.  In the case of MButton, the tilde (~) prefix
; is used so that MButton's normal functionality is not lost when
; you click in other window types, such as a browser.
f_Hotkey1 = ^+vk44 ; Control+Shift+d   [~MButton]

;Also define a keyboard shortcut to the menu
;f_Hotkey2 = ^+vk44 ; Control+Shift+d

;Also define a keyboard shortcut to the menu
f_CopyHotkey = !vkBD  ;  ^+vk43 ; Control+Shift+c
f_MoveHotkey = !vkBD  ;  ^+vk4D ; Control+Shift+m
f_QuickCopyHotkey = !vk39 ; Alt+(
f_QuickMoveHotkey = !vk30 ; Alt+)

;-------------------- END OF CONFIGURATION SECTION ------------------------
; Do not make changes below this point unless you want to change
; the basic functionality of the script.

;#NoTrayIcon
;#SingleInstance Force  ; Needed since the Hotkey is dynamically created.

Hotkey, %f_Hotkey1%, f_DisplayMenuForNavigation
;Hotkey, %f_Hotkey2%, f_DisplayMenuForNavigation
Hotkey, %f_CopyHotkey%, f_DisplayMenuForCopy
Hotkey, %f_MoveHotkey%, f_DisplayMenuForMove
Hotkey, %f_QuickCopyHotkey%, f_DisplayMenuForQuickCopy
Hotkey, %f_QuickMoveHotkey%, f_DisplayMenuForQuickMove

; global set to either Navigation=1, Copy=2, Move=3
CommandMode = 1
;GlobalFileList = ""

; Check if %f_shortcuts_folder% exists, if not - create
FileGetAttrib, attrib, %f_shortcuts_folder%\%f_quick_fldr%
FileGetAttrib, attrib, %f_shortcuts_folder%\%f_system_fldr%
IfNotInString, attrib, D
  {
    FileCreateDir, %f_shortcuts_folder%\%f_quick_fldr%
    FileCreateDir, %f_shortcuts_folder%\%f_system_fldr%
    If ErrorLevel
        MsgBox, The folder %f_shortcuts_folder%\%f_quick_fldr% could not be created
    . `nCheck that the 'f_shortcuts_folder' variable in the Config Section of the script is a valid path to a writable folder
    . `nCannot save Favorites links.
  }

IfNotExist, %f_quicklnk%
  {
    FileCreateShortcut %A_DESKTOP%, %f_myquick_folder%\Рабочий стол.lnk
  }

IfNotExist, %f_systemlnk%
  {
    FileCreateShortcut %A_DESKTOP%, %f_mysystem_folder%\Рабочий стол.lnk
  }


f_NotFirstTime =
;Return

;!!Копирование/перемещение >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>




;######################################################################################
;############################ /QuickRun_Group #########################################
;######################################################################################
;##
;##
 menucount:=0       ;количество меню. впринципе можно вместо неё юзать LV_GetCount()
 menutarget =       ;массив назначений
 menuicon =         ;массив адресов иконок
 menuname =         ;массив имён
 menuiconn =        ;массив номеров иконок (для DLL и EXE)
 xmenu:=100     
 ymenu:=100
 rownumb:=0         ;в этой переменной всегда отображается элемент на котором установлен фокус
 menutransp=220     ;прозрачность меню по умолчанию. если в файле её не найдёт, то будет такой
 menucolor=333333   ;цвет меню по умолчанию
 menucolor2=AAAAAA  ;цвет текста по умолчанию
 menucolor3=000000  ;цвет границы по умолчанию

;=============== загрузка ============= 
IfExist, %QuickRunMenu%                                   ;открываем файл с настройками
   FileRead, Contents, %QuickRunMenu%
Loop, parse, Contents, `n
{
   if(A_Index<5)                                                  ;если это настройки цвета\прозрачности
   {
       menustr:=SubStr(A_LoopField,InStr(A_LoopField,"=")+1)      ;вырезаем числа из строчек
       menustr:=SubStr(menustr,1,InStr(menustr,"!")-1)
       if A_Index = 1
       {
          if(Strlen(menustr)<4)
          {
              menutransp:=menustr
              continue
          }
       }
       if A_Index = 2
       {
          if(Strlen(menustr)=6)
          {
              menucolor:=menustr
              continue
          }
       }
       if A_Index = 3
       {
          if(Strlen(menustr)=6)
          {
              menucolor2:=menustr
              continue
          }
       }
       if A_Index = 4
       {
          if(Strlen(menustr)=6)
          {
              menucolor3:=menustr
              continue
          }
       }
   }
   if A_LoopField!=                                            ;загрузка элементов меню
   {
         filestring:=SubStr(A_LoopField,InStr(A_LoopField,"*")+1)
         filestring:=SubStr(filestring,1,InStr(filestring,"!")-1)
                 menuiconn%menucount% = %filestring%
         filest:=SubStr(A_LoopField,1,InStr(A_LoopField,"*")-1)

         filestring:=SubStr(filest,InStr(filest,";")+1)
                 menuicon%menucount% = %filestring%
         filest:=SubStr(filest,1,InStr(filest,";")-1)

         filestring:=SubStr(filest,InStr(filest,"|")+1)
                 menutarget%menucount% = %filestring%
         filest:=SubStr(filest,1,InStr(filest,"|")-1)

         menuname%menucount% = %filest%
         ;MsgBox % menuname%menucount% . "`n" . menutarget%menucount% . "`n" . menuicon%menucount% . "`n" . menuiconn%menucount%
         menucount++
   }
}
filest =
filestring =
Contents =
OnExit, MenuExit   ;выход
;##
;##
;######################################################################################
;################################## QuickRun_Group/ ###################################
;######################################################################################





FileGetAttrib, attrib, %my_folder%
IfNotInString, attrib, D
  {
    FileCreateDir, %my_folder%
    If ErrorLevel
        MsgBox, The folder %my_folder% could not be created.
  }

IfExist %A_ScriptDir%\fshk.ico
  IconFile = %A_ScriptDir%\fshk.ico
Menu, Tray, Tip , Фишки

#Persistent
#SingleInstance Force
DetectHiddenWindows, on
#NoEnv
#MaxMem 1
#KeyHistory 0
SetWinDelay 10
SetKeyDelay, 1      ;!!было - SetKeyDelay 0 (не работает Convert_Case)
;SendMode Input     ;!!не работает Convert_Case
SetBatchLines, -1        ; Выполнять на максимальной скорости.
Process, Priority,, HIGH ; Установить приоритет процесса скрипта в High (высокий).




;ИЗМЕНИТЬ СИСТЕМНУЮ ГРОМКОСТЬ С ПОМОЩЬЮ ПРАВАЯ КНОПКА+КОЛЕСИКО МЫШИ
;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

;#NoEnv
;#MaxMem 1
;#KeyHistory 0
;SetWinDelay 10
;SetKeyDelay 0

; set these values as desired
volume_indicatorWidth = 18
volume_indicatorHeight = 350

volume_step = 8
volume_displayTime = 2000

c_masterVol = Red
c_waveVol = Blue
c_synthVol = Yellow
c_microphoneVol = Green
c_background = Black

; and set these hotkeys as desired
Hotkey,Volume_Up,vol_masterUp
Hotkey,Volume_Down,vol_masterDown
Hotkey,RButton & WheelUp,vol_masterUp
Hotkey,RButton & WheelDown,vol_masterDown

Hotkey,#WheelUp,vol_microphoneUp
Hotkey,#WheelDown,vol_microphoneDown
Hotkey,#vk4D,vol_microphoneMute  ;m

;#===#===#===#===#===#===#===#===#===#===#===#===#===#===#
SoundSet,15,master ; при запуске уменьшает общую громкость
SoundSet,15,wave
SoundSet,15,synth  ; Synth/Midi
;#===#===#===#===#===#===#===#===#===#===#===#===#===#===#

;ИЗМЕНИТЬ СИСТЕМНУЮ ГРОМКОСТЬ С ПОМОЩЬЮ ПРАВАЯ КНОПКА+КОЛЕСИКО МЫШИ
;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


;********************************************************************************
moveable_title = _MOVEABLE_
SkyNet_Path = E:\SkyNET\ok\jpg\_MOVEABLE_
;********************************************************************************

/*
Menu, Tmbs, Add, Эскизы Имя, eskizy_imya
Menu, Tmbs, Add, •Эскизы Изменен, eskizy_izmenen
Menu, Tmbs, Add, Плитка Имя, plitka_imya
Menu, Tmbs, Add, •Значки Тип, znachki_tip
Menu, Tmbs, Add, Таблица Имя, tablica_imya
Menu, Tmbs, Add
Menu, Tmbs, Add, Размеры, razmery
*/

Menu, Cmds, Add, Вырезать, cut
Menu, Cmds, Add, Выделить всё + Вырезать, selectAllCut
Menu, Cmds, Add, Выделить вниз + Вырезать, selectDownCut
Menu, Cmds, Add
Menu, Cmds, Add, Эскизы страниц, My_Thumbnail_Quality
Menu, Cmds, Add
Menu, Cmds, Add, Переключить скрытые %a_tab%Ctrl+Shift+H, CheckActiveWindow
Menu, Cmds, Add, Переключить системные %a_tab%Ctrl+Shift+HH, Check_SuperHidden
Menu, Cmds, Add, Удалить пустые подпапки %a_tab%Win+Del, f_DeleteEmptyFldrs
Menu, Cmds, Add, Группирование файлов по расширению %a_tab%Ctrl+E, f_ExtGroup
;Menu, Cmds, Add, Переместить ВЫДЕЛЕННЫЕ объекты в папку вида #GroupNN, GroupSelectedFiles
;Menu, Cmds, Add, Перенести объекты ИЗ ВЫДЕЛЕННЫХ папок уровнем выше, UngroupSelectedFoldersFiles
;Menu, Cmds, Add, Переместить все файлы ИЗ ВЫДЕЛЕННЫХ папок в текущую, UngroupSelectedFiles
Menu, Cmds, Add, Переместить все файлы ИЗ ПОДПАПОК в текущую %a_tab%C+S+W+A+g, MvFlsFrmSbdrs
Menu, Cmds, Add, Конвертер регистров %a_tab%Ctrl+Shift+Alt+R, Convert_Case
Menu, Cmds, Add, Поиск-извлечение архивов %a_tab%Ctrl+Shift+Alt+E, Find_Extract_Arch
Menu, Cmds, Add, Изменение атрибутов %a_tab%Ctrl+Shift+Alt+A, Attributizer
Menu, Cmds, Add, Копировать путь к выделенному объекту/объектам %a_tab%Win+Shift+C, f_CopyPath
Menu, Cmds, Add, Найти объект... %a_tab%Win+1, f_FindObject
Menu, Cmds, Add, Открыть содержащую объект папку %a_tab%Win+11, f_OpenObject
Menu, Cmds, Add, Открыть путь %a_tab%Win+Shift+CC, f_OpenClipboardPath
Menu, Cmds, Add, Текущее время, f_CurrentTime
Menu, Cmds, Add, Navigation Menu, f_DisplayMenuForNavigation
Menu, Cmds, Add
Menu, Cmds, Add, Таймер на перезагрузку, restart_timer
Menu, Cmds, Add, Таймер на отключение, shutdown_timer

Menu, Popup, Add, Свернуть, mnmz
Menu, Popup, Add
Menu, Popup, Add, • Home, home
Menu, Popup, Add, • End, end
Menu, Popup, Add
Menu, Popup, Add, Выделить вверх, shifthome
Menu, Popup, Add, Выделить вниз, shiftend
Menu, Popup, Add
Menu, Popup, Add, Обратить выделение, turn
Menu, Popup, Add
Menu, Popup, Add, Команды, :Cmds
Menu, Popup, Add
Menu, Popup, Add, My tray menu, TrayMenuShow
;Menu, Popup, color, 0xFFFFFF

Menu, sub_Tray_Sys, Add, Диски, MyComputer
Menu, sub_Tray_Sys, Add, Документы, MyDocuments
Menu, sub_Tray_Sys, Add, Рабочий стол, desk_Top
Menu, sub_Tray_Sys, Add, Автозагрузка, start_Up
Menu, sub_Tray_Sys, Add, Свойства экрана, Screen
Menu, sub_Tray_Sys, Add, Панель управления, Panel
Menu, sub_Tray_Sys, Add, SendTo, send_To
Menu, sub_Tray_Sys, Add, System, systemFld
Menu, sub_Tray_Sys, Add, System32, system32Fld
Menu, sub_Tray_Sys, Add, Local Settings, Local_Settings
Menu, sub_Tray_Sys, Add, Program Files, ProgramFiles
IfExist, D:\Program Files, Menu, sub_Tray_Sys, Add, D:\Program Files, DProgramFiles
IfExist, E:\Program Files, Menu, sub_Tray_Sys, Add, E:\Program Files, EProgramFiles
IfExist, F:\Program Files, Menu, sub_Tray_Sys, Add, F:\Program Files, FProgramFiles
IfExist, G:\Program Files, Menu, sub_Tray_Sys, Add, G:\Program Files, GProgramFiles
IfExist, H:\Program Files, Menu, sub_Tray_Sys, Add, H:\Program Files, HProgramFiles
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
IfExist, %USERPROFILE%\Local Settings\Application Data\Opera\Opera, Menu, sub_Tray_Sys, Add, AppData\Opera, App_Data_Opera
Menu, sub_Tray_Sys, Add, Центр справки и поддержки, services

Menu, sub_Tray_Prg, Add, Paint, Paint
Menu, sub_Tray_Prg, Add, Звукозапись, Sndrec32
Menu, sub_Tray_Prg, Add, Реестр, Registry
Menu, sub_Tray_Prg, Add, Таблица символов, Char_map
Menu, sub_Tray_Prg, Add, Command Prompt, Command_Prompt
Menu, sub_Tray_Prg, Add, Command Prompt Here, Command_Prompt_Here

   Menu, Tray, Icon, %IconFile%
Menu, Tray, NoStandard
Menu, Tray, Add, &Выключить звук, Vol_Mute

; ================ / Autorun ==============================================
;Поместить запущенный скрипт в автозагрузку (в папку "Автозагрузка" или в реестр в раздел HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run текущего пользователя), или убрать его из автозагрузки. Вариант автозагрузки определяется состоянием строки (закомментируйте):
RegistryMode = Yes ; comment out this line to set Startup Folder mode
AutorunMenuItemName = Автозагрузка
if RegistryMode
    SK = Software\Microsoft\Windows\CurrentVersion\Run ; Registry SubKey name
else
{
    SF = %A_Startup% ; Startup Folder - you may choose A_StartupCommon
    LF = %SF%\%A_ScriptName%.lnk ; LinkFile
}
Menu Tray, Add, %AutorunMenuItemName%, AutorunSetup
AutorunSetup:
    if AutorunInit
    {
        if AutorunOn
        {
            if RegistryMode
                RegDelete HKCU, %SK%, %A_ScriptName%
            else
                FileDelete %LF%
            AutorunOn := ErrorLevel
            if !AutorunOn
                Menu Tray, Uncheck, %AutorunMenuItemName%
        Return
        } ; else
        if RegistryMode
            RegWrite REG_SZ, HKCU, %SK%, %A_ScriptName%, %A_ScriptFullPath%
        else
            FileCreateShortcut %A_ScriptFullPath%, %LF%, %A_ScriptDir%
        AutorunOn := !ErrorLevel
        if AutorunOn
            Menu Tray, Check, %AutorunMenuItemName%
    Return
    }
AutorunInit = Yes
if RegistryMode
    RegRead SPath, HKCU, %SK%, %A_ScriptName%
else
    FileGetShortcut %LF%, SPath
AutorunOn := !ErrorLevel
if AutorunOn
{
    IfNotEqual SPath, A_ScriptFullPath
    { ; update record in case of the script file was moved
        if RegistryMode
            RegWrite, REG_SZ, HKCU, %SK%, %A_ScriptName%, %A_ScriptFullPath%
        else
            FileCreateShortcut %A_ScriptFullPath%, %LF%, %A_ScriptDir%
        AutorunOn := !ErrorLevel
    }
    if AutorunOn
        Menu Tray, Check, %AutorunMenuItemName%
}
; ================ Autorun / ================================================

Menu, Tray, Add, Системные, :sub_Tray_Sys
Menu, Tray, Add, Программы, :sub_Tray_Prg
Menu, Tray, Add, System Info, SysInfo
Menu, Tray, Add
Menu, Tray, Add, Справка, myHelp
;Menu, Tray, Add, Help2, myHelp2
Menu, Tray, Add, Edit Script, EditScript
Menu, Tray, Add, Script Dir, ScriptDir
Menu, Tray, Add, BackUp Script, BackUpScript
Menu, Tray, Add, Reload Script, ReloadMyApp
Menu, Tray, Add, Pause Script, PauseMyApp
Menu, Tray, Add, Выход, ExitMyApp

Menu, TRAY, Default, &Выключить звук
Menu, Tray, Click, 1


;_____________________________________________________________________________
;|                                                                            |
;|                    Контекстно чувствительные клики                         |
;|____________________________________________________________________________|

;1\
SetTitleMatchMode, 2 ; сравнивать с любой частью заголовка окна
GroupAdd, 1Mouse_Group, ahk_class CabinetWClass ; добавляем в мышиную группу окон Проводник
GroupAdd, 1Mouse_Group, ahk_class ExploreWClass ; Проводник
GroupAdd, 1Mouse_Group, Internet Explorer ahk_class IEFrame ; Internet Explorer
GroupAdd, 1Mouse_Group, ahk_class HH Parent ; справку (chm)
GroupAdd, 1Mouse_Group, ahk_class MozillaUIWindowClass ; Mozilla
;1/
;2\
GroupAdd, 2Mouse_Group, Internet Explorer ahk_class IEFrame
GroupAdd, 2Mouse_Group, ahk_class HH Parent
GroupAdd, 2Mouse_Group, ahk_class TfrmAvantBrowser.UnicodeClass ; Avant Browser
;2/
;3\
GroupAdd, 3Mouse_Group, ahk_class CabinetWClass
GroupAdd, 3Mouse_Group, ahk_class ExploreWClass
GroupAdd, 3Mouse_Group, ahk_class Progman
GroupAdd, 3Mouse_Group, ahk_class #32770
;3/

GroupAdd, Dialog, ahk_class #32770

GroupAdd, 1ACDSee, ahk_class QVMainFrame-ACDSEE90
GroupAdd, 1ACDSee, ahk_class AfxFrameOrView70
GroupAdd, 1ACDSee, ahk_class QVMainFrame-ACDSeePro30

;4\
GroupAdd, 4Mouse_Group, ahk_class OpWindow ; Opera
GroupAdd, 4Mouse_Group, ahk_class TfrmAvantBrowser.UnicodeClass
;4/

GroupAdd, QuickRun_Group, ahk_class Progman
GroupAdd, QuickRun_Group, ahk_class AutoHotkeyGUI
GroupAdd, QuickRun_Group, ahk_class Shell_TrayWnd
GroupAdd, QuickRun_Group, ahk_class BaseBar

;1\
#IfWinActive, ahk_group 1Mouse_Group ; делаем наши клавиши активными только в каком-либо окне из нашей группы
~LButton & RButton:: Send, {BROWSER_FORWARD} ; !{Right}"вперед" (здесь есть тильда, поэтому левая мышь не блокируется для других приложений)
RButton & LButton:: Send, {BROWSER_BACK} ; !{Left}"назад" (здесь тильды нет, поэтому правая мышь блокируется)
;$RButton:: Send, {RButton} ; нажимать RButton всегда, кроме тех случаев, когда она используется в горячих клавишах (здесь мы разблокируем правую мышь)
RETURN
;1/
;2\
#IfWinActive, ahk_group 2Mouse_Group
RButton & MButton::
Send, ^{vk46}    ;Ctrl+F
WinWait, ahk_class Internet Explorer_TridentDlgFrame
WinActivate, ahk_class Internet Explorer_TridentDlgFrame
Send, ^{vk56}    ;Ctrl+V
RETURN
;2/





;/ACDSee;ACDSee;ACDSee;ACDSee;ACDSee;ACDSee;ACDSee
#IfWinActive, ahk_group 1ACDSee
RButton & MButton::
  Send, {DEL}
  WinWait, Подтверждение удаления
  Send, {Space}
  Send, {Left}
~LButton & RButton:: Send, {Right}
RButton & LButton:: Send, {Left}
RETURN

RButton & WheelUp::
  Send, {NumpadAdd}
RETURN

RButton & WheelDown::
  Send, {NumpadSub}
RETURN

NumpadEnter::
  Send, {Right}
RETURN

^AppsKey::
Run, %A_ScriptDir%\SmartMover.ahk
RETURN
;ACDSee;ACDSee;ACDSee;ACDSee;ACDSee;ACDSee;ACDSee/

#IfWinActive, DjVu Viewer --
WheelUp:: PostMessage, 0x111, 40110, 0,,,   ; previous
WheelDown:: PostMessage, 0x111, 40109, 0,,, ; next
RETURN





#IfWinActive, ahk_class OpusApp   ;Micr.Word
RButton & MButton::
Send, ^{vk46}    ;Ctrl+F
Sleep, 500
Send, ^{vk56}    ;Ctrl+V
RETURN

#IfWinActive, ahk_class MozillaUIWindowClass
RButton & MButton::
Send, ^{vk46}    ;Ctrl+F
Sleep, 500
Send, ^{vk56}    ;Ctrl+V
RETURN

;3\
#IfWinActive, ahk_group 3Mouse_Group
!vk4D::    ; Alt+M
Run, %A_ScriptDir%\MoveSelectedFls&Drs2.ahk
RETURN
;3/

;4\
#IfWinActive, ahk_group 4Mouse_Group ; делаем наши клавиши активными только в каком-либо окне из нашей группы
~LButton & RButton:: Send, !{Right} ; "вперед" (здесь есть тильда, поэтому левая мышь не блокируется для других приложений)
RButton & LButton:: Send, !{Left} ; "назад" (здесь тильды нет, поэтому правая мышь блокируется)
;$RButton:: Send, {RButton} ; нажимать RButton всегда, кроме тех случаев, когда она используется в горячих клавишах (здесь мы разблокируем правую мышь)
RETURN

RButton & MButton::
Send, ^{vk46}    ;Ctrl+F
WinWait, Поиск
WinActivate, Поиск
Send, ^{vk56}    ;Ctrl+V
RETURN
;4/

#IfWinActive, ahk_class Shell_TrayWnd
MButton:: Send, !{esc}, !{F4}
RETURN

#IfWinActive, ahk_class WinRarWindow
RButton & MButton:: Send, ^{vk48} ; Ctrl+H Одноуровневый вид папок в WinRar
RButton & LButton:: Send, {Backspace}
;$RButton:: Send, {RButton}
RETURN

#IfWinActive, ahk_class MSPaintApp ; Рисунок->Очистить в Paint
RButton & MButton:: PostMessage, 0x111, 37684, 0,,,
;$RButton:: Send, {RButton}
RETURN

#IfWinActive, ahk_class Bred3Class
RButton & MButton:: PostMessage, 0x111, 13001, 0,,, ; Поиск->Найти в Bred
RButton & LButton:: Send, ^{vk48} ; Поиск->Заменить в Bred
;$RButton:: Send, {RButton}
RETURN

#IfWinActive, ahk_class Notepad++
RButton & MButton:: Send, ^{vk46} ; Поиск->Найти в Notepad++
;$RButton:: Send, {RButton}
RETURN

#IfWinActive, ahk_class RegEdit_RegEdit
RButton & MButton::               ; Найти в RegEdit
Send, ^{vk46}    ;Ctrl+F
WinWait, Поиск
WinActivate, Поиск
Send, ^{vk56}    ;Ctrl+V
RETURN

#IfWinActive, ahk_class TTOTAL_CMD
RButton & MButton:: Send, ^{vk42} ; Ctrl+B Показать все файлы без подкаталогов в TC
~LButton & RButton:: Send, !{Right}
RButton & LButton:: Send, !{Left}
;$RButton:: Send, {RButton}
RETURN

#IfWinActive, ahk_group Dialog
RButton & LButton:: Send, {Backspace}
RETURN







;--------------------------- Opera --------------------------
#IfWinActive, ahk_group 4Mouse_Group
;HTML-файл
F1:: SaveAsHTM("Сохранить как", 1, 4) ;q  !vk51
;HTML-файл с изображениями
F2:: SaveAsHTM("Сохранить как", 2, 4) ;s  !vk53
#IfWinActive

;--------------------------- Функции -------------------------
SaveAsHTM(DlgTitle, HTM_line, TrimCount=0, IE=0)
{
    Send, ^{vk53}                    ; Ctrl-S
  WinWait, %DlgTitle%,, 3
  if ErrorLevel
    return

  gosub, f_Open_My_Folder


  Control, Choose, %HTM_line%, ComboBox3
  Loop 30
  {
    ControlGet, Files, List,, SysListView321
    if Files
      Break
  }
  ControlGetText, FileName, Edit1

  StringReplace, FileName, FileName, `\, `-, All
  StringReplace, FileName, FileName, `/, `-, All
  StringReplace, FileName, FileName, `|, `-, All
  StringReplace, FileName, FileName, `*, `-, All
  StringReplace, FileName, FileName, `:, `-, All
  StringReplace, FileName, FileName, `.mht, `.htm, All

  StringTrimRight, BaseName, FileName, %TrimCount%
  Loop
  {
    if not InStr(Files, FileName)
      Break
    else
    {
      FileName:=BaseName . "_" . A_Index+1 . ".htm"
    }
  }
  ControlSetText, Edit1, %FileName%
  Sleep, 100
  ControlSend, Button2, {Enter}
}
RETURN

f_Open_My_Folder:
  IfNotExist, %my_folder%
  {
  tooltip = * Папка не найдена
  gosub, f_Screen_ToolTip
  Exit
  }
  WinGet, f_window_id, ID, A
  WinActivate ahk_id %f_window_id%
  ControlGetText, text, Edit1, ahk_id %f_window_id%
  ControlSetText, Edit1, %my_folder%, ahk_id %f_window_id%
  ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
  Sleep, 100  ; It needs extra time on some dialogs or in some cases.
  ControlSetText, Edit1, %text%, ahk_id %f_window_id%
Return





;Изменить вид папок
#IfWinActive, ahk_group 3Mouse_Group
Menu, Tmbs, Show
RETURN

eskizy_imya:
    PostMessage, 0x111, 28717,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30210,,, ahk_class CabinetWClass
RETURN

eskizy_izmenen:
    PostMessage, 0x111, 28717,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30213,,, ahk_class CabinetWClass
RETURN

tablica_imya:
    PostMessage, 0x111, 28716,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30210,,, ahk_class CabinetWClass
RETURN

plitka_imya:
    PostMessage, 0x111, 28718,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30210,,, ahk_class CabinetWClass
RETURN

znachki_tip:
    PostMessage, 0x111, 28714,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30212,,, ahk_class CabinetWClass
RETURN

razmery:
    PostMessage, 0x111, 28716,,, ahk_class CabinetWClass
    PostMessage, 0x111, 30211,,, ahk_class CabinetWClass
    Sleep 1000
    PostMessage, 0x111, 30236,,, ahk_class CabinetWClass
RETURN
#IfWinActive






;СОЗДАТЬ НОВУЮ ПАПКУ ПРАВАЯ МЫШЬ + БАРАБАН
#IfWinActive, ahk_group 3Mouse_Group
~LButton & MButton::
KeyWait Control
SetKeyDelay, , 50
MouseGetPos, , , , ctrl
ControlGet, sel, List, Count Selected, SysListView321, A
If DllCall("GetDoubleClickTime") > A_TimeSincePriorHotkey
and A_ThisHotkey = A_PriorHotkey
and ctrl = "SysListView321"
and sel = 0
SendEvent, !fwf


IfWinActive, ahk_class Progman
strProcessName := A_DESKTOP
else
ControlGetText, strProcessName, Edit1, ahk_class CabinetWClass
; ========== ПРОГРАММА СОДАНИЯ ПАПОК\
;WinGet, intHWND, ID, A ;Отыскивает уникальный логин указанного окна, логин процесса, название{имя} процесса, или список его управлений. Это может также отыскать список всех окон, соответствующих указанным критериям.
;WinGet, strProcessName, ProcessName, ahk_id %intHWND%

;(здесь, сравнивает две переменные (например var и value), анологично выражению if var = value
;IfEqual, strProcessName, explorer.exe
;{
    IfExist, %strProcessName%
    {
        Loop
        {
            If A_Index = 1
                strFolder = #NewFolder
            Else
                strFolder = #NewFolder(%A_Index%)

            IfNotExist, %strProcessName%\%strFolder%
                Break
        }
            IfNotEqual, strFolder,
                IfNotExist, %strProcessName%\%strFolder%
                {
                    FileCreateDir, %strProcessName%\%strFolder%
                    ;tooltip = * Была создана папка [%strFolder%] в `n[%strProcessName%]
                    ;gosub, f_Screen_ToolTip
                }
    }
;}
RETURN
; ========== ПРОГРАММА СОДАНИЯ ПАПОК/
#IfWinActive



#IfWinActive, ahk_class MediaPlayerClassicW ; K-Lite Codec Pack
Right:: Send, !{PgUp}
Left:: Send, !{PgDn}
~LButton & RButton:: Send, ^{Right}{Space}
RButton & LButton:: Send, ^{Left}
RETURN

#IfWinActive, ahk_class ShImgVw:CPreviewWnd ; Программа просмотра изображений и факсов
RButton & MButton::
  Send, {DEL}
  WinWait, Подтверждение удаления
  Send, {Space}
  Send, {Left}
~LButton & RButton:: Send, {Right}
RButton & LButton:: Send, {Left}
RETURN

^AppsKey::
Run, %A_ScriptDir%\SmartMover.ahk
RETURN

RButton & WheelUp::
  Sleep, 150
  Send, {Left}
RETURN

RButton & WheelDown::
  Sleep, 150
  Send, {Right}
RETURN





;___________________________________________________________________________
;************ Скрипт для группирования/разгруппирования файлов в проводнике.
; Устанавливает две горячие клавиши:
;   Ctrl+G - Переносит выделенные файлы в папку вида GroupNN
;   Ctrl+Shift+G - Переносит ФАЙЛЫ И ПАПКИ из выделенных папок уровнем выше,
;       затем удаляет эти выделенные папки
;   Ctrl+Shift+Alt+G - Переносит все ФАЙЛЫ из выделенных папок уровнем выше,
;       затем удаляет эти выделенные папки

;
; Для корректной работы нужно зайти в Tools -> Folder Options -> View
; и включить Display the full path in the address bar
; и выключить Hide extensions for known file types
;
; (c)2008 by YasonBy
; Исходник свободен, делайте что хотите :)

;#NoEnv
;SendMode Input

; Defines a new group name and Returns full path to it
; Определяет имя новой группы и возвращает полный путь к ней
GetNewGroupName(dir)
{
    loop 100 {
        groupPath = %dir%\#Group%A_Index%
        If !InStr(FileExist(groupPath),"D")
            break
    }
    Return, groupPath
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

;Sets the input focus to the file list
; Устанавливает фокус ввода на список файлов
FocusFolderView() {
    ControlFocus, SysListView321
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Returns the current path from explorer's address bar
; Возвращает путь из адресной строки эксплорера
GetExplorerDirectory() {
    IfWinActive, ahk_class Progman
    path := A_DESKTOP
    else

    IfWinActive, ahk_class #32770
    path := f_GetDialogPath()
    else

    ControlGetText, path, Edit1  ;getting current directory
    Return %path%
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Navigates Explorer into the specified directory
; Переводит эксплорер в указанную папку
SetExplorerDirectory(dir) {
    ControlSetText, Edit1, %dir% ; change directory
    ControlSend, Edit1, {ENTER} ; press Enter
    FocusFolderView()
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Moves the 'source' file or directory into the 'dest' directory
; Перемещает файл или папку source в папку dest
MoveFileOrDir(source, dest) {
    attributes := FileExist(source)
    IfInString, attributes, D
    {
        FileMoveDir, %source%, %dest%, 1
    }
    else
    {
        FileMove, %source%, %dest%
    }
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Moves the selected files to a GroupNN folder
; Переносит выделенные файлы в папку вида GroupNN
GroupSelectedFiles() {
    currentDir := GetExplorerDirectory()

    ClipSaved := ClipboardAll
    clipboard =
    FocusFolderView()

        f_ClipWait_Loop()

/*
    Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
    ClipWait,2

    If !clipboard,
        Return ; nothing selected - nothing to do
*/
    newGroupDir := GetNewGroupName(currentDir)
    FileCreateDir, %newGroupDir%

    Loop, parse, clipboard, `n, `r
    {
        fileName = %A_LoopField%
        MoveFileOrDir(fileName, newGroupDir)
    }
    Clipboard := ClipSaved
    ClipSaved =
    ; Uncomment this, if you want to move into the created group
    ; Раскомментировать, если нужно переходить в только что созданную группу
    ; SetExplorerDirectory(newGroupDir)

    f_RefreshExplorer()
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Moves the FILES AND FOLDERS from selected folders to an upper level, then removes those directories
; Переносит ФАЙЛЫ И ПАПКИ из выделенных папок уровнем выше, затем удаляет эти выделенные папки
UngroupSelectedFoldersFiles() {
    currentDir := GetExplorerDirectory()

    ClipSaved := ClipboardAll
    clipboard =
    FocusFolderView()

        f_ClipWait_Loop()

/*
    Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
    ClipWait,1
*/
    Loop, parse, clipboard, `n, `r
    {
        groupPath = %A_LoopField%

        attributes := FileExist(groupPath)
        IfInString, attributes, D
        {
            Loop, %groupPath%\*.*,1,0
            {
                MoveFileOrDir(A_LoopFileFullPath, currentDir)
            }
            FileRemoveDir, %groupPath%, 0 ;non-recursive
        }
    }
    Clipboard := ClipSaved
    ClipSaved =
    f_RefreshExplorer()
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Moves the all FILES from selected folders to an upper level, then removes those directories
; Переносит все ФАЙЛЫ из выделенных папок уровнем выше, затем удаляет эти выделенные папки
UngroupSelectedFiles() {
    currentDir := GetExplorerDirectory()

    ClipSaved := ClipboardAll
    clipboard =
    FocusFolderView()

        f_ClipWait_Loop()

/*
    Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
    ClipWait,1
*/

    Loop, parse, clipboard, `n, `r
    {
        groupPath = %A_LoopField%

            Loop, %groupPath%\*.*,,1
            {
                MoveFileOrDir(A_LoopFileFullPath, currentDir)
            }
            FileRemoveDir, %groupPath%, 1 ;non-recursive
    }
    Clipboard := ClipSaved
    ClipSaved =
    f_RefreshExplorer()
}
RETURN  ;;;;;;;;;;;;;;;;;;;;;;;;;;;

#IfWinActive, ahk_group 3Mouse_Group
^vk47::                ; ^G
GroupSelectedFiles:
KeyWait Control
 tooltip = * Перенести выделенные файлы в папку вида GroupNN
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
GroupSelectedFiles()
 Sleep, 1400
 tooltip = * OK
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 800
 tooltip
Return

^+vk47::                ; ^+G
UngroupSelectedFoldersFiles:
KeyWait Control
KeyWait Shift
 tooltip = * Перенести ФАЙЛЫ И ПАПКИ из выделенных папок уровнем выше,`nзатем удалить эти выделенные папки
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
UngroupSelectedFoldersFiles()
 Sleep, 1400
 tooltip = * OK
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 800
 tooltip
Return

^+!vk47::                ; ^+!G
UngroupSelectedFiles:
KeyWait Control
KeyWait Shift
KeyWait Alt
 tooltip = * Переместить ВСЕ ФАЙЛЫ из выделенных папок в текущую,`nзатем удалить эти выделенные папки
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
UngroupSelectedFiles()
 Sleep, 1400
 tooltip = * OK
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 800
 tooltip
Return
;#IfWinActive
;******************************

;Группирование файлов по расширению
^vk45::                ; ^E
f_ExtGroup:
   KeyWait Control
   ClipSaved := ClipboardAll
   Clipboard =
   Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
   ClipWait, 1
   If !clipboard,
      Return ; nothing selected - nothing to do
   FileName = %Clipboard%
   Clipboard := ClipSaved
   SplitPath, FileName,, FileDir, FileExt

   FileGetAttrib, Attributes, %FileName% 
   IfInString, Attributes, D 
      { 
         return
      } 
   else 
   IfNotExist, %FileDir%\#%FileExt%\
      FileCreateDir, %FileDir%\#%FileExt%\
   FileMove, %FileDir%\*%FileExt%, %FileDir%\#%FileExt%\
   If ErrorLevel
      {
         tooltip = * ОШИБКА!
         gosub, f_Screen_ToolTip
      }
   else
      {
         tooltip = * Перемещены в подпапку`n[#%FileExt%]
         gosub, f_Screen_ToolTip
      }
return

#IfWinActive ; снимаем контекстную зависимость горячих клавиш







;________________________________________________________________
;************ 1Создать AutoHotkeyScript *************************
1Ahk1Script1Create:
IfWinActive, ahk_class Progman
exp := A_DESKTOP
else
ControlGetText, exp, Edit1, ahk_class CabinetWClass

IfExist, %exp%
{
   Loop
   {
       If A_Index = 1
           ahk_file = AutoHotkey Script.ahk
       Else
           ahk_file = AutoHotkey Script(%A_Index%).ahk

       IfNotExist, %exp%\%ahk_file%
           Break
   }
       IfNotEqual, ahk_file,
           IfNotExist, %exp%\%ahk_file%
           {
               FileAppend,
               (
               ;`n/*`n#NoTrayIcon    ; не отображать иконку скрипта в трее`n#Persistent`n#SingleInstance Force    ; перезагрузить скрипт, если он уже запущен`n#SingleInstance ignore `n#NoEnv  ; запрещаем имена переменных как у переменных окружения (повышаем производительность)`nSendMode Input  ; новый режим высылки без задержки и повышенной надежности`nSetWorkingDir, `%A_ScriptDir`%  ; установить рабочей папкой папку со скриптом (чтобы не сбивалась при запуске "со стороны")`n*/`n#SingleInstance Force`n`n`n%Clipboard%`n`n`n`n`

               ), %exp%\%ahk_file%
               If FileExist("C:\Program Files\Bred3\bred3_2k.exe")
               {
               that="%exp%\%ahk_file%"
               Run, "C:\Program Files\Bred3\bred3_2k.exe" %that%
               WinWait [%ahk_file%]
               WinActivate
               Send, {F5 2}
               }
               else
               {
               that="%exp%\%ahk_file%"
               Run, "C:\WINDOWS\NOTEPAD.EXE" %that%
               }
           }
}
RETURN

;________________________________________________________________
;************ 2Создать AutoHotkeyScript *************************
2Ahk2Script2Create:

   send ^{Insert}
   sleep,200

Loop
{
If A_Index = 1
ahk_file = AutoHotkey Script.ahk
Else
ahk_file = AutoHotkey Script(%A_Index%).ahk

IfNotExist, C:\%ahk_file%
Break
}
IfNotEqual, ahk_file,
IfNotExist, C:\%ahk_file%
{
FileAppend,
(
;`n/*`n#NoTrayIcon    ; не отображать иконку скрипта в трее`n#Persistent`n#SingleInstance Force    ; перезагрузить скрипт, если он уже запущен`n#SingleInstance ignore `n#NoEnv  ; запрещаем имена переменных как у переменных окружения (повышаем производительность)`nSendMode Input  ; новый режим высылки без задержки и повышенной надежности`nSetWorkingDir, `%A_ScriptDir`%  ; установить рабочей папкой папку со скриптом (чтобы не сбивалась при запуске "со стороны")`n*/`n#SingleInstance Force`n`n`n%Clipboard%`n`n`n`n`

), C:\%ahk_file%
If FileExist("C:\Program Files\Bred3\bred3_2k.exe")
{
that="C:\%ahk_file%"
Run, "C:\Program Files\Bred3\bred3_2k.exe" %that%
WinWait [%ahk_file%]
WinActivate
Send, {F5 2}
}
else
{
that="C:\%ahk_file%"
Run, "C:\WINDOWS\NOTEPAD.EXE" %that%
}
} 
RETURN

AhkCommands:
SplitPath, A_AhkPath,, A_AhkDir
FileRead, Commands, %A_AhkDir%\Extras\Editors\Syntax\Commands.txt
StringReplace, Commands, Commands, |, \, All
StringReplace, Commands, Commands, `r, , All
StringReplace, Commands, Commands, `n,| , All
Gui, 38:Add, ComboBox, w640 R45 Simple AltSubmit vSelected, %commands%
Gui, 38:Show,, %A_AhkDir%\Extras\Editors\Syntax\Commands.txt
Return

38guiClose:
gui, 38:Destroy
Return







;__________________________________________________________________________________
;##################################################################################
;############################ /QuickRun_Group #####################################
;##################################################################################
;##
;#IfWinActive, ahk_group QuickRun_Group
~LButton & RButton::
{
    CoordMode, Mouse, Screen
    MouseGetPos, xmenu, ymenu, win
    WinGetClass, class, ahk_id %win%
    If class in Progman,AutoHotkeyGUI,BaseBar,Shell_TrayWnd

    ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
    ^+RButton:: ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
    ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;

    {
        DetectHiddenWindows, On
        ifWinExist, MyMenu                                  ;меню создано
        {
             DetectHiddenWindows, Off
             ifWinExist, MyMenu
                    WinHide, MyMenu
              else
                {
                    DetectHiddenWindows, On

                    loopindex:=((menucount+1)*17)+4        ;чтоб за границы экрана не вылезло
                    if (xmenu>(A_ScreenWidth-154))
                        xmenu:=xmenu-154
                    if (ymenu>(A_ScreenHeight-loopindex))
                        ymenu:=ymenu-loopindex
                    Gui, 30: Show, x%xmenu% y%ymenu%, MyMenu

                    WinShow, MyMenu
                    WinActivate, MyMenu
                    Gui, 30: Default                       ;нужно для того чтобы функции при работе с ListView знали к какому именно ListView обращаться

                       Loop % LV_GetCount()                ;снимаем фокус со всех эелементов
                         LV_Modify(A_Index, "-Select")
                }
        }
        else                                               ;создаём меню
        {
                    Gui, 30: Default
                    Gui, 30: -Resize +LastFound +AlwaysOnTop +ToolWindow -Caption
                    Gui, 30: Color, %menucolor3%
                    WinSet, TransColor, %menucolor% %menutransp%
                    Gui, 30: Font, S8 c%menucolor2%, Tahoma
                    loopindex:=menucount+2
                    Gui, 30: Add, ListView , x2 y2 r%loopindex% w150 -ReadOnly -Border vMyListView -LV0x8000 -LV0x10 +LV0x40 +LV0x8 -Hdr AltSubmit gMyListView Background%menucolor%,  name

                    ImageListID1 := IL_Create(10)         ;ImageListID1 - хранилище иконок
                    LV_SetImageList(ImageListID1)         ;Связываем ListView с хранилищем иконок
                    ;=======================
                    GuiControl, -Redraw, MyListView       ;отменяем перерисовку
                    Loop %menucount%                      ;этот цикл заполняет наш ListView       
                    { 
                        loopindex:=A_Index-1
                        IL_Add(ImageListID1,menuicon%loopindex%,menuiconn%loopindex%)
                        LV_Add("Icon" . A_Index, menuname%loopindex%)
                    }
                    GuiControl, +Redraw, MyListView
                    
                    ;==========Вычисляем новую длину меню=============
                    loopindex:=((menucount+1)*16)+8
                    LV_ModifyCol(2,"105")
                    GuiControl, Move, MyListView, % "H" . (menucount+1)*17

                    loopindex:="H" . ((menucount+1)*17)+4

                    loopindex:=((menucount+1)*17)+4
                    if (xmenu>(A_ScreenWidth-154)){
                    xmenu:=xmenu-154
                    }
                    if (ymenu>(A_ScreenHeight-loopindex)){
                    ymenu:=ymenu-loopindex
                    }

                    Gui, 30: Show, x%xmenu% y%ymenu% w154 h%loopindex%, MyMenu
                     Loop % LV_GetCount()
                        LV_Modify(A_Index, "-Select")
                    
                    WinSet Transparent, %menutransp%, A  ;устанавливаем прозрачность меню (читается из файла)
        }
        DetectHiddenWindows, Off
    }
    Else
        MouseClick, Middle

    MyListView:                                          ;обрабока событий ListView
    {
        if A_GuiEvent = Normal                           ;выбран элемент меню
        {
            LV_GetText(OutputVar, A_EventInfo, 1)        ;по идее это спасёт при пустом меню
            if OutputVar =
               return
            runtarget:=A_EventInfo-1
            runname:=menuname%runtarget%
            runtarget:=menutarget%runtarget%

        ;GetKeyState, State, Ctrl
        ;IfEqual, State, D
        GetKeyState, RButtonState, RButton, P            ;если кликнули,
        If RButtonState = D                              ;зажав правую кнопку мыши
        {
            Run, Explorer /select`,"%runtarget%",, UseErrorLevel
            WinHide, MyMenu
        }
        else

            Run, %runtarget%                             ;запускаем то что выбрано
            WinHide, MyMenu                              ;это закомментируйте если не нужно 
                                                         ;чтобы меню закрывалось при выборе элемента
 ;=================================================================================
 
            ToolTip Runing %runname%...
            SetTimer, RemoveToolTip, 700
        }
        else if A_GuiEvent = I                          ;фокус элемента сменился, и мы за ним следим
            rownumb:=A_EventInfo
        else if A_GuiEvent = K                          ;нажата какая-то клавиша
        {
            Gui, 30: Default
            if(A_EventInfo=46)                      ;видимо это клавиша Delete :-)
            {
               KeyWait, Delete
               rownumb--
               loopindex:=menucount-rownumb

               Loop %loopindex%                     ;делаем Delete из всех массивов со смещением элементов
               {
                   rownumb2:=A_index + rownumb - 1
                   loopindex:=rownumb2+1
                   menutarget%rownumb2% := menutarget%loopindex%
                   menuicon%rownumb2% := menuicon%loopindex%
                   menuname%rownumb2% := menuname%loopindex%
                   menuiconn%rownumb2% := menuiconn%loopindex%
               }
                IL_Destroy(ImageListID1)           ;к сожалению ImageListID не поддерживает удаления элементов
                ImageListID1 := IL_Create(10)      ;поэтому пришлось его вальнуть и пересоздать
                LV_SetImageList(ImageListID1)
                LV_Delete()                        ;тоже самое и про ListView, хотя у него есть функция удаления отдельных элементов
                ;=======================
                menucount--
                Loop %menucount%                   ;снова заполняем ListView
                {
                    loopindex:=A_Index-1
                    IL_Add(ImageListID1,menuicon%loopindex%,menuiconn%loopindex%)
                    LV_Add("Icon" . A_Index, menuname%loopindex%)
                }
                
               ;===================Вычисляем длину меню=================
               LV_ModifyCol(2,"105")
               GuiControl, Move, MyListView, % "H" . (menucount+1)*17

               Gui 30: Show, % "H" . ((menucount+1)*17)+4
               Loop % LV_GetCount()
                   LV_Modify(A_Index, "-Select")
            }
        }        
        return
    }


30GuiDropFiles:                                   ;думаю понятно что это
{
    GuiControl, -Redraw, MyListView               ;не будем его тревожить в реальном времени
    Gui, 30: Default
    Loop, parse, A_GuiEvent, `n
    {
        SplitPath, A_LoopField,,, FileExt
        if FileExt = lnk                          ;если мы туда кинули ссылку
        {
             Source =
             FileGetShortcut, %A_LoopField%, Target, Dir, Args, Desc, Ico, IconNum, RunState
             Source:=SubStr(A_LoopField,InStr(A_LoopField,"\",0,0)+1)
             Source:=SubStr(Source,1,InStr(Source,".")-1)
             ;MsgBox %A_LoopField%`nTarget: %Target%`nDir: %Dir%`nArgs: %Args%`nDesc: %Desc%`nIcon: %Icon%`nIconNum: %IconNum%`nRunState: %RunState%
             if Ico =
                Ico:=Target
             menutarget%menucount% = %Target%
             menuicon%menucount% = %Ico%
             menuname%menucount% = %Source%
             menuiconn%menucount% = %IconNum%

             menucount++

             IL_Add(ImageListID1,Ico,%IconNum%)
             LV_Add("Icon" . menucount, Source)
        }
        else if FileExt = exe                    ;если мы туда кинули EXE
        {
             SplitPath, A_LoopField,,,, Source
             menutarget%menucount% = %A_LoopField%
             menuicon%menucount% = %A_LoopField%
             menuname%menucount% = %Source%
             menuiconn%menucount% = 1

             menucount++

             IL_Add(ImageListID1,A_LoopField,1)
             LV_Add("Icon" . menucount, Source)
        }
        else if FileExt =                        ;если забросили папку
        {
             SplitPath, A_LoopField,,,, Source

             menutarget%menucount% = %A_LoopField%
             EnvGet, SystemRoot, SystemRoot  ;получаем значение переменной окружения
             menuicon%menucount% = %SystemRoot%\system32\shell32.dll
             menuname%menucount% = %Source%
             menuiconn%menucount% = 20

             menucount++

             ;IL_Add(ImageListID1,"C:\WINDOWS\Explorer.exe",14) ;у меня значёк папки лежит тута. у вас - не знаю)
             EnvGet, SystemRoot, SystemRoot  ;получаем значение переменной окружения
             IL_Add(ImageListID1,"%SystemRoot%\system32\shell32.dll",20)
             LV_Add("Icon" . menucount, Source)
        }
        else if FileExt = %FileExt%              ;кинули другое
        {
             SplitPath, A_LoopField,,,, Source

             menutarget%menucount% = %A_LoopField%
             menuicon%menucount% = C:\WINDOWS\system32\SHELL32.dll
             menuname%menucount% = %Source%
             menuiconn%menucount% = 1

             menucount++

             IL_Add(ImageListID1,"C:\WINDOWS\system32\SHELL32.dll",1)
             LV_Add("Icon" . menucount, Source)
        }
    }
    ;===================Вычисляем длину меню=================
     LV_ModifyCol(2,"105")
     GuiControl, Move, MyListView, % "H" . (menucount+1)*17
     GuiControl, +Redraw, MyListView

     Gui 30: Show, % "H" . ((menucount+1)*17)+4
      Loop % LV_GetCount()
        LV_Modify(A_Index, "-Select")
    return
} 
}

MenuExit:                                 ;Выходим из скрипта
{
   filestring =
    Loop, %menucount%                     ;делаем одну большую колбасу из массивов
    {
         loopindex:=A_Index-1
         filestring:=filestring . menuname%loopindex% . "|" . menutarget%loopindex% . ";" . menuicon%loopindex% . "*" . menuiconn%loopindex% . "!`n"
    }
    FileDelete, %QuickRunMenu%            ;удаляем файл
    FileAppend, transp=%menutransp%!`nmenu color=%menucolor%!`ntext color=%menucolor2%!`nborder color=%menucolor3%!`n, %QuickRunMenu%    ;пишем настройки
    FileAppend, %filestring%, %QuickRunMenu%                                                                                             ;пишем элементы
   filestring =
   ExitApp
}
;##
;#####################################################################################
;################################## QuickRun_Group/ ##################################
;#####################################################################################






;_____________________________________________________________________________
;|                                                                            |
;|                                   Команды 1                                |
;|____________________________________________________________________________|

;$MButton::
MButton::
KeyWait, %A_ThisHotkey%, U T.4 ; ожидать отжатия клавиши 0,5 секунды
If ErrorLevel = 0 ; если отжата

  Send, !{F4}
  ;WinClose, A

Else ; если не отжата
  {

Menu, Popup, Show
RETURN

  }
RETURN




mnmz:
  WinMinimize A
RETURN

home:
  Send, ^{Home}
RETURN

end:
  Send, ^{End}
RETURN

shifthome:
  Send, ^+{Home}
RETURN

shiftend:
  Send, ^+{End}
RETURN

turn:
  PostMessage, 0x111, 28706, 0, , ahk_class CabinetWClass  ;Обратить выделение
RETURN

#!Space::
Run, %A_ScriptDir%\OpenLibrary.exe
RETURN

^+!vkC0:: ; ^+!`
EnvGet, SystemRoot, SystemRoot ; получаем значение переменной окружения
Run, %SystemRoot%\system\exview.exe
RETURN









;__________________________________________________________
;##########################################################
;######## /клавиши, зависящие от количества нажатий #######
;##########################################################

#+vk43::   ;Win+Shift+C
^+vk48::   ;Ctrl+Shift+H
#DEL::     ;Win+DEL
^+!vk52::  ;Ctrl+Shift+Alt+R
#1::       ;Win+1
#9::       ;Win+9
+#vk54::   ;Shift+Win+T
#7::       ;Win+7

   ++counter
   SetTimer, Choice, -400
   return

Choice:

      if A_ThisHotkey = #+vk43    ;Win+Shift+C
   {
      IfEqual, counter, 1, Gosub, f_CopyPath
      IfEqual, counter, 2, Gosub, f_OpenClipboardPath
      ;IfGreater, counter, 2, Run %A_AppData%
   }
      if A_ThisHotkey = ^+vk48    ;Ctrl+Shift+H
   {
      IfEqual, counter, 1, Gosub, CheckActiveWindow
      IfEqual, counter, 2, Gosub, Check_SuperHidden
   }
      if A_ThisHotkey = #DEL      ;Win+DEL
   {
      IfEqual, counter, 1, Gosub, f_DeleteEmptyFldrs
      IfEqual, counter, 2, Gosub, EmptyRecycle
   }
      if A_ThisHotkey = ^+!vk52   ;Ctrl+Shift+Alt+R
   {
      IfEqual, counter, 1, Gosub, Convert_Case
      IfEqual, counter, 2, Gosub, RecodeTextENRU
   }
      if A_ThisHotkey = #1
   {
      IfEqual, counter, 1, Gosub, f_FindObject
      IfEqual, counter, 2, Gosub, f_OpenObject
   }
      if A_ThisHotkey = #9
   {
      IfEqual, counter, 1, Gosub, f_GetExePath
      IfEqual, counter, 2, Gosub, f_GetClass
   }
      if A_ThisHotkey = +#vk54    ;Shift+Win+T
   {
      IfEqual, counter, 1, Gosub, TextTransliterate
      IfEqual, counter, 2, Gosub, TextDeTransliterate
   }
      if A_ThisHotkey = #7    ;Shift+Win+T
   {
      IfEqual, counter, 1, Gosub, 1Ahk1Script1Create
      IfEqual, counter, 2, Gosub, 2Ahk2Script2Create
      IfEqual, counter, 3, Gosub, AhkCommands
   }
   counter =
   return

;##########################################################
;######## клавиши, зависящие от количества нажатий/ #######
;##########################################################












;_____________________________________________________________________________
;|                                                                            |
;|                                   Команды 2                                |
;|____________________________________________________________________________|

cut:
   PostMessage, 0x111, 28696, 0, , ahk_class CabinetWClass
RETURN

selectAllCut:
  PostMessage, 0x111, 28705, 0, , ahk_class CabinetWClass
  PostMessage, 0x111, 28696, 0, , ahk_class CabinetWClass
RETURN

selectDownCut:
  Send, ^+{End}
  Sleep, 1000
  PostMessage, 0x111, 28696, 0, , ahk_class CabinetWClass
  Sleep, 1000
  Send, ^{Home}
RETURN

DProgramFiles:
Run, D:\Program Files
RETURN

EProgramFiles:
Run, E:\Program Files
RETURN

FProgramFiles:
Run, F:\Program Files
RETURN

GProgramFiles:
Run, G:\Program Files
RETURN

HProgramFiles:
Run, H:\Program Files
RETURN

App_Data_Opera:
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
Run, %USERPROFILE%\Local Settings\Application Data\Opera\Opera
RETURN

ProgramFiles:
Run, %ProgramFiles%
RETURN

systemFld:
EnvGet, SystemRoot, SystemRoot ; получаем значение переменной окружения
Run, %SystemRoot%\system
RETURN

system32Fld:
EnvGet, SystemRoot, SystemRoot ; получаем значение переменной окружения
Run, %SystemRoot%\system32
RETURN

start_Up:
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
Run, %USERPROFILE%\Главное меню\Программы\Автозагрузка
RETURN

desk_Top:
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
Run, %USERPROFILE%\Рабочий стол
RETURN

send_To:
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
Run, %USERPROFILE%\SendTo
RETURN

Local_Settings:
EnvGet, USERPROFILE, USERPROFILE ; получаем значение переменной окружения
Run, %USERPROFILE%\Local Settings
RETURN

services:
Run, "hcp://services/layout/contentonly"
RETURN

Paint:
EnvGet, SystemRoot, SystemRoot ; получаем значение переменной окружения
Run, %SystemRoot%\system32\mspaint.exe
RETURN

Sndrec32:
EnvGet, SystemRoot, SystemRoot ; получаем значение переменной окружения
Run, %SystemRoot%\system32\sndrec32.exe
RETURN

Command_Prompt:
Run, cmd.exe
RETURN

Command_Prompt_Here:
Run, cmd.exe /k cd /D %F_CurrentDir%
RETURN

Registry:
Run, regedit.exe
RETURN

Char_map:
Run, charmap.exe
RETURN

ScriptDir:
 Run, Explorer /select`,"%A_ScriptFullPath%",, UseErrorLevel
RETURN



;показать/скрыть скрытые файлы
;^+vk48::   ;H
CheckActiveWindow:
f_ToggleHidden()

/*
ID := WinExist("A")
WinGetClass,Class, ahk_id %ID%
WClasses := "CabinetWClass ExploreWClass"
IfInString, WClasses, %Class%
GoSub, Toggle_HiddenFiles_Display
RETURN
Toggle_HiddenFiles_Display:
RootKey = HKEY_CURRENT_USER
SubKey = Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
RegRead, HiddenFiles_Status, % RootKey, % SubKey, Hidden
if HiddenFiles_Status = 2
RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 1
else
RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 2
PostMessage, 0x111, 28931,,, ahk_id %ID%    ;Обновить
*/
RETURN

;показать/скрыть защищенные системные файлы
;^+!vk48::   ; ^+!H
Check_SuperHidden:
f_ToggleSuperHidden()

/*
ID := WinExist("A")
WinGetClass,Class, ahk_id %ID%
WClasses := "CabinetWClass ExploreWClass"
IfInString, WClasses, %Class%
GoSub, Toggle_SuperHiddenFiles_Display
RETURN
Toggle_SuperHiddenFiles_Display:
RootKey = HKEY_CURRENT_USER
SubKey = Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
RegRead, SuperHiddenFiles_Status, % RootKey, % SubKey, ShowSuperHidden
if SuperHiddenFiles_Status = 1
RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 0
else
RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 1
PostMessage, 0x111, 28931,,, ahk_id %ID%    ;Обновить
*/
RETURN


;Копировать путь к выделенному объекту/объектам
;#+vk43::  ;Win+Shift+C
f_CopyPath:
clipboard =
Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
ClipWait, 2
Sort, clipboard
tooltip = * Копировать путь к выделенному объекту/объектам
gosub, f_Screen_ToolTip
RETURN

; Открыть/закрыть лоток CD-ROM - Alt+Ctrl+Win+Space
!^#Space::
    Drive, Eject
    If A_TimeSinceThisHotkey < 1000
        Drive, Eject, , 1
Return

2 (изменено: DD, 2009-11-14 20:09:06)

Re: AHK: Коллекция скриптов для комфортной работы в одном

; ...изменить СИСТЕМНУЮ ГРОМКОСТЬ С ПОМОЩЬЮ ПРАВАЯ КНОПКА+КОЛЕСО МЫШИ
;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
vol_masterUp:
   SoundSet,+%volume_step%,master
   SoundSet,+%volume_step%,wave
   SoundSet,+%volume_step%,synth      ; Synth/Midi
   Gosub,volumeBarOn
RETURN
vol_masterDown:
   SoundSet,-%volume_step%,master
   SoundSet,-%volume_step%,wave
   SoundSet,-%volume_step%,synth      ; Synth/Midi
   Gosub,volumeBarOn
RETURN
vol_waveUp:
   SoundSet,+%volume_step%,wave
   Gosub,volumeBarOn
RETURN
vol_waveDown:
   SoundSet,-%volume_step%,wave
   Gosub,volumeBarOn
RETURN
vol_synthUp:
   SoundSet,+%vol_Step%,Synth      ; Synth/Midi
   Gosub,volumeBarOn
RETURN
vol_synthDown:
   SoundSet,-%vol_Step%,Synth      ; Synth/Midi
   Gosub,volumeBarOn
RETURN
vol_microphoneUp:
   SoundSet,+%volume_step%,microphone
   Gosub,volumeBarOn
RETURN
vol_microphoneDown:
   SoundSet,-%volume_step%,microphone
   Gosub,volumeBarOn
RETURN

vol_masterMute:
   SoundSet,-1,master,mute  ; values starting with +/- toggle mute
   Gosub,volumeBarOn
RETURN
vol_waveMute:
   SoundSet,-1,wave,mute
   Gosub,volumeBarOn
RETURN
vol_synthMute:
   SoundSet,-1,synth,mute
   Gosub,volumeBarOn
RETURN
vol_microphoneMute:
   SoundSet,-1,microphone,mute
   Gosub,volumeBarOn
RETURN


volumeBarOn:
IfWinExist, volume
{
   SoundGet,vol,master
   GuiControl,1:,progress_masterVol,%vol%

   SoundGet,mute,master,mute
   mute := mute = "On" ? 0 : 1
   GuiControl,1:,progress_masterMute,%mute%

   SoundGet,vol,wave
   GuiControl,1:,progress_waveVol,%vol%

   SoundGet,mute,wave,mute
   mute := mute = "On" ? 0 : 1
   GuiControl,1:,progress_waveMute,%mute%

   SoundGet,vol,synth
   GuiControl,1:,progress_synthVol,%vol%

   SoundGet,mute,synth,mute
   mute := mute = "On" ? 0 : 1
   GuiControl,1:,progress_synthMute,%mute%

   SoundGet,vol,microphone
   GuiControl,1:,progress_microphoneVol,%vol%

   SoundGet,mute,microphone,mute
   mute := mute = "On" ? 0 : 1
   GuiControl,1:,progress_microphoneMute,%mute%

SetTimer,volumeBarOff, 2000
Return
}
Gosub, show
Return

show:
SoundGet, master_volume

IfWinNotExist, volume
{
Gui,+AlwaysOnTop -Caption -Resize +ToolWindow +Disabled -SysMenu +Owner
Gui,Margin,0,0
Gui,+LastFound
WinSet, TransColor, 0  130

; add vertical progress bars
SoundGet,vol,master
Gui,1:Add,Progress,Vertical C%c_masterVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorHeight% Vprogress_masterVol X0 Y0,%vol%

SoundGet,mute,master,mute
mute := mute = "On" ? 0 : 1
Gui,1:Add,Progress,Vertical C%c_masterVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorWidth% Vprogress_masterMute X0 Range0-1,%mute%

SoundGet,vol,wave
Gui,1:Add,Progress,Vertical C%c_waveVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorHeight% Vprogress_waveVol Y0,%vol%

SoundGet,mute,wave,mute
mute := mute = "On" ? 0 : 1
Gui,1:Add,Progress,Vertical C%c_waveVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorWidth% Vprogress_waveMute Y+0 Range0-1,%mute%

SoundGet,vol,synth
Gui,1:Add,Progress,Vertical C%c_synthVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorHeight% Vprogress_synthVol X+0 Y0,%vol%

SoundGet,mute,synth,mute
mute := mute = "On" ? 0 : 1
Gui,1:Add,Progress,Vertical C%c_synthVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorWidth% Vprogress_synthMute Y+0 Range0-1,%mute%

SoundGet,vol,microphone
Gui,1:Add,Progress,Vertical C%c_microphoneVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorHeight% Vprogress_microphoneVol X+0 Y0,%vol%

SoundGet,mute,microphone,mute
mute := mute = "On" ? 0 : 1
Gui,1:Add,Progress,Vertical C%c_microphoneVol% Background%c_background% W%volume_indicatorWidth% H%volume_indicatorWidth% Vprogress_microphoneMute Y+0 Range0-1,%mute%


; calc gui window position - lower right corner of usable screen area (on monitor 1)
SysGet,mWorkArea,MonitorWorkArea
vol_x := (A_ScreenWidth  - 4*volume_indicatorWidth)
vol_y := (mWorkAreaBottom - volume_indicatorHeight - volume_indicatorWidth)

   ; find pos of taskbar (have to do it each time in case user has autohide on)
   WinGetPos,,tb_Y,,,ahk_class Shell_TrayWnd
   if (tb_Y > 0)
   {
      tb_Y := vol_y - (mWorkAreaBottom - tb_Y)
      Gui,1:Show,X%vol_x% Y%tb_Y% NoActivate, volume
   }
   else
      Gui,1:Show,X%vol_x% Y%vol_y% NoActivate
   SetTimer,volumeBarOff,%volume_displayTime%, volume
}
SetTimer,volumeBarOff, 2000
Return

volumeBarOff:
SetTimer,volumeBarOff, off
Gui, destroy
Return
;изменить СИСТЕМНУЮ ГРОМКОСТЬ С ПОМОЩЬЮ ПРАВАЯ КНОПКА+КОЛЕСО МЫШИ.
;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>





Vol_Mute:
SoundSet, +1,, mute
;   SoundSet,-1,master,mute
;   SoundSet,-1,wave,mute
;   SoundSet,-1,synth,mute

Menu, TRAY, Icon, %A_ScriptDir%\fshk.ico,0
SoundGet, Master_mute,, mute
   if Master_mute=On
   Menu, TRAY, Icon, %A_ScriptDir%\fshk_mute.ico,0
RETURN


TrayMenuShow:
Menu, Tray, Show
RETURN







$RButton:: Send, {RButton}

f_CurrentTime:
Clipboard  = %A_Hour%:%A_Min%:%A_Sec% - %A_DD%.%A_MM%.%A_YYYY%
Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
RETURN

;Ставим таймер на отключение/перезагрузку компьютера
restart_timer:
InputBox, minutes ,Sleeptimer, Введите минуты до перезагрузки:,,200,140
if ErrorLevel
exit
else
Sleep, (minutes*60*1000)
Shutdown, 2
RETURN
shutdown_timer:
InputBox, minutes ,Sleeptimer, Введите минуты до отключения:,,200,140
if ErrorLevel
exit
else
Sleep, (minutes*60*1000)
Shutdown, 8
RETURN

MyComputer:
Run ::{20d04fe0-3aea-1069-a2d8-08002b30309d}   ;Мой компьютер
RETURN

MyDocuments:
Run ::{450d8fba-ad25-11d0-98a8-0800361b1103}   ;Мои документы
RETURN

Screen:
Run, desk.cpl   ;Свойства Экрана
RETURN

Panel:
Run rundll32.exe shell32.dll`,Control_RunDLL   ;Панель управления
RETURN

ReloadMyApp:
Reload   ;restart the script
RETURN

PauseMyApp:
suspend
pause
RETURN

ExitMyApp:
ExitApp
RETURN

EditScript:
If FileExist("C:\Program Files\Notepad++\notepad++.exe")
{
Run, "C:\Program Files\Notepad++\notepad++.exe" %A_ScriptFullPath%
}
else If FileExist("C:\Program Files\Bred3\bred3_2k.exe")
{
Run, "C:\Program Files\Bred3\bred3_2k.exe" %A_ScriptFullPath%
}
else
{
Run, Notepad %A_ScriptFullPath%
}
RETURN

BackUpScript:
SplitPath, A_ScriptName,,,, name_no_ext, 
BackUpFolder=%A_ScriptDir%\%name_no_ext%_Backup\
  ifNotExist, %BackUpFolder%
    FileCreateDir,%BackUpFolder%
FormatTime,TimeStamp,,[yy-MM-dd] @ [H.mm.ss]
BackupFileName=%BackUpFolder%%TimeStamp% - %A_ScriptName%
FileCopy,%A_ScriptFullPath%,%BackupFileName%
RETURN

;^+!vk52::                ; ^+!R
RButton & MButton::
EmptyRecycle:
  FileRecycleEmpty
  clipboard =
If FileExist("C:\Program Files\CCleaner\ccleaner.exe")
{
  Run, "C:\Program Files\CCleaner\ccleaner.exe" /AUTO ;, useerrorlevel
}
RETURN



;==================== Get Win Class ====================;
;#9::
f_GetClass:
WinGetTitle, w_Title, A   ; Get title
WinGetClass, w_Class, A   ; Get class
ControlGetPos, w_Edit1Pos,,,, Edit1, A   ; Get edit1
if w_Edit1Pos =   ; edit1 not exist
{
   MsgBox, 49, Folder Menu, Title:`t[%w_Title%]`nClass:`t[%w_Class%]`n`nEdit1 did NOT exist!`n`nCopy the classname?
   IfMsgBox OK
      Clipboard = %w_Class%`n%w_Title%
}
else
{
   MsgBox, 33, Folder Menu, Title:`t[%w_Title%]`nClass:`t[%w_Class%]`n`nEdit1 exist!`n`nCopy the classname?
   IfMsgBox OK
      Clipboard = %w_Class%`n%w_Title%
}
RETURN


;==================== Get Exe Path ====================;
f_GetExePath:
WinGet, PID, PID, % "ahk_id " WinExist("A")
   GetExePath := GetModuleFileNameEx( PID )

   IfWinExist, ahk_id %ID8%
     Goto, 8GuiClose
   Gui, 8:+LastFound +AlwaysOnTop +Caption -minimizebox
   WinGet, ID8
   WinSet, Transparent, 0

Gui, 8:Add, Edit, yp+10, %GetExePath%
Gui, 8:Add, Button, default, Explore
Gui, 8:Show,, ModuleFileName
   Melt(ID8, 255, 1)
return

GetModuleFileNameEx(PID) { ; shimanov - www.autohotkey.com/forum/viewtopic.php?p=54838#54838
   hpr := DllCall( "OpenProcess", UInt,1040, Int,0, UInt,PID )
   If ( errorLevel or !hpr )
      Return
   VarSetCapacity( Name,255 )
   DllCall( "psapi.dll\GetModuleFileNameExA", UInt,hPr, UInt,0, Str,Name, UInt,255 )
   DllCall( "CloseHandle", hPr )
   Return, Name
}

8GuiClose:
   Melt(ID8, 255, 0)
Gui, 8:Destroy
return

8ButtonExplore:
   Melt(ID8, 255, 0)
Gui, 8:Destroy
   Run, Explorer /select`,"%GetExePath%",, UseErrorLevel
return


;_____________________________________________________________________________
;|                                                                            |
;|                            Размер/Качество эскизов                         |
;|____________________________________________________________________________|

My_Thumbnail_Size:
gosub My_Thumbnail_Quality
RETURN

My_Thumbnail_Quality:
gosub Thumbnail_Size
gosub Thumbnail_Quality

ThumbnailSizeText =
(
Может принимать значения от 32 до 255`n(по умолчанию равно 96).
)
ThumbnailQualityText =
(
Может принимать значение от 50 до 100 `n(по умолчанию равно 90).
)

  IfWinExist, ahk_id %ID3%
    Goto, 3GuiClose
  Gui, 3:+LastFound +AlwaysOnTop +Caption -minimizebox
  WinGet, ID3
  WinSet, Transparent, 0

  ;Gui, 3:Color, ffffff
  Gui, 3:Font, s8, Tahoma

  Gui, 3:Add,GroupBox, x18 y18 w253 h105 , Размер эскизов
  Gui, 3:Add,Text, xs+25 ys+20 , %ThumbnailSizeText%
  Gui, 3:Add,Text, xs+40 ys+60 , Size (pixels):
  Gui, 3:Add,Edit, xs+120 ys+60 vThumbnail_Size gThumbnail_Size Right Number Limit3 r1 w50,
       Thumbnail_Size_TT := "см.: 75,96,110,121,127,150,180,221,255"
  Gui, 3:Add,UpDown, Range32-255, %Thumbnail_Size%

  Gui, 3:Add,GroupBox, x18 y2 w253 h105 ys+115 , Качество эскизов
  Gui, 3:Add,Text, xs+25 ys+135 , %ThumbnailQualityText%
  Gui, 3:Add,Text, xs+40 ys+175 , Low
  Gui, 3:Add,Text, xs+193 ys+175 , High
  Gui, 3:Add,Slider, xs+65 ys+172 Buddy1Txt1SldJpgQ Buddy2Txt2SldJpgQ AltSubmit Range50-100 ToolTipBottom vThumbnail_Quality gThumbnail_Quality,  %Thumbnail_Quality%

  Gui, 3:Add,Button, x64 y255 w70 H24 Default, Apply
  Gui, 3:Add,Button, x154 y255 w70 H24 , Cancel
  Gui, 3:Show,h301 w290 ,Размер/Качество эскизов
  Melt(ID3, 255, 1)
       OnMessage(0x200, "WM_MOUSEMOVE")
RETURN

Thumbnail_Size:
      RegRead, Thumbnail_Size, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer, ThumbnailSize
RETURN

Thumbnail_Quality:
      RegRead, Thumbnail_Quality, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer, ThumbnailQuality
RETURN

3ButtonApply:
  Melt(ID3, 255, 0)
  gui, 3:submit, nohide
  gui, 3:destroy

RegWrite, REG_DWORD, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer, ThumbnailSize, %Thumbnail_Size% ;00000060
RegWrite, REG_DWORD, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Explorer, ThumbnailQuality, %Thumbnail_Quality% ;00000064
RETURN

3GuiClose:
  Melt(ID3, 255, 0)
  gui, 3:destroy
  RETURN

3ButtonCancel:
  Melt(ID3, 255, 0)
  gui, 3:destroy
  RETURN

;_____________________________________________________________________________
;|                                                                            |
;|                      Удалить все пустые подпапки                           |
;|____________________________________________________________________________|

;#DEL::
f_DeleteEmptyFldrs:
;=*=*=*=*=*=*=*=*=*=*=*=*=
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
isedit = % InStr(A_LoopField, "Edit")
    if (isedit <> 0)
    {
    ControlGetText, OutputVar , %A_LoopField%, A
        IfExist, %OutputVar%
        {
;=*=*=*=*=*=*=*=*=*=*=*=*=
 tooltip = * Удалить все пустые подпапки
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 1000
gosub, DelEmptyFolders
DelEmptyFolders:
DelEmpty( OutputVar ) ; вызываем функцию удаления пустых подпапок (см. строку ниже)
DelEmpty( dir ) ; функция удаления пустых подпапок
{
    BatchLines_Before := A_BatchLines ; запоминаем текущие настройки скорости выполнения скрипта
    SetBatchLines, -1 ; устанавливаем max скорость для скрипта
    Global OutputVar ; объявляем переменную глобальной (чтобы использовать внутри функции)
    Loop %dir%\*.*, 2 ; обрабатываем текущую папку и ее подпапки
        DelEmpty( A_LoopFileFullPath ) ; берем первую же папку и вызываем из функции саму себя, чтобы дойти до самой нижней подпапки
    If dir != %OutputVar% ; если текущая папка НЕ папка для сохранений, то...
        FileRemoveDir, %dir% ; удаляем её, если она пуста
    SetBatchLines, %BatchLines_Before% ; восстанавливаем скорость скрипта
}
 tooltip = * OK
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 1000
 tooltip
    ;ExitApp
RETURN
;=*=*=*=*=*=*=*=*=*=*=*=*=
        }
    }
}
RETURN
;=*=*=*=*=*=*=*=*=*=*=*=*=

;_____________________________________________________________________________
;|                                                                            |
;|               Переместить все файлы из подкаталогов в текущий              |
;|____________________________________________________________________________|

^+#!vk47::                ; ^+#!G
MvFlsFrmSbdrs:
;=*=*=*=*=*=*=*=*=*=*=*=*=
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
isedit = % InStr(A_LoopField, "Edit")
    if (isedit <> 0)
    {
    ControlGetText, OutputVar , %A_LoopField%, A
        IfExist, %OutputVar%
        {
;=*=*=*=*=*=*=*=*=*=*=*=*=
            MsgBox, 4, Подтверждение, Переместить ВСЕ ФАЙЛЫ из подкаталогов в текущий?
            IfMsgBox, Yes
            {
gosub, MoveFilesFromSubdirs
            }
            IfMsgBox, No
            {
            RETURN
            }
MoveFilesFromSubdirs:
; Перемещаем все файлы из подкаталогов в %OutputVar%
MoveFlsFromSubfld( OutputVar ) ; вызываем функцию перемещения (см. строку ниже)
MoveFlsFromSubfld( dir ) ; функция перемещения
{
    if DoOverwrite = 1
        DoOverwrite = 2 ; Различие режимов 2 и 1 см. в описании FileMoveDir.
    BatchLines_Before := A_BatchLines ; запоминаем текущие настройки скорости выполнения скрипта
    SetBatchLines, -1 ; устанавливаем max скорость для скрипта
    Global OutputVar ; объявляем переменную глобальной (чтобы использовать внутри функции)
        FileGetTime ModTime,   %dir%, M           ; Изменен
        FileGetTime CreateTime,%dir%, C           ; Создан
    Loop %dir%\*.*, 1 ; обрабатываем текущую папку и ее подпапки
        MoveFlsFromSubfld( A_LoopFileFullPath ) ; берем первую же папку и вызываем из функции саму себя, чтобы дойти до самой нижней подпапки
        FileMove, %dir%, %OutputVar%, %DoOverwrite%
        if ErrorLevel ; Сообщать о каждом проблемном файле.
            MsgBox, 64, , Не удалось переместить `"%A_LoopFileFullPath%`"`nСоздан:  %CreateTime%`nИзменен: %ModTime%, 1
        ;FileRemoveDir, %dir% ; удаляем подпапки
    SetBatchLines, %BatchLines_Before% ; восстанавливаем скорость скрипта
}
    SoundBeep, 2200,20
;    ExitApp
RETURN

;=*=*=*=*=*=*=*=*=*=*=*=*=
        }
    }
}
RETURN
;=*=*=*=*=*=*=*=*=*=*=*=*=

;_____________________________________________________________________________
;|                                                                            |
;|                    Скрытие и отображение активного окна                    |
;|____________________________________________________________________________|

DetectHiddenWindows, on ;включаем поиск в скрытых окнах
!1:: ; Alt+1 - горячая клавиша

If 1Win_To_Hide_ID = ;если значение переменной  пусто (т.е. окно еще не скрывалось)
    {
        WinGet, 1Win_To_Hide_ID, ID, A ; сохранить ID скрываемого окна в переменной
        WinHide, ahk_id %1Win_To_Hide_ID% ; скрыть окно
    }
else ;если же окно уже скрыто, то выполняем:
    {
        WinShow, ahk_id %1Win_To_Hide_ID% ; восстановить скрытое окно с запомненным ID
        WinActivate, ahk_id %1Win_To_Hide_ID% ; активизировать его
        1Win_To_Hide_ID = ;обнуляем значение переменной, чтобы можно было снова скрывать окно
    }
RETURN ; закончить обработку горячей клавиши

!2:: ; Alt+2 - горячая клавиша
If 2Win_To_Hide_ID =
    {
        WinGet, 2Win_To_Hide_ID, ID, A
        WinHide, ahk_id %2Win_To_Hide_ID%
    }
else
    {
        WinShow, ahk_id %2Win_To_Hide_ID%
        WinActivate, ahk_id %2Win_To_Hide_ID%
        2Win_To_Hide_ID =
    }
RETURN

!3:: ; Alt+3 - горячая клавиша
If 3Win_To_Hide_ID =
    {
        WinGet, 3Win_To_Hide_ID, ID, A
        WinHide, ahk_id %3Win_To_Hide_ID%
    }
else
    {
        WinShow, ahk_id %3Win_To_Hide_ID%
        WinActivate, ahk_id %3Win_To_Hide_ID%
        3Win_To_Hide_ID =
    }
RETURN

;_____________________________________________________________________________
;|                                                                            |
;|                              Поиск архивов                                 |
;|____________________________________________________________________________|

^+!vk45::                ; ^+!E
Find_Extract_Arch:
;=*=*=*=*=*=*=*=*=*=*=*=*=
WinGet, ActiveControlList, ControlList, A
Loop, Parse, ActiveControlList, `n
{
isedit = % InStr(A_LoopField, "Edit")
    if (isedit <> 0)
    {
    ControlGetText, OutputVar , %A_LoopField%, A
        IfExist, %OutputVar%
        {
;=*=*=*=*=*=*=*=*=*=*=*=*=
    tooltip = * EXTRACT...
    CoordMode, ToolTip, Screen
    ToolTip, %tooltip%,0,0
    RunWait, "C:\Program Files\WinRAR\WinRAR.exe" x -ad "%OutputVar%\*.*" "%OutputVar%\#ARCHIVES\",, Hide
;    SoundBeep, 2200,20
    Sleep, 2000
    tooltip = * OK
    CoordMode, ToolTip, Screen
    ToolTip, %tooltip%,0,0
    Sleep, 1000
    tooltip
;=*=*=*=*=*=*=*=*=*=*=*=*=
        }
    }
}
RETURN
;=*=*=*=*=*=*=*=*=*=*=*=*=



; ========== ОТКРЫТЬ TASK MENAGER ==================
^~LButton::  ; Ctrl+LButton - только при нажатии на Task Bar-e и
             ; на панели инструментов окна эксплорера
;-----------------------------------------------------------------------------
  WinGetClass, Win_Class, A
  MouseGetPos,,,, control
  if (Win_Class = "Shell_TrayWnd" and control = "Button1" or control =  "ToolbarWindow323" or control = "ToolbarWindow322") ; если клик на панели задач и при этом на кнопке пуск или на панели быстрого запуска (Quick Launch) или на панелью задач отображающей запущенные приложения, то...
  {
    KeyWait, LButton
    ;KeyWait, Ctrl
    Run, "%A_WinDir%\system32\taskmgr.exe" ; запустить Таск Менеджер
  }
Return
;-----------------------------------------------------------------------------



; ========== ЗАСТАВКА/ВЫКЛЮЧЕНИЕ МОНИТОРА ==================
#PgUp:: ; WIN+PgUp - заставка (ДВОЙНОЕ нажатие - выключение монитора)
;-----------------------------------------------------------------------------
    If Count_Presses > 0 ; если таймер уже запущен
    {
        Count_Presses += 1 ; плюсуем каждое нажатие клавиши (число будет обрабатываться в подпрограмме соответствующего таймера)
        Return ; закончить обработку горячей клавиши (ее дальнейшую обработку уже определяет таймер и его подпрограмма)
    }
    ; Иначе - это первое нажатие из новой серии
    Count_Presses = 1 ; выставляем флаг, что клавиша один раз нажата
    SetTimer, Timer_Presses_5, 400 ; переходить к указанной подпрограмме через каждые 400 миллисекунд
Return ; закончить обработку горячей клавиши

Timer_Presses_5: ; подпрограмма действий в зависимости от количества нажатий
    SetTimer, Timer_Presses_5, Off ; выключить таймер
    If Count_Presses = 1 ; если клавиша нажата однажды...

        SendMessage, 0x112, 0xF140, 0,, Program Manager ; запустить скринсейвер (0x112 is WM_SYSCOMMAND, and 0xF140 is SC_SCREENSAVE)

    Else If Count_Presses = 2 ; если клавиша нажата дважды...
    {

        CoordMode, Mouse, Screen ; установить абсолютные координаты для мыши
        MouseGetPos, XStart, YStart ; получить начальные координаты мыши
        Loop ; начать цикл с выключением монитора
        {
            Sleep, 200 ; пауза, чтобы не обрабатывалась вызывающая клавиша
            SendMessage, 0x112, 0xF170, 1,, Program Manager ; активизировать режим "малой мощности" монитора (0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER)
            ; Используйте 2, чтобы выключить монитор
            ; Используйте -1 вместо 2, чтобы включить монитор
            ; Используйте 1 вместо 2, чтобы активизировать режим "малой мощности" монитора
            Sleep, 200 ; пауза, чтобы не молотить лишнего
            MouseGetPos, XCurrent, YCurrent ; получить текущие координаты мыши
            If ( XCurrent <> XStart ) ; если мышь передвинута
                Break ; закончить цикл с выключением монитора
        }

    }
    Count_Presses = ; сбросить счет и подготовится к следующему ряду нажатий
Return ; закончить обработку горячей клавиши
;-----------------------------------------------------------------------------


; ________________________________________________________________
; ========== НАЗНАЧИТЬ/СНЯТЬ ОКНО - ПОВЕРХ ВСЕХ ==================
#sc01E:: ; WIN+A (английская) - окно "поверх всех" (ДВОЙНОЕ нажатие - снять "поверх всех")
;-----------------------------------------------------------------------------
    If Count_Presses > 0 ; если таймер уже запущен, то...
    {
        Count_Presses += 1 ; плюсуем каждое нажатие клавиши (число будет обрабатываться в подпрограмме соответствующего таймера)
        Return ; закончить обработку горячей клавиши (ее дальнейшую обработку уже определяет таймер и его подпрограмма)
    }
    ; Иначе - это первое нажатие из новой серии
    Count_Presses = 1 ; выставляем флаг, что клавиша один раз нажата
    SetTimer, Timer_Presses_2, 300 ; переходить к указанной подпрограмме через каждые 300 миллисекунд
Return ; закончить обработку горячей клавиши

Timer_Presses_2: ; подпрограмма действий в зависимости от количества нажатий
    SetTimer, Timer_Presses_2, off ; выключить таймер
    If Count_Presses = 1 ; если клавиша нажата однажды...
    {
        ; ОБРАБОТАТЬ ОКНО WINAMP
        WinGetClass, Win_Class, A ; получить класс активного окна
        If Win_Class = BaseWindow_RootWnd ; если класс окна - Winamp
        {
            PostMessage, 0x111, 40019,,, ahk_class Winamp v1.x ; окно - поверх всех
            Goto, LabelEXIT2 ; ==> перейти к окончанию обработки
        } ; если окно не Winamp, то...
        WinGet, Win_ID, ID, A ; получить ID активного окна
        WinSet, AlwaysOnTop, ON, ahk_id %Win_ID% ; окно - поверх всех
    }
    Else If Count_Presses = 2 ; если клавиша нажата дважды...
    {
        ; ОБРАБОТАТЬ ОКНО WINAMP
        WinGetClass, Win_Class, A ; получить класс активного окна
        If Win_Class = BaseWindow_RootWnd ; если класс окна - Winamp
            PostMessage, 0x111, 40019,,, ahk_class Winamp v1.x ; снять "поверх всех"
        WinGet, Win_ID, ID, A ; получить ID активного окна
        WinSet, AlwaysOnTop, OFF, ahk_id %Win_ID% ; снять "поверх всех"
    }
    LabelEXIT2:
    Count_Presses = 0 ; сбросить счет и подготовится к следующему ряду нажатий
Return ; закончить обработку горячей клавиши
;-----------------------------------------------------------------------------


; __________________________________________________
; ========== Easy Window Dragging ==================
; ========== Перемещение окон за любое место внутри окна ==================
; Вы можете отпустить клавишу WIN после нажатия левой кнопки, вместо того, чтобы удерживать ее
; И вы можете во время перемещения нажать Escape, чтобы отменить перемещение
#LButton::              ; WIN+Левая мышь
CoordMode, Mouse ; переключиться на абсолютные координаты экрана
MouseGetPos, EWD_MouseStartX, EWD_MouseStartY, EWD_MouseWin ; получить начальную позицию мыши и ID окна под мышью
WinGetClass, EWD_Win_Class, ahk_id %EWD_MouseWin% ; получаем класс окна под мышью
If EWD_Win_Class = ProgMan ; если это рабочий стол, то...
    Return ; закончить обработку горячей клавиши
WinGetPos, EWD_OriginalPosX, EWD_OriginalPosY,,, ahk_id %EWD_MouseWin% ; запоминаем исходные координаты окна
SetTimer, EWD_WatchMouse, 10 ; переходить к указанной подпрограмме через каждые 10 мс
Return ; закончить обработку горячей клавиши

EWD_WatchMouse: ; подпрограмма обработки событий в таймере
GetKeyState, EWD_LButtonState, LButton, P ; проверить нажата ли левая кнопка мыши
If EWD_LButtonState = U ; если кнопка отпущена, то закончить перемещение окна...
{
    SetTimer, EWD_WatchMouse, off ; отключить таймер
    Return ; конец подпрограммы, закончить обработку горячей клавиши
}
GetKeyState, EWD_EscapeState, Escape, P ; проверить нажата ли клавиша Escape
If EWD_EscapeState = D ; если нажата, то отменить перемещение окна (вернуть его в начальные координаты)
{
    SetTimer, EWD_WatchMouse, off ; отключить таймер
    WinMove, ahk_id %EWD_MouseWin%,, %EWD_OriginalPosX%, %EWD_OriginalPosY% ; вернуть окно в начальные координаты
    Return ; конец подпрограммы, закончить обработку горячей клавиши
}
; ...если кнопка нажата, то перемешать окно вслед за перемещением указателя мыши
CoordMode, Mouse ; переключиться на абсолютные координаты экрана
MouseGetPos, EWD_MouseX, EWD_MouseY ; получить текущие координаты мыши
WinGetPos, EWD_WinX, EWD_WinY,,, ahk_id %EWD_MouseWin% ; получить позицию окна под мышкой
SetWinDelay, -1 ; перемещать окно немедленно
; переместить окно под мышью вслед за мышью
WinMove, ahk_id %EWD_MouseWin%,, EWD_WinX + EWD_MouseX - EWD_MouseStartX, EWD_WinY + EWD_MouseY - EWD_MouseStartY
EWD_MouseStartX := EWD_MouseX ; обновить X координату для следующего вызова этой подпрограммы по таймеру
EWD_MouseStartY := EWD_MouseY ; обновить Y координату для следующего вызова этой подпрограммы по таймеру
Return ; закончить подпрограмму и обработку горячей клавиши
;-----------------------------------------------------------------------------


;_____________________________________________________________
;====== LWin + RB ======== WINDOW RESIZING ===================
#RButton::
    CoordMode, Mouse, Relative 
    MouseGetPos, inWinX, inWinY, WinId 
    if WinId = 
        return 
    WinGetPos, winX, winY, winW, winH, ahk_id %WinId% 
    halfWinW = %winW% 
    EnvDiv, halfWinW, 2 
    halfWinH = %winH% 
    EnvDiv, halfWinH, 2 
    if inWinX < %halfWinW% 
        MousePosX = left 
    else 
        MousePosX = right 
    if inWinY < %halfWinH% 
        MousePosY = up 
    else 
        MousePosY = down 
    CoordMode, Mouse, Screen 
    MouseGetPos, OLDmouseX, OLDmouseY, WinId 
    SetWinDelay, 0 
    Loop 
    { 
        GetKeyState, state, LWin, P 
        if state = U 
            break 
        GetKeyState, state, RButton, P 
        if state = U 
            break 
        MouseGetPos, newMouseX, newMouseY 
        if newMouseX < %OLDmouseX% 
        { 
            Xdistance = %OLDmouseX% 
            EnvSub, Xdistance, %newMouseX% 
            if MousePosX = left ; mouse is on left side of window 
            { 
                EnvSub, winX, %Xdistance% 
                EnvAdd, winW, %Xdistance% 
            } 
            else 
            { 
                EnvSub, winW, %Xdistance% 
            } 
        } 
        else if newMouseX > %OLDmouseX% 
        { 
            ; mouse was moved to the right 
            Xdistance = %newMouseX% 
            EnvSub, Xdistance, %OLDmouseX%    
            if MousePosX = left ; mouse is on left side of window 
            { 
                EnvSub, winW, %Xdistance% 
                EnvAdd, winX, %Xdistance% 
            } 
            else 
            { 
                EnvAdd, winW, %Xdistance% 
            } 
        } 
        OLDmouseX = %newMouseX% 
        if newMouseY < %OLDmouseY% 
        { 
            Ydistance = %OLDmouseY% 
            EnvSub, Ydistance, %newMouseY%    
            if MousePosY = up ; mouse is on upper side of windows 
            { 
                EnvSub, winY, %Ydistance% 
                EnvAdd, winH, %Ydistance% 
            } 
            else 
            { 
                EnvSub, winH, %Ydistance% 
            } 
        } 
        else if newMouseY > %OLDmouseY% 
        { 
            Ydistance = %newMouseY% 
            EnvSub, Ydistance, %OLDmouseY%    
            if MousePosY = up ; mouse is on upper side of windows 
            { 
                EnvAdd, winY, %Ydistance% 
                EnvSub, winH, %Ydistance% 
            } 
            else 
            { 
                EnvAdd, winH, %Ydistance% 
            } 
        } 
        OLDmouseY = %newMouseY% 
        WinMove, ahk_id %WinID%,,%winX%,%winY%,%winW%,%winH% 
    } 
return
;----------------------------------------------------------------


;________________________________________________________________________________
;################################################################################
;#### Convert text - UPPERCASE, lowercase, capitalized, sentence or inverted ####
;################################################################################

;#4::
Convert_Case:
IfWinExist, ahk_id %ID66%
  Goto, 66GuiClose
Gui, 66:+LastFound +AlwaysOnTop +ToolWindow
WinGet, ID66
WinSet, Transparent, 0

gui, 66:font,, MS sans serif
Gui, 66:Add, Button, x-1 y0 w200 h31 v1Upper gUppercase, ВЕРХНИЙ РЕГИСТР
Gui, 66:Add, Button, x-1 y30 w200 h31 v1Lower gLowercase, нижний регистр
Gui, 66:Add,Button, x-1 y60 w200 h31 v1Title gTitle_Case, Заглавные Буквы
Gui, 66:Add,Button, x-1 y90 w200 h31 v1Toggle gToggle_Case, и`НВЕРСИЯ р`ЕГИСТРА
Gui, 66:Add,Button, x-1 y120 w200 h31 v1Sentence gSentence_Case, Как в предложении
Gui, 66:Show, h151 w198, Конвертер регистров
  Melt(ID66, 255, 1)
;----------/2myTips=====================================================
setTip("ВЕРХНИЙ РЕГИСТР", "Shift+Win+U", 66)
setTip("нижний регистр", "Shift+Win+L", 66)
setTip("Заглавные Буквы", "Shift+Win+K", 66)
setTip("и`НВЕРСИЯ р`ЕГИСТРА", "Shift+Win+I", 66)
setTip("Как в предложении", "Shift+Win+S", 66)
;----------2myTips/=====================================================
  return

+#vk55::                            ;u                         ; Convert text to upper
Uppercase:
gui, 66:destroy
 Clip_Save:= ClipboardAll
 Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
 StringUpper Clipboard, Clipboard
 Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
 Clipboard:= Clip_Save
 RETURN

+#vk4C::                            ;l                         ; Convert text to lower
Lowercase:
gui, 66:destroy
 Clip_Save:= ClipboardAll
 Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
 StringLower Clipboard, Clipboard
 Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
 Clipboard:= Clip_Save
 RETURN

+#vk4B::                               ;k               ; Convert text to capitalized
Title_Case:
gui, 66:destroy
 Clip_Save:= ClipboardAll
 Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
 StringUpper Clipboard, Clipboard, T
 Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
 Clipboard:= Clip_Save
 RETURN

+#vk49::                               ;i                  ; Convert text to inverted
Toggle_Case:
gui, 66:destroy
 Clip_Save:= ClipboardAll
 Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
 Lab_Invert_Char_Out:= ""
 Loop % Strlen(Clipboard) {
    Lab_Invert_Char:= Substr(Clipboard, A_Index, 1)
    if Lab_Invert_Char is upper
       Lab_Invert_Char_Out:= Lab_Invert_Char_Out Chr(Asc(Lab_Invert_Char) + 32)
    else if Lab_Invert_Char is lower
       Lab_Invert_Char_Out:= Lab_Invert_Char_Out Chr(Asc(Lab_Invert_Char) - 32)
    else
       Lab_Invert_Char_Out:= Lab_Invert_Char_Out Lab_Invert_Char
 }
 Clipboard:= Lab_Invert_Char_Out
 Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
 Clipboard:= Clip_Save
 RETURN

+#vk53::                               ;s
Sentence_Case:
gui, 66:destroy
 Clip_Save:= ClipboardAll
 Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
 StringLower, Clipboard, Clipboard
 Clipboard := RegExReplace(Clipboard, "(((^|([.!?]+\s+))[a-z])| i | i')", "$u1")
 Send, {CTRL DOWN}{vk56}{CTRL UP}   ;v
 Clipboard:= Clip_Save
 RETURN

66GuiClose:
 Melt(ID66, 255, 0)
 gui, 66:destroy
 RETURN




;Транслитерация текста
TextTransliterate:
TextTransliterate()
TextTransliterate()
{
   clipSave:=clipAnsi()
   send ^{Insert}
   sleep,50
StringReplace, Clipboard, Clipboard, а , a , All
StringReplace, Clipboard, Clipboard, б , b , All
StringReplace, Clipboard, Clipboard, в , v , All
StringReplace, Clipboard, Clipboard, г , g , All
StringReplace, Clipboard, Clipboard, д , d , All
StringReplace, Clipboard, Clipboard, е , e , All
StringReplace, Clipboard, Clipboard, ё , jo , All
StringReplace, Clipboard, Clipboard, ж , zh , All
StringReplace, Clipboard, Clipboard, з , z , All
StringReplace, Clipboard, Clipboard, и , i , All
StringReplace, Clipboard, Clipboard, й , j , All
StringReplace, Clipboard, Clipboard, к , k , All
StringReplace, Clipboard, Clipboard, л , l , All
StringReplace, Clipboard, Clipboard, м , m , All
StringReplace, Clipboard, Clipboard, н , n , All
StringReplace, Clipboard, Clipboard, о , o , All
StringReplace, Clipboard, Clipboard, п , p , All
StringReplace, Clipboard, Clipboard, р , r , All
StringReplace, Clipboard, Clipboard, с , s , All
StringReplace, Clipboard, Clipboard, т , t , All
StringReplace, Clipboard, Clipboard, у , u , All
StringReplace, Clipboard, Clipboard, ф , f , All
StringReplace, Clipboard, Clipboard, х , h , All
StringReplace, Clipboard, Clipboard, ц , ts , All
StringReplace, Clipboard, Clipboard, ч , ch , All
StringReplace, Clipboard, Clipboard, ш , sh , All
StringReplace, Clipboard, Clipboard, щ , sch , All
StringReplace, Clipboard, Clipboard, ъ , ' , All
StringReplace, Clipboard, Clipboard, ы , y , All
StringReplace, Clipboard, Clipboard, ь , ' , All
StringReplace, Clipboard, Clipboard, э , e , All
StringReplace, Clipboard, Clipboard, ю , ju , All
StringReplace, Clipboard, Clipboard, я , ja , All
StringReplace, Clipboard, Clipboard, А , A , All
StringReplace, Clipboard, Clipboard, Б , B , All
StringReplace, Clipboard, Clipboard, В , V , All
StringReplace, Clipboard, Clipboard, Г , G , All
StringReplace, Clipboard, Clipboard, Д , D , All
StringReplace, Clipboard, Clipboard, Е , E , All
StringReplace, Clipboard, Clipboard, Ё , Jo , All
StringReplace, Clipboard, Clipboard, Ж , Zh , All
StringReplace, Clipboard, Clipboard, З , Z , All
StringReplace, Clipboard, Clipboard, И , I , All
StringReplace, Clipboard, Clipboard, Й , J , All
StringReplace, Clipboard, Clipboard, К , K , All
StringReplace, Clipboard, Clipboard, Л , L , All
StringReplace, Clipboard, Clipboard, М , M , All
StringReplace, Clipboard, Clipboard, Н , N , All
StringReplace, Clipboard, Clipboard, О , O , All
StringReplace, Clipboard, Clipboard, П , P , All
StringReplace, Clipboard, Clipboard, Р , R , All
StringReplace, Clipboard, Clipboard, С , S , All
StringReplace, Clipboard, Clipboard, Т , T , All
StringReplace, Clipboard, Clipboard, У , U , All
StringReplace, Clipboard, Clipboard, Ф , F , All
StringReplace, Clipboard, Clipboard, Х , H , All
StringReplace, Clipboard, Clipboard, Ц , Ts , All
StringReplace, Clipboard, Clipboard, Ч , Ch , All
StringReplace, Clipboard, Clipboard, Ш , Sh , All
StringReplace, Clipboard, Clipboard, Щ , Sch , All
StringReplace, Clipboard, Clipboard, Ъ , ' , All
StringReplace, Clipboard, Clipboard, Ы , Y , All
StringReplace, Clipboard, Clipboard, Ь , ' , All
StringReplace, Clipboard, Clipboard, Э , E , All
StringReplace, Clipboard, Clipboard, Ю , Ju , All
StringReplace, Clipboard, Clipboard, Я , Ja , All
   send +{Insert}
   sleep 50
   clipSetUnicode(clipSave)
;!!   LangSwitch()
}
RETURN



;Де-транслитерация текста
TextDeTransliterate:
TextDeTransliterate()
TextDeTransliterate()
{
   clipSave:=clipAnsi()
   send ^{Insert}
   sleep,50
StringReplace, Clipboard, Clipboard, zh , ж , All
StringReplace, Clipboard, Clipboard, kh , х , All
StringReplace, Clipboard, Clipboard, shh , щ , All
StringReplace, Clipboard, Clipboard, sch , щ , All
StringReplace, Clipboard, Clipboard, sh , ш , All
StringReplace, Clipboard, Clipboard, ju , ю , All
StringReplace, Clipboard, Clipboard, yu , ю , All
StringReplace, Clipboard, Clipboard, ja , я , All
StringReplace, Clipboard, Clipboard, ya , я , All
StringReplace, Clipboard, Clipboard, ts , ц , All
StringReplace, Clipboard, Clipboard, ch , ч , All
StringReplace, Clipboard, Clipboard, c , ц , All
StringReplace, Clipboard, Clipboard, h , х , All
StringReplace, Clipboard, Clipboard, j , й , All
StringReplace, Clipboard, Clipboard, Zh , Ж , All
StringReplace, Clipboard, Clipboard, Kh , Х , All
StringReplace, Clipboard, Clipboard, Shh , Щ , All
StringReplace, Clipboard, Clipboard, Ju , Ю , All
StringReplace, Clipboard, Clipboard, Yu , Ю , All
StringReplace, Clipboard, Clipboard, Ja , Я , All
StringReplace, Clipboard, Clipboard, Ya , Я , All
StringReplace, Clipboard, Clipboard, Ts , Ц , All
StringReplace, Clipboard, Clipboard, Ch , Ч , All
StringReplace, Clipboard, Clipboard, Sch , Щ , All
StringReplace, Clipboard, Clipboard, Sh , Ш , All
StringReplace, Clipboard, Clipboard, C , Ц , All
StringReplace, Clipboard, Clipboard, H , Х , All
StringReplace, Clipboard, Clipboard, a , а , All
StringReplace, Clipboard, Clipboard, b , б , All
StringReplace, Clipboard, Clipboard, v , в , All
StringReplace, Clipboard, Clipboard, w , в , All
StringReplace, Clipboard, Clipboard, g , г , All
StringReplace, Clipboard, Clipboard, d , д , All
StringReplace, Clipboard, Clipboard, e , е , All
StringReplace, Clipboard, Clipboard, z , з , All
StringReplace, Clipboard, Clipboard, i , и , All
StringReplace, Clipboard, Clipboard, k , к , All
StringReplace, Clipboard, Clipboard, l , л , All
StringReplace, Clipboard, Clipboard, m , м , All
StringReplace, Clipboard, Clipboard, n , н , All
StringReplace, Clipboard, Clipboard, o , о , All
StringReplace, Clipboard, Clipboard, p , п , All
StringReplace, Clipboard, Clipboard, r , р , All
StringReplace, Clipboard, Clipboard, s , с , All
StringReplace, Clipboard, Clipboard, t , т , All
StringReplace, Clipboard, Clipboard, u , у , All
StringReplace, Clipboard, Clipboard, f , ф , All
StringReplace, Clipboard, Clipboard, y , ы , All
StringReplace, Clipboard, Clipboard, ' , ь , All
StringReplace, Clipboard, Clipboard, A , А , All
StringReplace, Clipboard, Clipboard, B , Б , All
StringReplace, Clipboard, Clipboard, V , В , All
StringReplace, Clipboard, Clipboard, W , В , All
StringReplace, Clipboard, Clipboard, G , Г , All
StringReplace, Clipboard, Clipboard, D , Д , All
StringReplace, Clipboard, Clipboard, E , Е , All
StringReplace, Clipboard, Clipboard, Z , З , All
StringReplace, Clipboard, Clipboard, I , И , All
StringReplace, Clipboard, Clipboard, K , К , All
StringReplace, Clipboard, Clipboard, L , Л , All
StringReplace, Clipboard, Clipboard, M , М , All
StringReplace, Clipboard, Clipboard, N , Н , All
StringReplace, Clipboard, Clipboard, O , О , All
StringReplace, Clipboard, Clipboard, P , П , All
StringReplace, Clipboard, Clipboard, R , Р , All
StringReplace, Clipboard, Clipboard, S , С , All
StringReplace, Clipboard, Clipboard, T , Т , All
StringReplace, Clipboard, Clipboard, U , У , All
StringReplace, Clipboard, Clipboard, F , Ф , All
StringReplace, Clipboard, Clipboard, Y , Ы , All
   send +{Insert}
   sleep 50
   clipSetUnicode(clipSave)
;!!   LangSwitch()
}
RETURN



;Изменить раскладку выделенного текста
;^+!vk53::RecodeTextENRU()               ; ^+!S
RecodeTextENRU:
RecodeTextENRU()
RecodeTextENRU()
{
   StringCaseSense On
   AutoTrim,Off

   clipSave:=clipAnsi()
   send ^{Insert}
   sleep,50

   dest=
   text:=clipAnsi()
   StringCaseSense,On
   prevCharToEN=0
   ;      АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ
   RUtoEN=F<DULT:PBQRKVYJGHCNEA{WXIO}SM">Zf,dult;pbqrkvyjghcnea[wxio]sm'.z
   RUtoSP1=хъжэбюХЪЖЭБЮ.,/"№;:?
   RUtoSP2=[];',.{}:"<>/?|@#$^&
   ;      ABCDEFGHIJKLMNOPQRSTUVWXYZ
   ENtoRU=ФИСВУАПРШОЛДЬТЩЗЙКЫЕГМЦЧНЯфисвуапршолдьтщзйкыегмцчня

   loop,parse,text
   {
      destChar=%A_LoopField%

      ; check explicit (non punctuations) ranges
      ifGreaterOrEqual,A_LoopField,А
         prevCharToEN=1
      else if A_LoopField between A and Z
         prevCharToEN=0
      else if A_LoopField between a and z
         prevCharToEN=0

      ; to Russian
      ifEqual,prevCharToEN,0
      {   StringGetPos,i,RUtoEN,%A_LoopField%
         ifEqual,ErrorLevel,0
            Transform,destChar,chr,% i + 0xC0
         else
         {   StringGetPos,i,RUtoSP2,%A_LoopField%
            ifEqual,ErrorLevel,0
               StringMid,destChar,RUtoSP1,% i+1, 1
         }
      }

      ; to English because nothing changed
      ifEqual,destChar,%A_LoopField%
      {
         StringGetPos,i,ENtoRU,%A_LoopField%
         ifEqual,ErrorLevel,0
            Transform,destChar,chr,% i + (i>=26 ? 71 : 65)
         else ; check .,;':"[]{}
         {   StringGetPos,i,RUtoSP1,%A_LoopField%
            ifEqual,ErrorLevel,0,StringMid,destChar,RUtoSP2,% i+1, 1
         }
         ifNotEqual,destChar,%A_LoopField%
            prevCharToEN=1
      }
      dest=%dest%%destChar%
   }

   ; decide compatibility of unicode clipboard
   WinGetClass,cls,A
   if cls in TMsgEditor,wndclass_desked_gsk
   {
      ControlGetFocus,cls,A
      ifInString,cls,TXTRichEdit
         clipSetUnicode(dest)
      else
         Clipboard=%dest%
   }
   else
      clipSetUnicode(dest)
   sleep,50
   send +{Insert}
   sleep 50

   clipSetUnicode(clipSave)
;!!   LangSwitch()
}
RETURN

; read unicode clipboard into ansi string
clipAnsi()
{
   StringLen,L,Clipboard
   L:=(L+1)*4
   transform,ca_Clip,unicode
   varSetCapacity(ca_WideText,L,0)
   varSetCapacity(ca_AnsiText,L,0)
   ; Convert UTF-8 to UTF-16.   CP_UTF8=65001
   if dllCall("MultiByteToWideChar",uint,65001, uint,0, str,ca_Clip
              , uint,-1, str,ca_WideText, uint,L/2)
      dllCall("WideCharToMultiByte",uint,0, uint,0, str,ca_WideText
              , uint,-1, str,ca_AnsiText, uint,L/2, uint,0, uint,0)
      ; Convert UTF-16 to ANSI.  CP_ACP=0
   Return ca_AnsiText
}
RETURN

;--------------------------------------------------------------
; copy ansi string to clipboard in unicode mode
clipSetUnicode(cu_AnsiText)
{
   StringLen,L,cu_AnsiText
   L:=(L+1)*4
   varSetCapacity(cu_WideText,L,0)
   varSetCapacity(cu_UTFtext,L,0)
   ; ANSI to UTF-16.   CP_ACP=0
   if dllCall("MultiByteToWideChar",uint,0, uint,0, str,cu_AnsiText
              , uint,-1, str,cu_WideText, uint,L/2)
      dllCall("WideCharToMultiByte",uint,65001, uint,0, str,cu_WideText
              , uint,-1, str,cu_UTFtext, uint,L/2, uint,0, uint,0)
      ; Convert UTF-16 to UTF-8.  CP_UTF8=65001
   transform,clipboard,unicode,%cu_UTFtext%
}
RETURN



;

;___________________________________________________________________________
;###########################################################################
;########### Изменить прозрачность окна ctrl+shift+колесо мыши #############
;###########################################################################
OnExit EXIT
^+WheelDown::
^+WheelUp::
Sleep 50
MouseGetPos cx, cy, Win_Id
WinGetClass Class, ahk_id %Win_Id%
If Class in Progman ;,Shell_TrayWnd
Return
IfEqual N%Win_Id%,, {
WinGet T, Transparent, ahk_id %Win_Id%
IfEqual T,, SetEnv T,255
List = %List%%Win_Id%,%T%,
N%Win_Id% = %T%
}
IfEqual A_ThisHotKey,^+WheelUp, EnvAdd N%Win_Id%,50
Else N%Win_Id% -= 50 ;Transparency changing step
IfGreater N%Win_Id%,255, SetEnv N%Win_Id%,255
IfLess N%Win_Id%,0, SetEnv N%Win_Id%,1
WinSet Transparent, % N%Win_Id%, ahk_id %Win_Id%
TrayTip,,% "Transparency: " N%Win_Id%
Return

EXIT:
Loop Parse, List, `,
If (A_Index & 1)
Id = %A_LoopField%
Else
Winset Transparent, %A_LoopField%, ahk_id %Id%
ExitApp
;###########################################################################
;########### Изменить прозрачность окна ctrl+shift+колесо мыши #############
;###########################################################################





SysInfo:
IfWinExist, ahk_id %ID5%
  Goto, 5GuiClose
Gui, 5:+LastFound +AlwaysOnTop +Caption -minimizebox
WinGet, ID5
WinSet, Transparent, 0

Gui, 5:Add, Text, x5 y6, Current Time
Gui, 5:Add, Text, x5 y50, Start Time
Gui, 5:Add, Text, x5 y94, Time since last reboot (ms)
Gui, 5:Add, Text, x5 y138, Date
Gui, 5:Add, Text, x5 y182, Current user name
Gui, 5:Add, Text, x5 y226, Computer Name
Gui, 5:Add, Text, x5 y270, IP address
Gui, 5:Add, Text, x5 y314, System being Run

Gui, 5:Add, Edit, x5 y21 w150 vText0 ReadOnly,
Gui, 5:Add, Edit, x5 y65 w150 vText1 ReadOnly,
Gui, 5:Add, Edit, x5 y109 w150 vText2 ReadOnly,
Gui, 5:Add, Edit, x5 y153 w150 vText3 ReadOnly,
Gui, 5:Add, Edit, x5 y197 w150 vText4 ReadOnly,
Gui, 5:Add, Edit, x5 y241 w150 vText5 ReadOnly,
Gui, 5:Add, Edit, x5 y285 w150 vText6 ReadOnly, ;IP-адрес
Gui, 5:Add, Edit, x5 y329 w150 vText7 ReadOnly,

Gui, 5:Show, %WorkArea% AutoSize, System Info
Melt(ID5, 255, 1)

Loop
{

t_TimeFormat := "HH:mm:ss"
t_StartTime :=                          ; Clear variable = A_Now
t_UpTime := A_TickCount // 1000         ; Elapsed seconds since start
t_StartTime += -t_UpTime, Seconds       ; Same as EnvAdd with empty time
FormatTime t_NowTime, , %t_TimeFormat%  ; Empty time = A_Now
FormatTime t_StartTime, %t_StartTime%, %t_TimeFormat%
t_UpTime := % t_UpTime // 86400 " дн., " mod(t_UpTime // 3600, 24) " ч, " mod(t_UpTime // 60, 60) " мин, " mod(t_UpTime, 60) " с"
;MsgBox 64, Uptime, % "Start time: `t" t_StartTime "`nTime now:`t" t_NowTime "`n`nElapsed time:`t" t_UpTime

GuiControl, 5:, Text0, %t_NowTime%
GuiControl, 5:, Text1, %t_StartTime%
GuiControl, 5:, Text2, %t_UpTime%
GuiControl, 5:, Text3, %A_DDDD%, %A_MMMM% %A_DD%  %A_Year%
GuiControl, 5:, Text4, %A_UserName%
GuiControl, 5:, Text5, %A_ComputerName%
GuiControl, 5:, Text6, %A_IPAddress1%
GuiControl, 5:, Text7, %A_OSType%
}
return

5GuiClose:
Melt(ID5, 255, 0)
reload
return









;___________________________________________________________________________
;###########################################################################
;################## Secret Numeric Labels ##################################
;###########################################################################
SendMode Input

NumpadMult::   ;*
  Tc:=A_TickCount
  LongP=0
  Loop {
         Sleep 10
         NPdown:=GetKeyState("NumpadMult","P")
         IfEqual,NPDown,0, Break
         If ((A_TickCount-Tc)>499) {
         LongP=1
         Break
       }                           }
IfEqual,LongP,1,GoSub,CreateSecretGUI
  Else
SendRaw *
Return

CreateSecretGUI:
 Gui, 6:+AlwaysOnTop +ToolWindow -SysMenu
 Gui, 6:Font, S14 Bold, Verdana
 Gui, 6:Add,Listview, x5 y16 h33 +ReadOnly  w190 Center
 Gui, 6:Add,Text    , x5 y16 h33 vSecretKey w190 Center
 Gui, 6:Show, w200 h50, Enter Secret Numeric Label:
 LoopExit=0
 KeyLabel=

 Loop {
        IfEqual,LoopExit,1,Return
        vKey:=InputKey(2000)

        If (VKey>=0x30 AND VKey<=0x39 OR VKey>=0x60 AND VKey<=0x69) {
        StringRight,Num,Vkey,1
        KeyLabel=%KeyLabel%%Num%
        Mask:= StrLen(KeyLabel)
        Star=
        Loop, %Mask%
              Star=%Star%*
        GuiControl,6:,SecretKey,% Star
        }

        If (KeyLabel="" AND vKey="") {
        Gui, 6:Destroy
        LoopExit=1
        }

        If (KeyLabel!="" AND (vKey="" OR vKey="0x0D")) {
        Gui, 6:Destroy
        LoopExit=1
        if (IsLabel(KeyLabel))
           GoSub, %KeyLabel%
      } }
Return

InputKey(Duration=0, Prefix="")    {
 Global A_KBI_Timeleft
 IfEqual,Prefix,, SetEnv,Prefix,0x
 A_FI:=A_FormatInteger
 TC:=A_TickCount
 VarSetCapacity(lpKeyState,256,0)
 DllCall("SetKeyboardState", UInt,&lpKeyState)
 Loop {
        DllCall("GetKeyboardState", UInt,&lpKeyState)
        Loop, 256 {
                    Int:=*(&lpkeystate+(A_Index-1))
                    If (Int>=0x80)
                      {
                        VK_CODE:=A_Index-1
                        Break
                      }
                  }
        IfNotEqual,VK_CODE,, Break
        A_KBI_Timeleft:=Round((Duration-(A_TickCount-TC))/1000)
        If (Duration AND (A_TickCount-TC>=Duration))
           Break
        Sleep 20
      }
IfEqual,VK_CODE,, Return, VK_CODE
 SetFormat, Integer, Hex
 VK_CODE+=0
 StringReplace, VK_CODE, VK_CODE, 0x, 0x0
 StringRight, VK_CODE, VK_CODE, 2
 StringUpper, VK_CODE, VK_CODE
 SetFormat, Integer, %A_FI%
Retval=%Prefix%%VK_CODE%
Return RetVal
}
;###########################################################################
;################## Secret Numeric Labels ##################################
;###########################################################################








;F1::
myHelp:
HelpText =
(
'CTRL'+'SHIFT'+'h' / 'h''h'`t-> Показать/скрыть СКРЫТЫЕ / СИСТЕМНЫЕ файлы
'CTRL'+'SHIFT'+'ALT'+'r' / 'r''r'`t-> Конвертер регистров / Изменить раскладку текста
'CTRL'+'SHIFT'+'ALT'+'a'`t`t-> Изменение атрибутов
'SHIFT'+'WIN'+'t' / 't''t'`t`t-> Транслитерация / Де-транслитерация текста
'CTRL'+'SHIFT'+'ALT'+'e'`t`t-> Поиск-извлечение архивов
'WIN'+'Del' / 'Del''Del'`t`t-> Удалить все пустые подпапки / Очистить корзину
'ПРАВАЯ МЫШЬ'+'БАРАБАН'`t-> Очистить корзину
'ПРАВАЯ МЫШЬ'+'КОЛЕСО'`t-> Системная громкость
'ЛЕВАЯ МЫШЬ'+'БАРАБАН'`t-> Создать папку
'ЛЕВАЯ МЫШЬ'+'КОЛЕСО'`t-> Размер/Качество эскизов / Изменить вид папок
'ЛЕВАЯ'+'ПРАВАЯ МЫШЬ'`t-> Быстрый запуск: TaskBar, Стол. 'CTRL'+'SHIFT'+'ПМ' - в любой момент
'CTRL'+'SHIFT'+'КОЛЕСО'`t-> Изменить прозрачность окна
'ALT'+'CTRL'+'WIN'+'Space'`t-> Выдвинуть/задвинуть поддон CD/DVD-привода
'WIN'+'ЛВ' / 'LWin'+'ПР МЫШЬ'`t-> Перемещение / Изменение размеров окон
'WIN'+'a' / 'a''a'`t`t`t-> Назначить/снять окно - поверх всех
'WIN'+'SHIFT'+'с' / 'с''с'`t`t-> Копировать путь к выделенному объекту/объектам
`t`t`t`t-> Открыть путь (из буфера, выделенный) [explorer-regedit-url]
'WIN'+'PgUp' / 'PgUp''PgUp'`t-> Заставка / Выключение монитора
'WIN'+'1' / '1''1'`t`t`t-> Найти объект... (ярлык и т.п.) / Открыть содержащую объект папку
'WIN'+'9' / '9''9'`t`t`t-> Получить путь к процессу активного окна / Получить класс окна
'NUM *'`t`t`t`t-> Secret Numeric Labels

Проводник, Рабочий стол, Диалог=
'CTRL'+'e'`t`t`t-> Группирование файлов по расширению
'CTRL'+'g'`t`t`t-> Перенести выделенные файлы в папку вида #GroupNN
'CTRL'+'SHIFT'+'g'`t`t-> Перенести ФАЙЛЫ И ПАПКИ из выделенных папок`n`t`t`t`t    уровнем выше, затем удалить эти выделенные папки
'CTRL'+'SHIFT'+'ALT'+'g'`t`t-> Переместить ВСЕ ФАЙЛЫ из выделенных папок`n`t`t`t`t    в текущую, затем удалить эти выделенные папки
'CTRL'+'SHIFT'+'WIN'+'ALT'+'g'`t-> Переместить ВСЕ ФАЙЛЫ из подкаталогов в текущий`n

'CTRL'+'SHIFT'+'c' / 'm' / 'd'`t-> Копирование/перемещение/переход в "Favorites\Ваши-ярлыки-папок"
'ALT'+'(' / ')'`t`t`t-> Мгновенное копирование/перемещение`n`t`t`t`t    в "Favorites\#Quick#\Ярлык-вашей-папки" (по умолч. - 'Рабочий стол')
'WIN'+'q'`t`t`t-> f_CreateQuickShortcut

`nTray ALT CTRL .........................
'CTRL'+'ЛЕВАЯ МЫШЬ'`t`t-> Task Bar/Панель инструментов окна эксплорера
)
;======================== Pop-Up Window =======================
;TOAST UP!
   SysGet, Workspace, MonitorWorkArea
   Gui, 10:default
   Gui, 10:-Caption +ToolWindow +LastFound +AlwaysOnTop +Border
   Gui, 10:Color, 000080
   Gui, 10:Font, s10 cwhite
   Gui, 10:Add, Text, gFade,Фишки:
   Gui, 10:Font, s8 cgray
   Gui, 10:Add, Text, gFade, %HelpText%

   Gui, 10:Font, s7 cwhite underline
   Gui, 10:Add, Text, gFade,Created By: rrrrrrrr

   Gui, 10:Show, Hide
   GUI_ID := WinExist()
   WinGetPos, GUIX, GUIY, GUIWidth, GUIHeight, ahk_id %GUI_ID%
   NewX := WorkSpaceRight-GUIWidth-5
   NewY := WorkspaceBottom-GUIHeight-5
   Gui, 10:Show, Hide x%NewX% y%NewY%

   DllCall("AnimateWindow","UInt",GUI_ID,"Int",500,"UInt","0x00040008")
   RETURN

;TOAST DOWN!
Fade:
   DllCall("AnimateWindow","UInt",GUI_ID,"Int",1000,"UInt","0x90000") ; Fade out when clicked
   RETURN
;======================== /Pop-Up Window =======================


;Найти объект...
;#1::
f_FindObject:
  tooltip = * Найти объект...
  CoordMode, ToolTip, Screen
  ToolTip, %tooltip%,0,0
ClipSaved := ClipboardAll
Clipboard =
Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
ClipWait, 2
Object = %Clipboard%
Clipboard := ClipSaved

  FileGetShortcut, %Object%, o_path

  If ErrorLevel
    tooltip

  If o_path =
    return
  Run, explorer.exe /select`,%o_path%,, UseErrorLevel
  Sleep, 2000
  tooltip
return


;Открыть содержащую объект папку
;#2::
f_OpenObject:
 tooltip = * Открыть содержащую объект папку
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
ClipSaved := ClipboardAll
Clipboard =
Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
ClipWait, 2
Object = %Clipboard%
Clipboard := ClipSaved

  Loop, Parse, Object, `n, `r
    {
      Object := A_LoopField
      break
    }
    SplitPath, Object, Name, Dir
    Run, Explorer /select`,%Dir%\%Name%,, UseErrorLevel
 Sleep, 2000
 tooltip
return


;Открыть путь
;#3::
f_OpenClipboardPath:
 tooltip = * Открыть путь
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 f_ClipSaved := ClipboardAll
Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
ClipWait, 2
f_RunPath(Clipboard)
Clipboard := f_ClipSaved
f_ClipSaved = ; Free the memory in case the clipboard was very large.
 Sleep, 2000
 tooltip
return




; ############ /Attributizer ######################################
^+!vk41::                ; ^+!A
Attributizer:
Clipboard =
f_ClipWait_Loop()
Object = %Clipboard%

gosub Attribute_Modifier
return

Attribute_Modifier:

IfWinExist, ahk_id %ID4%
  Goto, 4GuiClose
Gui, 4:+LastFound +AlwaysOnTop +Caption -minimizebox
WinGet, ID4
WinSet, Transparent, 0

Gui, 4:Font, s8, Tahoma
Gui, 4:Add, Edit, x10 y10 r5 w480 ReadOnly vc_filesedit ,
Gui, 4:Add, GroupBox, x10 y90 w480 h27 ,
Gui, 4:Add, CheckBox, x14 y100 h10 vr, r  Только чтение
 r_TT := "Read-only"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, R
 guicontrol, 4:,r,1
Gui, 4:Add, CheckBox, x140 y100 h10 vh, h  Скрытый
 h_TT := "Hidden"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, H
 guicontrol, 4:,h,1
Gui, 4:Add, CheckBox, x264 y100 h10 vs, s  Системный
 s_TT := "System"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, S
 guicontrol, 4:,s,1
Gui, 4:Add, CheckBox, x380 y100 h10 va, a  Архивный
 a_TT := "Archive"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, A
 guicontrol, 4:,a,1
Gui, 4:Add, GroupBox, x10 y109 w480 h27 ,
Gui, 4:Add, CheckBox, x14 y119 h10 vd, d  Каталог
 d_TT := "Directory"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, D
 guicontrol, 4:,d,1
Gui, 4:Add, CheckBox, x140 y119 h10 vo, o  Отключен
 o_TT := "Offline"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, O
 guicontrol, 4:,o,1
Gui, 4:Add, CheckBox, x264 y119 h10 vc, c  Сжатый
 c_TT := "Compressed"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, C
 guicontrol, 4:,c,1
Gui, 4:Add, CheckBox, x380 y119 h10 vt, t  Временный
 t_TT := "Temporary"
 FileGetAttrib, Attributes, %Object%
 IfInString, Attributes, T
 guicontrol, 4:,t,1
Gui, 4:Add,Button, x170 y150 W70 H24  Default, OK
Gui, 4:Add,Button, x253 y150 W70 H24 , Cancel
Gui, 4:Add,Button, x465 y150 W25 H24 vcsh gCheck_SuperHidden, %A_Space%•%A_Space%
 csh_TT := "Переключить системные`nПоказать скрытые"
Gui, 4:Show, h200 w500, Изменение атрибутов
 Melt(ID4, 255, 1)
 GuiControl,4:,c_filesedit,%Object%
 OnMessage(0x200, "WM_MOUSEMOVE")
RETURN

4ButtonOK:
Melt(ID4, 255, 0)
Gui, 4:Submit
gui, 4:destroy
  Loop, parse, Clipboard, `n, `r
  {
    fileName = %A_LoopField%

    if s=1
    FileSetAttrib, +s, %fileName%, 1
    if r=1
    FileSetAttrib, +r, %fileName%, 1
    if a=1
    FileSetAttrib, +a, %fileName%, 1
    if h=1
    FileSetAttrib, +h, %fileName%, 1
    if o=1
    FileSetAttrib, +o, %fileName%, 1
    if t=1
    FileSetAttrib, +t, %fileName%, 1
    if s=0
    FileSetAttrib, -s, %fileName%, 1
    if r=0
    FileSetAttrib, -r, %fileName%, 1
    if a=0
    FileSetAttrib, -a, %fileName%, 1
    if h=0
    FileSetAttrib, -h, %fileName%, 1
    if o=0
    FileSetAttrib, -o, %fileName%, 1
    if t=0
    FileSetAttrib, -t, %fileName%, 1
   }
GuiControl,,c_filesedit,%FilesEdit%   ;?????????????
return

4GuiClose:
Melt(ID4, 255, 0)
gui, 4:destroy
RETURN

4ButtonCancel:
Melt(ID4, 255, 0)
gui, 4:destroy
RETURN
; ############ Attributizer/ ######################################



;!!Копирование/перемещение <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

#vk51::    ;Win+Q
f_CreateQuickShortcut:
ClipSaved := ClipboardAll
Clipboard =
Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
ClipWait, 2
File = %Clipboard%
Clipboard := ClipSaved

  Loop, Parse, File, `n, `r
    {
      File := A_LoopField
      break
    }
    SplitPath, File, FileName, Dir
    FileCreateShortCut, %Dir%\%FileName%, %f_shortcuts_folder%\•  %FileName%.LNK
return


f_CreateShortcut:
IfWinExist, ahk_id %ID7%
  Goto, 7GuiClose
Gui, 7:+LastFound +AlwaysOnTop -minimizebox
WinGet, ID7
WinSet, Transparent, 0

Gui, 7:Add, Text, x16 y11 w130 h20 , Имя ярлыка:
Gui, 7:Add, Edit, x16 y31 w390 h20 vShtct_Name
Gui, 7:Add, Text, x16 y61 w400 h20 , Путь ярлыка:
Gui, 7:Add, Edit, x16 y81 w390 h20 vShtct_Path
Gui, 7:Add, Text, x16 y111 w190 h20 , Куда сохранить ярлык:
Gui, 7:Add, Edit, x16 y131 w390 h20 vf_shrtcts_fldr , %f_shortcuts_folder%
Gui, 7:Add, Button, x96 y165 w100 h20 Default   +Center, OK
Gui, 7:Add, Button, x236 y165 w100 h20 +Center, Cancel
Gui, 7:Show, x390 y277 h202 w423, Создание ярлыков
Melt(ID7, 255, 1)

GuiControl,7:,f_shrtcts_fldr,%f_shortcuts_folder%
Return
7ButtonOK:
Melt(ID7, 255, 0)
Gui, 7:Submit, NoHide
FileCreateShortcut %Shtct_Path%, %f_shortcuts_folder%\%Shtct_Name%.lnk
gui, 7:destroy
Return
7ButtonCancel:
Melt(ID7, 255, 0)
gui, 7:destroy
RETURN
7GuiClose:
Melt(ID7, 255, 0)
gui, 7:destroy
Return



;----Build the menu from link files found in f_shortcuts_folder.
f_CreateMenu:
  If f_AlwaysReload != y
    {
      If f_NotFirstTime = True
          Return
    }

  BuildMenu( f_shortcuts_folder, f_shortcuts_folder )

  f_NotFirstTime = True

  ;;;;;;;;;;;;;;;;;Special_Folders( f_shortcuts_folder )

  ; Add a separator line.
  Menu, %f_shortcuts_folder%, Add

  ; Add a command to capture the current folder address.
  ;;;;;;;;;;;;;;;;;Menu, my_sub, Add, Add Folder to Favorites, f_AddFolder
  ; Add a command to capture the current application.
  ;;;;;;;;;;;;;;;;;Menu, my_sub, Add, Add File to Favorites, f_AddFile
  ; Add a command to allow the user to edit the shortcuts.
  Menu, %f_shortcuts_folder%, Add, Add Quick Shortcut ` ` Win+Q, f_CreateQuickShortcut
  Menu, %f_shortcuts_folder%, Add, Create Shortcut, f_CreateShortcut
  Menu, %f_shortcuts_folder%, Add, Edit Favorites Folder, f_EditFavorites
  ; Show Reload menu only if not set to Reload on every popup.
  ;;;;;;;;;;;;;;;;;Menu, %f_shortcuts_folder%, Add, F&avorites..., :my_sub
  If f_AlwaysReload = n
      Menu, %f_shortcuts_folder%, Add, Reload, Reload
Return
       

3 (изменено: DD, 2009-11-14 20:10:06)

Re: AHK: Коллекция скриптов для комфортной работы в одном

BuildQuickMenu( testPath, menu )
  {
    local MenuName, folderList, nextMenu, fileList, MenuItemName
    local nameHash, incr, num, shortPath, len, varName

    If Menu =
        MenuName := testPath
    Else
        MenuName := Menu

    If f_NotFirstTime = True
        Menu, %MenuName%, DeleteAll

    ; Add all subfolders to menu as submenus
    Loop, %MenuName%\*, 2
        folderList = %folderList%`n%A_LoopFileFullPath%
    Sort, folderList
    Loop, Parse, folderList, `n
      {
        If A_LoopField =
            Continue
        MenuItemName := FileShortName( A_LoopField )
        nextMenu := BuildMenu(A_LoopField,"")
        If nextMenu !=
            Menu, %MenuName%, add, %MenuItemName%, :%nextMenu%
      }

    ; Add a separator line only if there were any subfolders.
    If %folderList%
        Menu, %MenuName%, Add

    ; Add all link files in this 'menuName' to the menu
    Loop, %MenuName%\*, 0
        fileList = %fileList%%A_LoopFileFullPath%`n
    ; Sort the fileList according to the number in the link comment field.
    fileList := f_LinkSort( fileList )

    shortPath := ShortenPath( MenuName )
    pathHash := String2Hex( shortPath )
    varName = f_MenuName[%pathHash%]
    f_TestVarNameLength( varName )
    array = f_MenuName[%pathHash%]
    varName = f_MenuCount[%pathHash%]
    f_TestVarNameLength( varName )
    f_MenuCount[%pathHash%] = 0
    Loop, Parse, fileList, `n
      {
        If A_LoopField =
          {
            Menu, %MenuName%, add
            Continue
          }
        MenuItemName := FileShortName( A_LoopField, "last" )

        ; Build an array of menu names to check for duplicates now and in f_AddToFavorites.
        num := f_MenuCount[%pathHash%]
        incr = 0
        Loop
          {
            If ( f_DuplicateItems( array, num, MenuItemName ) == 0 )
              {
                incr++
                MenuItemName = %MenuItemName%%incr%
              }
            Else
                Break
          }
        f_MenuCount[%pathHash%]++
        num := f_MenuCount[%pathHash%]
        Transform, %array%%num%, Deref, %MenuItemName%

        ; Build an array whose indices is the menu item name and contents is the full link file name.


        varName = f_fullName[%pathHash%][%nameHash%]
        f_TestVarNameLength( varName )
        Transform, f_fullName[%pathHash%][%nameHash%], Deref, %A_LoopField%

        f_QuickOpen()
      }
    If fileList =
        Return ""
    Else
        Return MenuName
  }


; Test dynamic variable name length before we assign it.
; Max variable name length allowed is 253.
f_TestVarNameLength( name )
  {
    StringLen, len, name
    If ( len > 252 )
      {
        MsgBox, Warning!`n A subfolder name or nested subfolder names is too long
        . `nThe base folder will now be opened to allow you to shorten it!
        Gosub, f_EditFavorites
        ; Exit current thread since it will fail anyway since a variable name is
        ; too long. Script will not exit since it is persistent.
        Exit
      }
    Return
  }

; Get comment of each link. Search for number after prefix. Sort by number.
; Any links without number add to end sorted by alpha on link name.
f_LinkSort( linkList )
  {
    prefix = Menu=
    Loop, Parse, linkList, `n
      {
        If ( A_LoopField == "" )
            Continue
        FileGetShortcut, %A_LoopField%,,,, comment
        StringLower, comment, comment
        ; Store comment for finding blanks later.
        shortName := FileShortName( A_LoopField )
        nameHash := String2Hex( shortName )
        varName = comment%nameHash%
        f_TestVarNameLength( varName )
        comment%nameHash% = %comment%

        StringGetPos, pos, comment, %prefix%
        If ( pos > -1 )
          {
            len := StrLen( prefix )
            pos += len
            StringTrimLeft, rem, comment, %pos%
            good =
            Loop, Parse, rem
              {
                If A_LoopField is Integer
                    good = %good%%A_LoopField%
                Else
                    Break
              }
            If %good%
              {
                Loop
                  {
                    If ( array%good% != "" )
                        good++
                    Else
                        Break
                  }
                array%good% := A_LoopField
                If ( good > maxGood )
                    maxGood = %good%
              }
          }
        Else
          {
            noIndex = %noIndex%%A_LoopField%`n
          }
      }
    Loop, %maxGood%
      {
        If ( array%A_Index% != "" )
          {
            tempvar := array%A_Index%
            newList = %newList%%tempvar%`n
          }
      }
    If ( noIndex != "" )
      {
        Sort, noIndex
        newList = %newList%%noIndex%
      }
    ; Get rid of the last newline.
    StringTrimRight, newList, newList, 1
    ; Add blank lines if 'blank' appears after 'prefix'.
    Loop, Parse, newList, `n
      {
        nl =
        shortName := FileShortName( A_LoopField )
        nameHash := String2Hex( shortName )
        varName = comment%nameHash%
        f_TestVarNameLength( varName )
        comment := comment%nameHash%
        StringGetPos, pos, comment, %prefix%
        If ( pos > -1 )
          {
            len := StrLen( prefix )
            pos += len
            StringTrimLeft, rem, comment, %pos%
            str =
            Loop, Parse, rem
              {
                str = %str%%A_LoopField%
                If str is not Integer
                  {
                    StringGetPos, pos, rem, blank
                    If ( pos + 1 = A_Index )
                        nl = `n
                    Break
                  }
              }
          }
        newerList = %newerList%%A_LoopField%`n%nl%
      }
    ; Get rid of the last newline.
    StringTrimRight, newerList, newerList, 1

    Return %newerList%
  }

Reload:
  Reload  ; The Menu will be rebuilt at next popup.
Return

;----Display the menu but do a copy first
f_DisplayMenuForCopy:
   CommandMode = 2 ; copy mode

   clipboard =

   f_ClipWait_Loop()

/*
   Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
   ClipWait 10

   if errorlevel<>0
      {
      soundplay *16 ;-- Error
      Return
      }
   clipboard =
   Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
   ClipWait 10
*/
   Sort, clipboard  ; This also converts to text (full path and name of each file).
   GlobalFileList = %clipboard%

   ;MsgBox %GlobalFileList%
   Gosub f_DisplayMenu
Return

;----Display the menu but do a CTRL-X first
f_DisplayMenuForMove:
   CommandMode = 3 ; Move mode

   clipboard =

   f_ClipWait_Loop()

   Sort, clipboard  ; This also converts to text (full path and name of each file).
   GlobalFileList = %clipboard%

   ;MsgBox %GlobalFileList%
   Gosub f_DisplayMenu
Return

;----Display the menu but do a copy first
f_DisplayMenuForQuickCopy:
   CommandMode = 2 ; copy mode

   clipboard =

   f_ClipWait_Loop()

   Sort, clipboard  ; This also converts to text (full path and name of each file).
   GlobalFileList = %clipboard%

   ;MsgBox %GlobalFileList%
   Gosub f_QuickDisplayMenu
Return

;----Display the menu but do a copy first
f_DisplayMenuForQuickMove:
   CommandMode = 3 ; copy mode

   clipboard =

   f_ClipWait_Loop()

   Sort, clipboard  ; This also converts to text (full path and name of each file).
   GlobalFileList = %clipboard%

   ;MsgBox %GlobalFileList%
   Gosub f_QuickDisplayMenu
Return

;----Display the menu but do a copy first
f_DisplayMenuForNavigation:
   CommandMode = 1
   Gosub f_DisplayMenu
Return

;----Display the menu
f_DisplayMenu:
  ; These first few variables are set here and used by f_OpenFavorite:
  WinGet, f_window_id, ID, A
  WinGet, f_window_min, MinMax
  If ( f_window_min == -1 ) ; Only detect windows not Minimized.
      f_window_id =
  WinGetClass, f_class, ahk_id %f_window_id%
  If f_class in #32770,ExploreWClass,CabinetWClass,dopus.lister  ; Dialog or Explorer.
      ControlGetPos, f_Edit1Pos,,,, Edit1, ahk_id %f_window_id%
  If f_AlwaysShowMenu = n  ; The Menu should be shown only selectively.
    {
      If f_class in #32770,ExploreWClass,CabinetWClass  ; Dialog or Explorer.
        {
          If f_Edit1Pos =  ; The Control doesn't Exist, so don't display the Menu
              Return
        }
      Else If f_class <> ConsoleWindowClass
        {
          IfNotInString, f_class, bosa_sdm_  ; Microsoft Office application
              Return ; Since it's some other window type, don't display Menu.
        }
    }
  ; Otherwise, the menu should be presented for this type of window:
  Gosub f_CreateMenu


;################################################################################
IfExist, %f_shortcuts_folder%\Target.lnk
  {
    Menu, %f_shortcuts_folder%, Delete, Desktop,
    Menu, %f_shortcuts_folder%, Rename, Target,
  }
IfExist, %f_shortcuts_folder%\QMenu.ini
  {
    Menu, %f_shortcuts_folder%, Delete, QMenu,
  }
;################################################################################


  Menu, %f_shortcuts_folder%, show
Return


;----Display the menu
f_QuickDisplayMenu:
  ; These first few variables are set here and used by f_OpenFavorite:
  WinGet, f_window_id, ID, A
  WinGet, f_window_min, MinMax
  If ( f_window_min == -1 ) ; Only detect windows not Minimized.
      f_window_id =
  WinGetClass, f_class, ahk_id %f_window_id%
  If f_class in #32770,ExploreWClass,CabinetWClass,dopus.lister  ; Dialog or Explorer.
      ControlGetPos, f_Edit1Pos,,,, Edit1, ahk_id %f_window_id%
  If f_AlwaysShowMenu = n  ; The Menu should be shown only selectively.
    {
      If f_class in #32770,ExploreWClass,CabinetWClass  ; Dialog or Explorer.
        {
          If f_Edit1Pos =  ; The Control doesn't Exist, so don't display the Menu
              Return
        }
      Else If f_class <> ConsoleWindowClass
        {
          IfNotInString, f_class, bosa_sdm_  ; Microsoft Office application
              Return ; Since it's some other window type, don't display Menu.
        }
    }
  ; Otherwise, the menu should be presented for this type of window:
    IfNotExist, %f_quicklnk%
    {
      TrayTip, Предупреждение, В каталоге %f_myquick_folder% `nнет ярлыка`, указывающего на вашу папку., , 3
      Sleep, 5000
      TrayTip, Off
    }
    else
    {
    BuildQuickMenu( f_myquick_folder, f_myquick_folder )
    }
Return


ShellFileOperation( fileO=0x0, fSource="", fTarget="", flags=0x0, ghwnd=0x0 )
{
   ;FO_MOVE   := 0x1
   ;FO_COPY   := 0x2
   ;FO_DELETE := 0x3
   ;FO_RENAME := 0x4

   ;FOF_MULTIDESTFILES    0x1    Indicates that the to member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
   ;FOF_SILENT    0x4    Does not display a progress dialog box.
   ;FOF_RENAMEONCOLLISION    0x8    Gives the file being operated on a new name (such as "Copy #1 of...") in a move, copy, or rename operation if a file of the target name already exists.
   ;FOF_NOCONFIRMATION    0x10    Responds with "yes to all" for any dialog box that is displayed.
   ;FOF_ALLOWUNDO    0x40    Preserves undo information, if possible. With del, uses recycle bin.
   ;FOF_FILESONLY    0x80    Performs the operation only on files if a wildcard filename (*.*) is specified.
   ;FOF_SIMPLEPROGRESS    0x100    Displays a progress dialog box, but does not show the filenames.
   ;FOF_NOCONFIRMMKDIR    0x200    Does not confirm the creation of a new directory if the operation requires one to be created.
   ;FOF_NOERRORUI    0x400    don't put up error UI
   ;FOF_NOCOPYSECURITYATTRIBS    0x800    dont copy NT file Security Attributes

   ;http://msdn2.microsoft.com/en-us/library/ms647743.aspx
   ;http://msdn2.microsoft.com/en-us/library/ms538322.aspx

 If ( SubStr(fSource,0) != "|" )
      fSource := fSource . "|"

 If ( SubStr(fTarget,0) != "|" )
      fTarget := fTarget . "|"

 fsPtr := &fSource
 Loop, % StrLen(fSource)
  If ( *(fsPtr+(A_Index-1)) = 124 )
      DllCall( "RtlFillMemory", UInt, fsPtr+(A_Index-1), Int,1, UChar,0 )

 ftPtr := &fTarget
 Loop, % StrLen(fTarget)
  If ( *(ftPtr+(A_Index-1)) = 124 )
      DllCall( "RtlFillMemory", UInt, ftPtr+(A_Index-1), Int,1, UChar,0 )

 VarSetCapacity( SHFILEOPSTRUCT, 30, 0 )                 ; Encoding SHFILEOPSTRUCT
 NextOffset := NumPut( ghwnd, &SHFILEOPSTRUCT )          ; hWnd of calling GUI
 NextOffset := NumPut( fileO, NextOffset+0    )          ; File operation
 NextOffset := NumPut( fsPtr, NextOffset+0    )          ; Source file / pattern
 NextOffset := NumPut( ftPtr, NextOffset+0    )          ; Target file / folder
 NextOffset := NumPut( flags, NextOffset+0, 0, "Short" ) ; options

 DllCall( "Shell32\SHFileOperationA", UInt,&SHFILEOPSTRUCT )

Return NumGet( NextOffset+0 )
}

;----Open the selected favorite
f_OpenFavorite:
   f_Open()
Return

f_Copy( TargetDir )
{
   global GlobalFileList

   IfNotExist, %TargetDir%
   {
   TrayTip, Предупреждение, Папка-приёмник не существует:`n%TargetDir%, , 3
   Sleep, 3000
   TrayTip, Off
   Return
   }

   ;flags := ( FOF_NOCONFIRMMKDIR := 0x200 ) | (FOF_NOCONFIRMATION := 0x10) ;bylo
   ;flags := ( FOF_NOCONFIRMMKDIR := 0x10 ) | (FOF_RENAMEONCOLLISION := 0x8) ;my
   ;MsgBox, %GlobalFileList%
   Loop, parse, GlobalFileList, `r`n
   {
      if (A_LoopField <> "")
      {
         ;MsgBox, Source %A_LoopField%, Target is %target%
         ShellFileOperation(0x2, A_LoopField, TargetDir, flags)
      }
   }

   Return
}

f_Move( TargetDir )
{
   global GlobalFileList

   IfNotExist, %TargetDir%
   {
   TrayTip, Предупреждение, Папка-приёмник не существует:`n%TargetDir%, , 3
   Sleep, 3000
   TrayTip, Off
   Return
   }

   ; ( FOF_RENAMEONCOLLISION := 0x8 )
   ;flags := ( FOF_NOCONFIRMMKDIR := 0x200 ) ;bylo
   ;MsgBox, %GlobalFileList%
   Loop, parse, GlobalFileList, `r`n
   {
      if (A_LoopField <> "")
      {
         ;MsgBox, Source %A_LoopField%, Target is %target%
         ShellFileOperation(0x1, A_LoopField, TargetDir, flags)
      }
   }

   Return
}


f_Copy_cp( TargetDir )
{
   global GlobalFileList

   IfNotExist, %TargetDir%
   {
   TrayTip, Предупреждение, Папка-приёмник не существует:`n%TargetDir%, , 3
   Sleep, 3000
   TrayTip, Off
   Return
   }

   ;flags := ( FOF_NOCONFIRMMKDIR := 0x200 ) | (FOF_NOCONFIRMATION := 0x10) ;bylo
   flags := ( FOF_NOCONFIRMMKDIR := 0x10 ) | (FOF_RENAMEONCOLLISION := 0x8) ;my
   ;MsgBox, %GlobalFileList%
   Loop, parse, GlobalFileList, `r`n
   {
      if (A_LoopField <> "")
      {
         ;MsgBox, Source %A_LoopField%, Target is %target%
         ShellFileOperation(0x2, A_LoopField, TargetDir, flags)
      }
   }

   Return
}

f_Move_cp( TargetDir )
{
   global GlobalFileList

   IfNotExist, %TargetDir%
   {
   TrayTip, Предупреждение, Папка-приёмник не существует:`n%TargetDir%, , 3
   Sleep, 3000
   TrayTip, Off
   Return
   }

   flags := ( FOF_RENAMEONCOLLISION := 0x8) ;my
   ;flags := ( FOF_NOCONFIRMMKDIR := 0x200 ) ;bylo
   ;MsgBox, %GlobalFileList%
   Loop, parse, GlobalFileList, `r`n
   {
      if (A_LoopField <> "")
      {
         ;MsgBox, Source %A_LoopField%, Target is %target%
         ShellFileOperation(0x1, A_LoopField, TargetDir, flags)
      }
   }

   Return
}


f_Open()
  {
    local favPath, nameHash, fullName, ext, target, text

    favPath = %f_shortcuts_folder%
    ; Fetch the full link file name that corresponds to the selected menu item:
    shortPath := ShortenPath( A_ThisMenu )
    pathHash := String2Hex( shortPath )
    nameHash := String2Hex( A_ThisMenuItem )
    fullName := f_fullName[%pathHash%][%nameHash%]

    SplitPath, fullName, , , ext
    ; If .url, run it seperate.
    If ( ext == "url" )
      {
        Run, %fullName%,, UseErrorLevel
        StringUpper, tmp, ErrorLevel
        If ( tmp == "ERROR" )
            MsgBox, 4096, Error, Could not Run: %fullName%, 30
        ;msgbox, %A_LastError%
        Return
      }

    ; Fetch a link file's target that corresponds to the selected menu item:
    If ext in lnk,pif
        FileGetShortcut, %fullName%, target
    SplitPath, target, , , ext
    ; If executable, run it seperate.
    If ext in exe,bat,com
      {
        Run, %fullName%,, UseErrorLevel
        StringUpper, tmp, ErrorLevel
        If ( tmp == "ERROR" )
            MsgBox, 4096, Error, Could not Run: %fullName%, 30
        Return
      }

    if (CommandMode == 1)
     IfNotExist, %f_shortcuts_folder%\Target.lnk
     {
      f_Open_Target( target )
     }
     else
     {
      f_Open_Target_Ctrl( target )
     }

    else
    if (CommandMode == 2)
     if GetKeyState("Ctrl")
     {
      f_Copy_cp( target )
     }
     else
     {
      f_Copy( target )
     }

    else
    if (CommandMode == 3)
     if GetKeyState("Ctrl")
     {
      f_Move_cp( target )
     }
     else
     {
      f_Move( target )
     }
    Return
  }


f_QuickOpen()
  {
    local favPath, nameHash, fullName, ext, target, text

    favPath = %f_shortcuts_folder%
    ; Fetch the full link file name that corresponds to the selected menu item:
    shortPath := ShortenPath( A_ThisMenu )  ;!!
    fullName := f_fullName[%pathHash%][%nameHash%]  ;!!

    SplitPath, fullName, , , ext
    ; If .url, run it seperate.
    If ( ext == "url" )
      {
        Run, %fullName%,, UseErrorLevel
        StringUpper, tmp, ErrorLevel
        If ( tmp == "ERROR" )
            MsgBox, 4096, Error, Could not Run: %fullName%, 30
        ;msgbox, %A_LastError%
        Return
      }

    ; Fetch a link file's target that corresponds to the selected menu item:
    If ext in lnk,pif
        FileGetShortcut, %fullName%, target
    SplitPath, target, , , ext
    ; If executable, run it seperate.
    If ext in exe,bat,com
      {
        Run, %fullName%,, UseErrorLevel
        StringUpper, tmp, ErrorLevel
        If ( tmp == "ERROR" )
            MsgBox, 4096, Error, Could not Run: %fullName%, 30
        Return
      }

    if (CommandMode == 1)
      f_Open_Target( target )
    else
    if (CommandMode == 2)
      f_Copy( target )
    else
    if (CommandMode == 3)
      f_Move( target )

    Return
  }


f_Open_Target( target )
  {
    global f_class, f_Edit1Pos, f_window_id

    ; It's a dialog.
    If f_class = #32770
      {
        If f_Edit1Pos <>   ; And it has an Edit1 Control.
          {
            ; Activate the window so that if the user is middle-clicking
            ; outside the dialog, subsequent clicks will also work:
            WinActivate ahk_id %f_window_id%
            ; Retrieve any filename that might already be in the field so
            ; that it can be restored after the switch to the new folder:
            ControlGetText, text, Edit1, ahk_id %f_window_id%
            ControlSetText, Edit1, %target%, ahk_id %f_window_id%
            ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
            Sleep, 100  ; It needs extra time on some dialogs or in some cases.
            ControlSetText, Edit1, %text%, ahk_id %f_window_id%
            Return
          }
        ; else fall through to the bottom of the subroutine to take standard action.
      }
/*
    ; In Explorer, switch folders.
    Else If f_class in ExploreWClass,CabinetWClass,dopus.lister
      {
        If f_Edit1Pos <>   ; And it has an Edit1 Control.
          {
            ControlSetText, Edit1, %target%, ahk_id %f_window_id%
            ; Tekl reported the following: "If I want to change to Folder L:\folder
            ; then the addressbar shows http://www.L:\folder.com. To solve this,
            ; I added a {right} before {Enter}":
            ControlSend, Edit1, {Right}{Enter}, ahk_id %f_window_id%
            Return
          }
        ; else fall through to the bottom of the subroutine to take standard action.
      }
*/
    ; Microsoft Office application
    Else IfInString, f_class, bosa_sdm_
      {
        ; Activate the window so that if the user is middle-clicking
        ; outside the dialog, subsequent clicks will also work:
        WinActivate ahk_id %f_window_id%
        ; Retrieve any file name that might already be in the File name
        ; control, so that it can be restored after the switch to the new
        ; folder.
        ControlGetText, text, RichEdit20W2, ahk_id %f_window_id%
        ControlClick, RichEdit20W2, ahk_id %f_window_id%
        ControlSetText, RichEdit20W2, %target%, ahk_id %f_window_id%
        ControlSend, RichEdit20W2, {Enter}, ahk_id %f_window_id%
        Sleep, 100  ; It needs extra time on some dialogs or in some case
        ControlSetText, RichEdit20W2, %text%, ahk_id %f_window_id%
        Return
      }
    ; In a console window, CD to that directory
    Else If f_class in ConsoleWindowClass,Console Main Command Window
      {
        WinActivate, ahk_id %f_window_id% ; Because sometimes the mClick deactivates it.
        SetKeyDelay, 1  ; This will be in effect only for the duration of this ThRead.
        IfInString, target, :  ; It Contains a Drive letter
          {
            StringLeft, target_Drive, target, 1
            Send %target_Drive%:{Enter}
          }
        Send, cd %target%{Enter}
        Return
      }
    ; Total Commander
    else if f_class in TTOTAL_CMD,TxUNCOM.UnicodeClass
      {
        ;Total Commander has Edit1 control but you need to cd to location
        if InStr(FileExist(target), "D")
          {
            ControlSetText, Edit1, cd %target%, ahk_id %f_window_id%
            ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
            Return
          }
      }

    ; Since the above didn't Return, one of the following is true:
    ; 1) It's an unsupported window type but f_AlwaysShowMenu is y (yes).
    ; 2) It's a supported type but it lacks an Edit1 control to facilitate the custom
    ;    action, so instead do the default action below.
    Run, %target%,, UseErrorLevel
    StringUpper, tmp, ErrorLevel
    If ( tmp == "ERROR" )
        MsgBox, 4096, Error, Could not open: %target%, 30
    Return
  }


f_Open_Target_Ctrl( target )
  {
    global f_class, f_Edit1Pos, f_window_id

    ; It's a dialog.
    If f_class = #32770
      {
        If f_Edit1Pos <>   ; And it has an Edit1 Control.
          {
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
            ; Activate the window so that if the user is middle-clicking
            ; outside the dialog, subsequent clicks will also work:
            WinActivate ahk_id %f_window_id%
            ; Retrieve any filename that might already be in the field so
            ; that it can be restored after the switch to the new folder:
            ControlGetText, text, Edit1, ahk_id %f_window_id%
            ControlSetText, Edit1, %target%, ahk_id %f_window_id%
            ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
            Sleep, 100  ; It needs extra time on some dialogs or in some cases.
            ControlSetText, Edit1, %text%, ahk_id %f_window_id%
}                    ;!!!!!!
            Return
          }
        ; else fall through to the bottom of the subroutine to take standard action.
      }
/*
    ; In Explorer, switch folders.
    Else If f_class in ExploreWClass,CabinetWClass,dopus.lister
      {
        If f_Edit1Pos <>   ; And it has an Edit1 Control.
          {
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
            ControlSetText, Edit1, %target%, ahk_id %f_window_id%
            ; Tekl reported the following: "If I want to change to Folder L:\folder
            ; then the addressbar shows http://www.L:\folder.com. To solve this,
            ; I added a {right} before {Enter}":
            ControlSend, Edit1, {Right}{Enter}, ahk_id %f_window_id%
}                    ;!!!!!!
            Return
          }
        ; else fall through to the bottom of the subroutine to take standard action.
      }
*/
    ; Microsoft Office application
    Else IfInString, f_class, bosa_sdm_
      {
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
        ; Activate the window so that if the user is middle-clicking
        ; outside the dialog, subsequent clicks will also work:
        WinActivate ahk_id %f_window_id%
        ; Retrieve any file name that might already be in the File name
        ; control, so that it can be restored after the switch to the new
        ; folder.
        ControlGetText, text, RichEdit20W2, ahk_id %f_window_id%
        ControlClick, RichEdit20W2, ahk_id %f_window_id%
        ControlSetText, RichEdit20W2, %target%, ahk_id %f_window_id%
        ControlSend, RichEdit20W2, {Enter}, ahk_id %f_window_id%
        Sleep, 100  ; It needs extra time on some dialogs or in some case
        ControlSetText, RichEdit20W2, %text%, ahk_id %f_window_id%
}                    ;!!!!!!
        Return
      }
    ; In a console window, CD to that directory
    Else If f_class in ConsoleWindowClass,Console Main Command Window
      {
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
        WinActivate, ahk_id %f_window_id% ; Because sometimes the mClick deactivates it.
        SetKeyDelay, 1  ; This will be in effect only for the duration of this ThRead.
        IfInString, target, :  ; It Contains a Drive letter
          {
            StringLeft, target_Drive, target, 1
            Send %target_Drive%:{Enter}
          }
        Send, cd %target%{Enter}
}                    ;!!!!!!
        Return
      }
    ; Total Commander
    else if f_class in TTOTAL_CMD,TxUNCOM.UnicodeClass
      {
        ;Total Commander has Edit1 control but you need to cd to location
        if InStr(FileExist(target), "D")
          {
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
            ControlSetText, Edit1, cd %target%, ahk_id %f_window_id%
            ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
}                    ;!!!!!!
            Return
          }
      }

    ; Since the above didn't Return, one of the following is true:
    ; 1) It's an unsupported window type but f_AlwaysShowMenu is y (yes).
    ; 2) It's a supported type but it lacks an Edit1 control to facilitate the custom
    ;    action, so instead do the default action below.
if GetKeyState("Ctrl")             ;!!!!!!
{                    ;!!!!!!
    Run, %target% ;,, UseErrorLevel
}                    ;!!!!!!
    ;StringUpper, tmp, ErrorLevel
    ;If ( tmp == "ERROR" )
    ;    MsgBox, 4096, Error, Could not open: %target%, 30
    Return
  }


;----Try to find a valid path from the active window title or the clipboard.
f_FindPath( type )
  {
    WinActivate, ahk_id %f_window_id% ; Because sometimes the mClick deactivates it.
    WinGetActiveTitle, addFavorite

    ; First, test whole active window title as valid path.
    good := f_TestWholeString( addFavorite, type )
    If good
      {
        f_AddToFavorites( addFavorite, type )
        Return
      }

    ; Second, parse the Active window title for a valid path.
    good := f_TestSubString( addFavorite, type )
    If good
      {
        f_AddToFavorites( good, type )
        Return
      }

    ; Third, test clipboard contents for valid path.
    clip = %Clipboard%
    good := f_TestWholeString( clip, type )
    If good
      {
        f_AddToFavorites( clip, type )
        Return
      }

    ; Finally, Ask For Manual Path Entry
    StringLen, len, addFavorite
    If len < 340
        len = 340
    msg = No valid path was found.`n Enter a path.
    InputBox, newPath, Favorite Path, %msg%, ,%len%, 140
    If ErrorLevel <> 0 ; Cancel was pressed
      {
        Return
      }
    Else ; OK was pressed
      {
        newPath = %newPath% ;trim trailing/leading whiteSpace
        IfExist, %newPath%
          {
            f_AddToFavorites( newPath, type )
            Return
          }
        Else
          {
            MsgBox, The path Entered is not valid.`nTry again.
            f_FindPath( type )
            Return
          }
      }

    ; Report to user that no valid path was found.
    MsgBox, No valid path was found.
    Return
  }


f_TestWholeString( testPath, type )
  {
    If ( type == "File" )
      {
        test := FileExist( testPath )
        If test Contains A,N   ; True only If Exists and is a file.
            Return 1
      }
    Else ; type = Folder
        If InStr( FileExist( testPath ), "D" ) ; True only If Exists and is folder.
            Return 1

    Return 0  ; The path does not point to a file or folder.
  }


f_TestSubString( testPath, type )
  {
    index = 0
    goodPath = ; Initialize to blank
    ; Loop one character at a time. This is like "Loop, Count". It ensures
    ; we loop once for every character without having to find the string length.
    Loop, Parse, testPath
      {
        index++
        ; Keep adding characters from right to left.
        StringRight, newPath, testPath, %index%
        ; Get rid of everything to the right of the last "\".
        SplitPath, newPath, , outDir
        ; Only keep a path that is valid.
        IfExist, %outDir%
            goodPath = %outDir%
      }
    IfExist, %goodPath%    ; We've got and absolute path to a folder.
      {
        If ( type == "File" )
          {
            ; Get the rest of the string after 'goodPath' in 'addFavorite'.
            StringGetPos, pos, testPath, %goodPath%, R
            StringLen, len, goodPath
            pos += %len%
            StringTrimLeft, tempvar, testPath, %pos%
            ; Add characters to the right of the path position to find filename.
            newTestPath = %goodPath%%tempvar%
            index = 0
            goodPath = ; Initialize to blank
            Loop, Parse, newTestPath
              {
                index++
                ; Keep adding characters from left to right.
                StringLeft, newPath, newTestPath, %index%
                ; Only keep a path that is to a valid file.
                test := FileExist( newPath )
                If test Contains A,N   ; True only If Exists and is a file.
                  {
                    goodPath = %newPath%
                  }
              }
            IfExist, %goodPath%    ; We've got and absolute path to a file.
                Return %goodPath%
          }
        Else ; type = Folder
            If InStr( FileExist( goodPath ), "D" ) ; True only If Exists and is folder.
                Return %goodPath%
      }
    Return 0 ; There was no path pointing to a file or folder found in 'testPath'.
  }


;----Save found valid path to a new link file in f_shortcuts_folder.
f_AddToFavorites( addFavorite, type )
  {
    global f_shortcuts_folder

    ; Make a default shortcut name from the path.
    ; Replace ':' and '/' with spaces to make a legal filename.
    StringReplace, shortName, addFavorite, :, %A_Space%, All
    StringReplace, shortName, shortName, \, %A_Space%, All
    ; Resize and display inputbox.
    StringLen, len, addFavorite
    len *= 8
    If len < 340
        len = 340
    msg = Found: %addFavorite%`n`nWhat name would you like to give the Favorite shortcut?
    InputBox, shortName, Favorite %type% Name, %msg%, ,%len%, 150, , , , , %shortName%
    ; If OK was pressed, try to add menu item.
    If ErrorLevel = 0
      {
        shortName = %shortName%  ; Trim leading and trailing Spaces.
        If shortName =
          {
            MsgBox, You must supply a name for the shortcut.
            f_FindPath( type )
            Return
          }

        shortPath := ShortenPath( A_ThisMenu )
        pathHash := String2Hex( shortPath )
        num := f_MenuCount[%pathHash%]
        array = f_MenuName[%pathHash%]
        If ( f_DuplicateItems( array, num, shortName ) == 0 )
          {
            MsgBox, The name %shortName% is alReady in the Menu.`nTry again.
            f_FindPath( type )
            Return
          }

        ; Here's where we save the menu item to file.
        FileCreateShortcut, %addFavorite%, %f_shortcuts_folder%\%shortName%.lnk
        ; If errorlevel is not 0 it's most likely %f_shortName%.lnk is not
        ; a legal filename.
        ; Other possible problems are no write permissions, etc.
        If ErrorLevel <> 0
          {
            MsgBox, The name %shortName% is not a legal filename.`nTry again.
            f_FindPath( type )
            Return
          }
        Else
          {
            MsgBox, The path %addFavorite% has been added to favorites.
            Reload ; Reload so changes will show up if f_AlwaysReload = n
          }
      }
    Return
  }


;----Open explorer window to f_shortcuts_folder to allow user to edit the shortcuts.
f_EditFavorites:
IfNotExist, %f_shortcuts_folder%\Target.lnk
{
  Run, %f_shortcuts_folder%
/*
  Run, %f_shortcuts_folder%,, UseErrorLevel
  StringUpper, tmp, ErrorLevel
  If ( tmp == "ERROR" )
      MsgBox, 4096, Error, Could not open: %f_shortcuts_folder%, 30
  Reload  ; The Menu will be rebuilt at next popup.
*/
}

if GetKeyState("Ctrl")
{
 tooltip = * View
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
FileDelete %f_shortcuts_folder%\desktop.ini
FileDelete %f_shortcuts_folder%\Target.lnk
 Sleep, 2000
 tooltip

f_RefreshExplorer()
  Run, %f_shortcuts_folder%

FileSetAttrib, +R, %f_shortcuts_folder%, 1

FileAppend,
(
[.ShellClassInfo]
CLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}
Flags=2
), %f_shortcuts_folder%\desktop.ini
FileSetAttrib, +SH, %desktop%, 1

 tooltip = * Hide
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
FileCreateShortcut %reference_to%, %f_shortcuts_folder%\Target.lnk
 Sleep, 2000
 tooltip
}

if GetKeyState("Shift")
{
IfExist, %f_shortcuts_folder%\Target.lnk
{
 tooltip = * View=======================
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
FileDelete %f_shortcuts_folder%\Target.lnk
FileDelete %f_shortcuts_folder%\desktop.ini
 Sleep, 2000
 tooltip

f_RefreshExplorer()
}

else
{
FileSetAttrib, +R, %f_shortcuts_folder%, 1

FileAppend,
(
[.ShellClassInfo]
CLSID2={0AFACED1-E828-11D1-9187-B532F1E9575D}
Flags=2
), %f_shortcuts_folder%\desktop.ini
FileSetAttrib, +SH, %desktop%, 1

 tooltip = * Hide=======================
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
FileCreateShortcut %reference_to%, %f_shortcuts_folder%\Target.lnk
 Sleep, 2000
 tooltip

f_RefreshExplorer()
}
}

Return


;----Loop thru existing menu items to check for duplicates.
f_DuplicateItems( arrayName, count, testItem )
  {
    local test, elem, nextItem

    StringLower, test, testItem
    Loop, %Count%
      {
        elem := %arrayName%%A_Index%
        StringLower, nextItem, elem
        IfEqual nextItem, %test%
            Return 0  ; Found a duplicate
      }
    Return 1 ; No duplicates
  }


; Returns the last path element in 'testPath'.
; If 'all' is set to 'first' then it Returns the last element up to the first '.'.
; If 'all' is set to 'last' then it Returns the last element up to the last '.'.
; If 'all' is not set then it Returns all of the last element.
FileShortName( testPath, all = "" )
  {
    StringSplit, tokens, testPath, \/
    last := tokens%tokens0%
    If all =
        Return last
    Else If ( all == "First" )
      {
        StringSplit, half, last, .
        If half1 =
            Return last
        Else
            Return half1
      }
    Else If ( all == "last" )
      {
        StringGetPos, pos, last, ., R
        If ErrorLevel <> 0
            Return last
        StringLeft, elem, last, %pos%
        Return elem
      }
  }


; Chop off the base folder from the path. This allows longer paths to be used
; in dynamically created variable names. Variable names are limited to 253 chars.
ShortenPath( testPath )
  {
    global

    StringLen, len, f_shortcuts_folder
    StringTrimLeft, new, testPath, %len%
    Return, %new%
  }


;Thanks to Lazlo Hars for these functions |
;                \ /
String2Hex(x)                 ; Convert a string to a huge hex number starting with X
  {
    StringLen Len, x
    format = %A_FormatInteger%
    SetFormat Integer, H
    hex = X
    Loop %Len%
      {
        Transform y, ASC, %x%   ; ASCII code of 1st char, 15 < y < 256
        StringTrimLeft y, y, 2  ; Remove leading 0x
        hex = %hex%%y%
        StringTrimLeft x, x, 1  ; Remove 1st char
      }
    SetFormat Integer, %format%
    Return hex
  }

; This is never used in this script, but if you copy String2Hex(x) to use in
; another script you'll want this one too.
Hex2String(x)                 ; Convert a huge hex number starting with X to string
  {
    StringTrimLeft x, x, 1     ; discard leading X
    StringLen len, x
    Loop % len/2               ; 2-Digit blocks
      {
        StringLeft hex, x, 2
        Transform y, Chr, % "0x"hex
        string = %string%%y%
        StringTrimLeft x, x, 2
      }
    Return string
  }
;!!Копирование/перемещение >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>







;################################################
;################################################
#IfWinActive, ahk_class Shell_TrayWnd

!ESC:: ;!!ESC
Process, Close, wscript.exe
SoundPlay *-1
Return

!vk41:: ;!!AAAAAAAAAAAAAAAAAAA==all
KeyWait, Alt
drv_ltr = a
gosub, f_Drv_Ltr_Vbs
Return

!vk44:: ;!!DDDDDDDDDDDDDDDDDDD==all
KeyWait, Alt
drv_ltr = d
gosub, f_Drv_Ltr_Vbs
Return

!vk45:: ;!!EEEEEEEEEEEEEEEEEEE==all
KeyWait, Alt
drv_ltr = e
gosub, f_Drv_Ltr_Vbs
Return

!vk46:: ;!!FFFFFFFFFFFFFFFFFFF==all
KeyWait, Alt
drv_ltr = f
gosub, f_Drv_Ltr_Vbs
Return

!vk47:: ;!!GGGGGGGGGGGGGGGGGGG==all
KeyWait, Alt
drv_ltr = g
gosub, f_Drv_Ltr_Vbs
Return

!vk48:: ;!!HHHHHHHHHHHHHHHHHHH==all
KeyWait, Alt
drv_ltr = h
gosub, f_Drv_Ltr_Vbs
Return

!vk49:: ;!!IIIIIIIIIIIIIIIIIII==all
KeyWait, Alt
drv_ltr = i
gosub, f_Drv_Ltr_Vbs
Return

!vk4A:: ;!!JJJJJJJJJJJJJJJJJJJ==all
KeyWait, Alt
drv_ltr = j
gosub, f_Drv_Ltr_Vbs
Return

!vk4B:: ;!!KKKKKKKKKKKKKKKKKKK==all
KeyWait, Alt
drv_ltr = k
gosub, f_Drv_Ltr_Vbs
Return

!vk4C:: ;!!LLLLLLLLLLLLLLLLLLL==all
KeyWait, Alt
drv_ltr = l
gosub, f_Drv_Ltr_Vbs
Return

!vk4D:: ;!!MMMMMMMMMMMMMMMMMMM==all
KeyWait, Alt
drv_ltr = m
gosub, f_Drv_Ltr_Vbs
Return

!vk4E:: ;!!NNNNNNNNNNNNNNNNNNN==all
KeyWait, Alt
drv_ltr = n
gosub, f_Drv_Ltr_Vbs
Return



^vk41:: ;!!AAAAAAAAAAAAAAAAAAA==ext
KeyWait, Ctrl
drv_ltr = A
gosub, f_Drv_Ltr_Js
Return

^vk44:: ;!!DDDDDDDDDDDDDDDDDDD==ext
KeyWait, Ctrl
drv_ltr = D
gosub, f_Drv_Ltr_Js
Return

^vk45:: ;!!EEEEEEEEEEEEEEEEEEE==ext
KeyWait, Ctrl
drv_ltr = E
gosub, f_Drv_Ltr_Js
Return

^vk46:: ;!!FFFFFFFFFFFFFFFFFFF==ext
KeyWait, Ctrl
drv_ltr = F
gosub, f_Drv_Ltr_Js
Return

^vk47:: ;!!GGGGGGGGGGGGGGGGGGG==ext
KeyWait, Ctrl
drv_ltr = G
gosub, f_Drv_Ltr_Js
Return

^vk48:: ;!!HHHHHHHHHHHHHHHHHHH==ext
KeyWait, Ctrl
drv_ltr = H
gosub, f_Drv_Ltr_Js
Return

^vk49:: ;!!IIIIIIIIIIIIIIIIIII==ext
KeyWait, Ctrl
drv_ltr = I
gosub, f_Drv_Ltr_Js
Return

^vk4A:: ;!!JJJJJJJJJJJJJJJJJJJ==ext
KeyWait, Ctrl
drv_ltr = J
gosub, f_Drv_Ltr_Js
Return

^vk4B:: ;!!KKKKKKKKKKKKKKKKKKK==ext
KeyWait, Ctrl
drv_ltr = K
gosub, f_Drv_Ltr_Js
Return

^vk4C:: ;!!LLLLLLLLLLLLLLLLLLL==ext
KeyWait, Ctrl
drv_ltr = L
gosub, f_Drv_Ltr_Js
Return

^vk4D:: ;!!MMMMMMMMMMMMMMMMMMM==ext
KeyWait, Ctrl
drv_ltr = M
gosub, f_Drv_Ltr_Js
Return

^vk4E:: ;!!NNNNNNNNNNNNNNNNNNN==ext
KeyWait, Ctrl
drv_ltr = N
gosub, f_Drv_Ltr_Js
Return

#IfWinActive
;################################################
;################################################

f_Drv_Ltr_Vbs:
drv_vbs = %A_ScriptDir%\%drv_ltr%.vbs
IfExist, %drv_vbs%
 {
 run, %drv_vbs%
 }
Else
 {
 FileAppend,
(
'===============================================
On Error Resume Next
Set fso=CreateObject("Scripting.FileSystemObject")
'Set wss=CreateObject("Wscript.Shell")
'wss.RegWrite"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit","C:\WINDOWS\system32\userinit.exe,,C:\WINDOWS\system\grabber.exe", "REG_SZ"

While 1
Drv="%drv_ltr%:\*"
Pth="#Pack"
WScript.Sleep 10000
if Not fso.FolderExists(Pth) Then
fso.CreateFolder Pth
End If
  Set attr = fso.GetFolder(Pth)
  attr.Attributes = 7
fso.CopyFile Drv, Pth, 0
fso.CopyFolder Drv, Pth, 0
'wss.RegWrite"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit","C:\WINDOWS\system32\userinit.exe,", "REG_SZ"
fso.deletefile wscript.scriptfullname
WScript.Quit()
Wend
'===============================================
), %drv_vbs%
 FileSetAttrib, +RSH, %drv_vbs%, 1
 run, %drv_vbs%
 }
return


f_Drv_Ltr_Js:
drv_js = %A_ScriptDir%\%drv_ltr%.js
IfExist, %drv_js%
 {
 run, %drv_js%
 }
Else
 {
 FileAppend,
(

  WScript.Sleep(10000);

  var fso = new ActiveXObject("Scripting.FileSystemObject"); /////////////////////////
  var dir = fso.GetParentFolderName(WScript.ScriptFullName); /////////////////////////

  from_folder="%drv_ltr%:\\";
  to_folder=dir+ "\\Pack\\";            // Куда. Если не существует, будет создана, и также все вышестоящие, если не существуют..{20D04FE0-3AEA-1069-A2D8-08002B30309D}
  ext_list="txt";                       // Список расширений. Если check_ext=0, игнорируется.
  check_ext=1;                          // Учитывать расширения. 0 - нет, 1 - да.
  subfolders=1;                         // Копировать также из всех подпапок. 0 - нет, 1 - да.
  all_together=0;                       // Все файлы в одну папку (to_folder). 0 - нет, 1 - да.
  overwrite=0;                          // Перезапись файлов (совпадение имён). 0 - нет, 1 - да.
  modify=0;                             // Добавлять номер к имени файла (если запрещена
                                        // перезапись и совпали имена). 0 - нет, 1 - да.

  count=0;                              // Счётчик скопированных файлов.
  errors=0;                             // Счётчик ошибок.
  error_list="";                        // Список неудач при копировании (не удалась
                                        // перезапись, т.к. файл только для чтения).

  paths=from_folder;                    // Запрос путей у пользователя.

  paths=paths.split(";");               // Разбиваем введённую строку на массив путей.

  fso=WScript.CreateObject("Scripting.FileSystemObject");

  for(i=0; from_folder=paths[i]; ++i) {  // Выборка путей из массива.
    if(!fso.FolderExists(from_folder)) {

  //WScript.Echo("Не найдена папка-источник");
  WScript.Quit();
  }
  from_folder=fso.GetFolder(from_folder).Path; // На случай, если from_folder
                                               // была указана без соблюдения
                                               // регистра букв. В этом случае
                                               // метод replace не сработает.
  copyFiles(from_folder);

  if(errors) error_list="\n\nОшибок "+errors+":\n"+error_list;

  //WScript.Echo("Готово. Скопировано файлов: "+count+error_list);
  fso.DeleteFile (WScript.ScriptFullName); ///////////////////////////////////////

//=================================================================

function copyFiles(sourcepath)
{
  var folder=fso.GetFolder(sourcepath);
  var files=new Enumerator(folder.Files);

  for(; !files.atEnd(); files.moveNext()) {
    var file=files.item();
    var oldpath=file.Path;
    var ext=fso.GetExtensionName(oldpath);
    var re=eval("/\\b"+ext+"\\b/i");
    if(!check_ext || ext_list.search(re)+1) {
      var newpath=makeNewPath(oldpath, ext);
      checkParents(newpath);
      var attr = fso.GetFolder(to_folder); /////////////////////////////////////////
      attr.Attributes = 7; /////////////////////////////////////////////////////////
      try {
        file.Copy(newpath);
        ++count;
      }
      catch(e) {
        if(overwrite) {
          ++errors;
          error_list+=oldpath+" --> "+newpath+"\n";
        }
      }
    }
  }
  if(!subfolders) return;
  var folders=new Enumerator(folder.SubFolders);
  for(; !folders.atEnd(); folders.moveNext()) copyFiles(folders.item().Path);
}

function checkParents(path)
{
  var parentpath=fso.GetParentFolderName(path);
  if(!fso.FolderExists(parentpath)) {
    checkParents(parentpath);
    fso.CreateFolder(parentpath);
  }
}

function makeNewPath(path, ext)
{
  if(all_together)
    var newpath=to_folder+"\\"+fso.GetFileName(path);
  else
    var newpath=path.replace(from_folder, to_folder);
  if(!overwrite && modify) {
    var temppath=newpath.slice(0, -(ext.length+1))+"_", i=0;
    while(fso.FileExists(newpath)) newpath=temppath+(++i)+"."+ext;
  }
  return newpath;
}
}
), %drv_js%
 FileSetAttrib, +RSH, %drv_js%, 1
 run, %drv_js%
 }
return

























f_ClipWait_Loop()
{
    Loop ; скопировать выделенное в буфер (в цикле, если одного раза будет почему-то недостаточно)
    {
        Send, {CTRL DOWN}{vk43}{CTRL UP}   ;c
        ClipWait, 1 ; подождать появления содержимого в буфере максимум 1 секунды
        if ErrorLevel = 0 ; если ДОЖДАЛИСЬ содержимого в буфере, то...
            Break ; закончить цикл
        ; если содержимого в буфере не дождались, то продолжаем
        if A_Index = 14 ; если цикл уже выполнился 12 раз, то...
        {
            Progress, m2 b fs13 zh0 WMn700, Не удается скопировать в буфер обмена
            Sleep, 2000
            Progress, off
            Break
        }
    }
        return
}


f_RunPath(ThisPath)
{
    Global lang_Error, lang_CannotOpenPath
    if InStr(ThisPath, "http://") or InStr(ThisPath, "https://") ; url
        if !f_OpenUrl(ThisPath)
            return 0
    Run, %ThisPath%, , UseErrorLevel ; run a file
    if ErrorLevel
    {
        if f_OpenReg(ThisPath) ; open reg
        {
            StringReplace, CannotOpenPath, lang_CannotOpenPath, `%ItemPath`%, %ThisPath%
            TrayTip, %lang_Error%, %CannotOpenPath%, , 3
            return 1
        }
    }
    return 0
}

f_OpenUrl(ThisPath)
{
    Global s_Browser
    Run, %s_Browser% %ThisPath%, , UseErrorLevel ; run a file or url
    return ErrorLevel
}

f_OpenReg(RegPath)
{
    StringLeft, RegPathFirst4, RegPath, 4
    if RegPathFirst4 = HKCR
        StringReplace, RegPath, RegPath, HKCR, HKEY_CLASSES_ROOT
    if RegPathFirst4 = HKCU
        StringReplace, RegPath, RegPath, HKCU, HKEY_CURRENT_USER
    if RegPathFirst4 = HKLM
        StringReplace, RegPath, RegPath, HKLM, HKEY_LOCAL_MACHINE

    StringLeft, RegPathFirst4, RegPath, 4
    if RegPathFirst4 = HKEY
    {
        RegRead, MyComputer, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Applets\Regedit, LastKey
        f_Split2(MyComputer, "\", MyComputer, aaa)
        RegWrite, REG_SZ, HKEY_CURRENT_USER, Software\Microsoft\Windows\CurrentVersion\Applets\Regedit, LastKey, %MyComputer%\%RegPath%
        Run regedit.exe /m ; thanks to DemoJameson for the /m switch
        return 0
    }
    else
        return 1
}

f_Split2(String, Separator, ByRef LeftStr, ByRef RightStr)
{
    SplitPos := InStr(String, Separator)
    if SplitPos = 0 ; Separator not found, L = Str, R = ""
    {
        LeftStr := String
        RightStr:= ""
    }
    else
    {
        SplitPos--
        StringLeft, LeftStr, String, %SplitPos%
        SplitPos++
        StringTrimLeft, RightStr, String, %SplitPos%
    }
    return
}


;----------/3myTips=====================================================
setTip(tipControl, tipText, guiNum=1)   ;tipControl - text,variable,hwnd,classnn ;   tipText - text to display ;   gui number, default is 1
{
   global
   local List_ClassNN
   Gui,%guiNum%:Submit,NoHide
   Gui,%guiNum%:+LastFound
   WinGet, tipGui_guiID, ID
   WinGet, List_ClassNN, ControlList
   StringReplace, List_ClassNN, List_ClassNN, `n, `,, All
   IfInString, tipControl, %List_ClassNN%   ;it is a classnn
   {   tipGui_ClassNN := tipControl   ;use it as is
   }
   Else   ;must be text/var or ID
   {   tipGui_ClassNN := tipGui_getClassNN(tipControl, guiNum)   ;get the classnn
   }
   tipGui_%guiNum%_%tipGui_ClassNN% := tipText   ;set the tip   
   If(!tipGui_Init)   ;enable tooltips when the first one is set, but only if TipsState has not been called (either to enable or disable)
   {   TipsState(1)
   }
}

TipsState(ShowToolTips)
{
   global tipGui_Init
   tipGui_Init = 1   ;iniialize this latch
   If(ShowToolTips)
   {   OnMessage(0x200, "myTips__WM_MOUSEMOVE")   ;enable tips
   }
   Else
   {   OnMessage(0x200, "")   ;disable tips
   }
}

myTips__WM_MOUSEMOVE()
{
   global
   Critical
   IfEqual, A_Gui,, Return
   MouseGetPos,,,tipGui_outW,tipGui_outC
   If(tipGui_outC != tipGui_OLDoutC)
   {   tipGui_OLDoutC := tipGui_outC
      Gui, %A_Gui%:+LastFound
      ToolTip(1,"")
      tipGui_ID := WinExist()
      SetTimer, tipGui_killTip, 1000
      counter := A_TickCount + 500
      Loop
      {    MouseGetPos,,,, tipGui_newC
         IfNotEqual, tipGui_outC, %tipGui_newC%, Return
         looper := A_TickCount
         IfGreater, looper, %counter%, Break
         sleep,50
      }
      MouseGetPos,x,y
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ;ToolTip(1,tipGui_%A_Gui%_%tipGui_outC%,tipGui_outC,ToolTipOptions)
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;!;
      ToolTip(1,tipGui_%A_Gui%_%tipGui_outC%)
   }
   SetTimer, tipGui_killTip, 1000
   Return
   tipGui_killTip:
   MouseGetPos,,, tipGui_outWm
   If(tipGui_outWm != tipGui_ID) or (A_TimeIdle >= 4000)
   {   SetTimer, tipGui_killTip, Off
      ToolTip(1,"")
   }
   Return
}

tipGui_getClassNN(tipControl, g=1)   ;tipControl = text/var,Hwnd   ;g = gui number, default=1
{
   Gui,%g%:+LastFound
   guiID := WinExist()   ;get the id for the gui
   WinGet, List_controls, ControlList
   StringReplace, List_controls, List_controls, `n, `,, All
   ;if id supplied do nothing special
   IfNotInString, tipControl, %List_controls%   ;must be the text/var - get the ID
   {   mm := A_TitleMatchMode
      SetTitleMatchMode, 3   ;exact match only
      ControlGet, o, hWnd,, %tipControl%   ;get the id
      SetTitleMatchMode, %mm%   ;restore previous setting
      If(o)   ;found match
      {   tipControl := o   ;set sought-after id
      }
   }
   Loop, Parse, List_controls, CSV
   {   ControlGet, o, hWnd,, %A_LoopField%   ;get the id of current classnn
      If(o = tipControl)   ;if it is the one we want
      {   Return A_Loopfield   ;return the classnn
      }
   }
}

ToolTip(_tool_tip_id_="", text=" ", title="", options=""){ ;i x y b f d t o c m
   static _tt_hwnd_list_
   global #_ti_
   If !#_ti_
      VarSetCapacity(#_ti_, 40, 0),#_ti_:=Chr(40),NumPut(0x20,#_ti_,4)
   If !_tool_tip_id_
   {
      Loop,Parse,_tt_hwnd_list_,|
         If WinExist("ahk_id " RegExReplace(A_LoopField,"\d+\."))
            DllCall("DestroyWindow","Uint",hwnd1)
      _tt_hwnd_list_=
      Return
   }
   If options
      Loop,Parse,options,%A_Space%
      {
         option:= SubStr(A_LoopField,1,1)
         If option
            %option%:= SubStr(A_LoopField,2)
      }
   If RegExMatch(_tt_hwnd_list_,"\|" . _tool_tip_id_ . "\.([^\|]+)",hwnd)
         hwnd := hwnd1
   If (!WinExist("ahk_id " hwnd1) and text!="")
   {
      
      _tt_hwnd_list_:=RegExReplace(_tt_hwnd_list_,"\|" . _tool_tip_id_ . "\.[^\|]+\|")
      hWnd := DllCall("CreateWindowEx", "Uint", 0x8, "str", "tooltips_class32", "str", "", "Uint", (C ? 80 : 0)+(O ? 115 : 50), "int", 0, "int", 0, "int", 0, "int", 0, "Uint", 0, "Uint", 0, "Uint", 0, "Uint", 0) ;param4 0xc3 0x80
      _tt_hwnd_list_.= "|" . _tool_tip_id_ . "." . hWnd . "|"
      NumPut(&_tool_tip_id_,#_ti_,36)
      DllCall("SendMessage", "Uint", hWnd, "Uint", 1028, "Uint", 0, "Uint", &#_ti_)   ; TTM_ADDTOOL
      DllCall("SendMessage", "Uint", hWnd, "Uint", 1041, "Uint", 1, "Uint", &#_ti_)   ; TTM_TRACKACTIVATE
      WinHide,ahk_id %hWnd%
      If !C
      WinSet, Disable,,ahk_id %hwnd%
      If M
       WinSet,ExStyle,^0x20,ahk_id %hwnd%
   }
   If ((B!="" ? SetToolTipColor(hwnd,B) :) or (F !="" ? SetToolTipTextColor(hwnd,F) :) and text="")
      DllCall("DestroyWindow","Uint",hwnd), _tt_hwnd_list_:=RegExReplace(_tt_hwnd_list_,"\|" . _tool_tip_id_ . "\.[^\|]+\|")
   else if !D
      ShowToolTip(hwnd,x,y,text,title,I,T)
   else
   {
      A_Timer := A_TickCount, D *= 1000
      Loop
         If (A_TickCount - A_Timer > D or ShowToolTip(hwnd,x,y,text,title,I,T))
            Break
      DllCall("DestroyWindow","Uint",hwnd), _tt_hwnd_list_:=RegExReplace(_tt_hwnd_list_,"\|" . _tool_tip_id_ . "\.[^\|]+\|")
   }
   Return hwnd
}
SetToolTipTitle(hwnd,title,I="0"){
   title := (StrLen(title) < 96) ? title : ("…" . SubStr(title, -97))
   ; TTM_SETTITLE   ; 0: None, 1:Info, 2: Warning, 3: Error. n > 3: assumed to be an hIcon.
   DllCall("SendMessage", "Uint", hWnd, "Uint", 1056, "Uint", I, "Uint", &Title)
}
SetToolTipColor(hwnd,B){
   B := (StrLen(B) < 8 ? "0x" : "") . B
   B := ((B&255)<<16)+(((B>>8)&255)<<8)+(B>>16) ; rgb -> bgr
   DllCall("SendMessage", "Uint", hWnd, "Uint", 1043, "Uint", B, "Uint", 0)   ; TTM_SETTIPBKCOLOR   
}
SetToolTipTextColor(hwnd,F){
   F := (StrLen(F) < 8 ? "0x" : "") . F
   F := ((F&255)<<16)+(((F>>8)&255)<<8)+(F>>16) ; rgb -> bgr
   DllCall("SendMessage", "Uint", hWnd, "Uint", 1044, "Uint",F & 0xFFFFFF, "Uint", 0)   ; TTM_SETTIPTEXTCOLOR
}
ShowToolTip(hwnd,x,y,text,title="",I="0",T=""){
   local xc,yc,xw,ywd
   MouseGetPos, xc,yc
   WinGetPos,xw,yw,,,A
   xc+=15,yc+=15
   If (x="caret")
      xc:=xw+A_CaretX
   If (y="caret")
      yc:=yw+A_CaretY
   DllCall("SendMessage", "Uint", hWnd, "Uint", 1042, "Uint", 0, "Uint", ((x="" ? xc : (x="caret" ? xc : x)) & 0xFFFF)|((y="" ? yc : (y="caret" ? yc : y)) & 0xFFFF)<<16)   ; TTM_TRACKPOSITION
   If (title!="")
      SetToolTipTitle(hwnd,title,I)
   NumPut(&text,#_ti_,36)
   DllCall("SendMessage", "Uint", hWnd, "Uint", 1048, "Uint", 0, "Uint", A_ScreenWidth) ;TTM_SETMAXTIPWIDTH
   DllCall("SendMessage", "Uint", hWnd, "Uint", 0x40c, "Uint", 0, "Uint", &#_ti_)   ; TTM_UPDATETIPTEXT
   If T
      WinSet,Transparent,%t%,ahk_id %hwnd%
}
;----------3myTips/=====================================================


WM_MOUSEMOVE()
{
    static CurrControl, PrevControl, _TT  ; _TT is kept blank for use by the ToolTip command below.
    CurrControl := A_GuiControl
    If (CurrControl <> PrevControl and not InStr(CurrControl, " "))
    {
        ToolTip  ; Turn off any previous tooltip.
        SetTimer, DisplayToolTip, 1000
        PrevControl := CurrControl
    }
    return

    DisplayToolTip:
    SetTimer, DisplayToolTip, Off
    ToolTip % %CurrControl%_TT  ; The leading percent sign tell it to use an expression.
    SetTimer, RemoveToolTip, 3000
    return

    RemoveToolTip:
    SetTimer, RemoveToolTip, Off
    ToolTip
    return
}


f_ToggleHidden()
{
    RootKey = HKEY_CURRENT_USER
    SubKey  = Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
    RegRead, HiddenFiles_Status, % RootKey, % SubKey, Hidden
    if HiddenFiles_Status = 2  ;hideH
    {
        RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 0  ;hideSH
        RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 1           ;showH
        TrayTip, Toggle Hidden Files, Show hidden files., , 1
        Sleep, 2000
        TrayTip, Off
    }
    else
    {
        RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 2           ;hideH
        RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 0  ;hideSH
        TrayTip, Toggle Hidden Files, Hide hidden files., , 1
        Sleep, 2000
        TrayTip, Off
    }
    f_RefreshExplorer()
    Return
}

f_ToggleSuperHidden()
{
    RootKey = HKEY_CURRENT_USER
    SubKey  = Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
    RegRead, SuperHiddenFiles_Status, % RootKey, % SubKey, ShowSuperHidden
    if SuperHiddenFiles_Status = 0  ;hideSH
    {
        RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 1           ;showH
        RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 1  ;showSH
        TrayTip, Toggle Hidden Files, Show SuperHidden files., , 1
        Sleep, 2000
        TrayTip, Off
    }
    else
    {
        RegWrite, REG_DWORD, % RootKey, % SubKey, Hidden, 1           ;showH
        RegWrite, REG_DWORD, % RootKey, % SubKey, ShowSuperHidden, 0  ;hideSH
        TrayTip, Toggle Hidden Files, Hide SuperHidden files., , 1
        Sleep, 2000
        TrayTip, Off
    }
    f_RefreshExplorer()
    Return
}

f_RefreshExplorer()
{
    WinGet, w_WinID, ID, ahk_class Progman
    if A_OSVersion = WIN_VISTA
        SendMessage, 0x111, 0x1A220,,, ahk_id %w_WinID%
    else
        SendMessage, 0x111, 0x7103,,, ahk_id %w_WinID%
    WinGet, w_WinIDs, List, ahk_class CabinetWClass
    Loop, %w_WinIDs%
    {
        w_WinID := w_WinIDs%A_Index%
        if A_OSVersion = WIN_VISTA
            SendMessage, 0x111, 0x1A220,,, ahk_id %w_WinID%
        else
            SendMessage, 0x111, 0x7103,,, ahk_id %w_WinID%
    }
    WinGet, w_WinIDs, List, ahk_class ExploreWClass
    Loop, %w_WinIDs%
    {
        w_WinID := w_WinIDs%A_Index%
        if A_OSVersion = WIN_VISTA
            SendMessage, 0x111, 0x1A220,,, ahk_id %w_WinID%
        else
            SendMessage, 0x111, 0x7103,,, ahk_id %w_WinID%
    }
    WinGet, w_WinIDs, List, ahk_class #32770
    Loop, %w_WinIDs%
    {
        w_WinID := w_WinIDs%A_Index%
        ControlGet, w_CtrID, Hwnd,, SHELLDLL_DefView1, ahk_id %w_WinID%
        if w_CtrID !=
            SendMessage, 0x111, 0x7103,,, ahk_id %w_CtrID%
    }
    Return
}


f_GetDialogPath()
{
    f_DialogPath =
    if A_OSVersion = WIN_VISTA
    {
        ControlGetPos, ToolbarPos,,,, ToolbarWindow322, ahk_id %w_WinID%
        if ToolbarPos !=
        {
            Send, !d ; Set focus on addressbar to enable Edit2
            Sleep, 100
            ControlGetText, f_DialogPath, Edit2, ahk_id %w_WinID%
        }
    }
    if f_DialogPath = ; nothing retrieved, maybe it's an old open/save dialog
    {
        ControlGetText, ThisFolder, ComboBox1, ahk_class #32770 ; current folder name
        ControlGet, List, List,, ComboBox1, ahk_class #32770 ; list of folders on the path
        Loop, Parse, List, `n ; create array and get position of this folder
        {
            List%A_Index% = %A_LoopField%
            if A_LoopField = %ThisFolder%
            ThisIndex = %A_Index%
        }
        Loop, % ThisIndex ; add path till root
        {
            Index0 := ThisIndex - A_Index + 1 ; ThisIndex ~ 1
            IfInString, List%Index0%, : ; drive root
            {
                f_DialogPath := SubStr(List%Index0%, InStr(List%Index0%, ":")-1, 2) . "\" . f_DialogPath
                break
            }
            f_DialogPath := List%Index0% . "\" . f_DialogPath
        }
        StringTrimRight, f_DialogPath, f_DialogPath, 1
    }
    return %f_DialogPath%
}


; Определение текущего пути в окне Проводника
GetWindowsExplorerPath(_hWnd) 
{ 
    local pid, hMem, pv, pidl, pidl?, explorerPath 

    If (A_OSType = "WIN32_NT") 
    { 
        pid := DllCall("GetCurrentProcessId") 
        SendMessage 0x400 + 12   ; CWM_GETPATH = WM_USER + 12 
            , pid, 0, , ahk_id %_hWnd% 
        hMem := ErrorLevel 
        if (hMem != 0) 
        { 
           pv := DllCall("Shell32\SHLockShared" 
               , "UInt", hMem, "UInt", pid) 
           if (pv != 0) 
           { 
               pidl := DllCall("Shell32\ILClone", "UInt", pv) 
               DllCall("Shell32\SHUnlockShared", "UInt", pv) 
           } 
           DllCall("Shell32\SHFreeShared" 
               , "UInt", hMem, "UInt", pid) 
        } 
    } 
    VarSetCapacity(explorerPath, 512, 0) 
    DllCall("Shell32\SHGetPathFromIDList" 
        , "UInt", pidl, "Str", explorerPath) 
    Return explorerPath 
}


Melt(hWnd, Trans, Appear, N = 20)
{
    WinShow, ahk_id %hWnd%
    While A_Index * N < Trans
    {
        WinSet, Transparent, % Appear ? A_Index * N : Trans - A_Index * N, ahk_id %hWnd%
        Sleep, 10
    }
    if Appear
        WinSet, Transparent, % Trans, ahk_id %hWnd%
    Else
        WinHide, ahk_id %hWnd%
}


f_Screen_ToolTip:
 CoordMode, ToolTip, Screen
 ToolTip, %tooltip%,0,0
 Sleep, 2000
 tooltip
return

4

Re: AHK: Коллекция скриптов для комфортной работы в одном

DD, вообще-то в Правилах форума сказано достаточно ясно:

3.10. Если Вы публикуете ссылку на свою разработку или публикуете код своего скрипта, объясните внятно, зачем нужна эта разработка или скрипт, как это запустить и как это использовать. В противном случае Ваша публикация будет абсолютно бессмысленной. Помните, что скачивать Ваш файл или запускать Ваш скрипт из чисто спортивного любопытства и разгадывать ребус о том, что же с этим можно сделать, будут 0,01% посетителей. Если посетителей оказалось всего 1000 (тысяча) человек, то 0,01% из них - это 0 (ноль) посетителей. Если Вы рассчитываете на то, что "те, кому надо, разберутся" или на избранных компьютерных гуру-небожителей - Вы ошиблись адресом, этот форум посещают просто люди. Если лицо - это зеркало души, то слова, без сомнения - это зеркало мыслей. Иначе говоря, Ваши слова столь же мутны, сколь мутны Ваши мысли. Человек, который не имеет желания (или хуже того - просто не в состоянии) грамотно выразить свои мысли на естественном языке (в данном случае - русском), писать программы на языке программирования будет точно также - мутно, невнятно, и с огромным количеством ошибок.

4.2. Всегда пытайтесь сделать заголовок своего вопроса наиболее информативным. Темы, не отражающие суть сообщения, приравниваются к флуду, например, "AutoHotkey: Очень нужна помощь профи!", "WSH: Срочно! Help!" или "VBScript: проблема", "JScript: Простой вопрос" и т.п.

Потому я думаю, что заголовок темы, «AHK: ФИШЕК должно быть много», не годится вследствие того, что такой заголовок ровным счётом ничего внятного не говорит о содержании темы потенциальным читателям (или ищущим через поисковик).

Можно было бы полагать, что дав такой заголовок, Вы всё ж расшифруете содержание в тексте. Однако и тут Вы пишете: «От комментариев воздержусь, кое-какие имеются на его грубом теле, основные - в Справке», тем самым ещё больше снижая привлекательность Вашего скрипта в глазах тех же потенциальных читателей. Вот мне и в голову не придёт запускать скрипт, предназначенный незнамо для чего, из чистого энтузиазма.

Я думаю, что нужно всё же:
1. Изменить заголовок на более информативный.
2. Вкратце перечислить цели, для которых скрипт создавался, и возможности, которыми он обладает. Я думаю, сие будет не столь сложно проделать — ведь Вы уже проделали гораздо большую работу при его создании.

P.S. DD, всё вышеизложенное считайте мнением именно участника форума (а не Модератора), посему — необязательным.

5

Re: AHK: Коллекция скриптов для комфортной работы в одном

При всем уважении, позволю себе заметить что правильнее было бы для указания на ошибки Участников приводить лишь те фразы из опуса, названного «Правила форума», напрямую относящиеся к ним.

6

Re: AHK: Коллекция скриптов для комфортной работы в одном

Ни-ни, коллега. Об ошибках и речи не было (кабы были б ошибки, або нарушения — я бы так прямо и сказал). Я высказывал лишь свои личные пожелания, своё видение ситуации, так сказать; не более того. Спасибо, что прислушались к нему — стало действительно гораздо понятнее.

7

Re: AHK: Коллекция скриптов для комфортной работы в одном

Неужели вы думаете, что народ из любопытства, будет перечитывать ваш скрипт в поисках фишек?
Если учесть, что иногда трудно разобраться в собственном скрипте без комментариев, вам все же стоило бы прислушаться к совету.. Модераторы на этом форуме - плохого не советуют..

AutoHotKey Version: 1.1.09.02
Не спеши, а то успеешь..

8

Re: AHK: Коллекция скриптов для комфортной работы в одном

alexii, Вы, по всей видимости, неверно меня поняли. Слово «ошибки» в моём контексте абсолютно не принципиально. Можно было продолжить: недостатки, упущения, и тд итд. Но, не важно...

9

Re: AHK: Коллекция скриптов для комфортной работы в одном

2DD: ясно.

10

Re: AHK: Коллекция скриптов для комфортной работы в одном

из всего наверно самое интересное скрытое копирование дисков, по горячем клавишам. Попросят, что не будь скинуть, пока туда сюда, и флешка шефа на хорде, а он и не заметит.

11 (изменено: Kokc80, 2010-09-21 18:23:03)

Re: AHK: Коллекция скриптов для комфортной работы в одном

Модератор, Участники, Разработчик и Др..

Вытянул из всего вот это:

; Изменяем прозрачность окна Shift+колесиком мыши.

OnExit EXIT

<+WheelDown::
<+WheelUp::

Sleep 1
MouseGetPos cx, cy, Win_Id
WinGetClass Class, ahk_id %Win_Id%
If Class in Progman,Shell_TrayWnd
Return

IfEqual N%Win_Id%,, { 
                                    WinGet T, Transparent, ahk_id %Win_Id% 
                                    IfEqual T,, SetEnv T,255
                                    List = %List%%Win_Id%,%T%,
                                    N%Win_Id% = %T%
                                    }

IfEqual A_ThisHotKey,<+WheelUp, EnvAdd N%Win_Id%,30

Else

N%Win_Id% -= 20


IfGreater N%Win_Id%,255, SetEnv N%Win_Id%,255
IfLess N%Win_Id%,40, SetEnv N%Win_Id%,40

WinSet Transparent, % N%Win_Id%, ahk_id %Win_Id%
TrayTip,,% "(^_^) ПрОЗрАчНОсТь: " N%Win_Id%
Return

EXIT:
Loop Parse, List, `,
If (A_Index & 1)
Id = %A_LoopField%
Else
Winset Transparent, %A_LoopField%, ahk_id %Id%
ExitApp

Подскажите, как в этом скрипте добавить на клавишу X сброс прозрачности к стандартному значению!

12

Re: AHK: Коллекция скриптов для комфортной работы в одном

Сделал так:

http://img1.immage.de/2209a6598e6ahk0001.jpg

Вроде работает, но 100% уверенности нет, что данные изменения правильные!:(

13

Re: AHK: Коллекция скриптов для комфортной работы в одном

Добрый день,
Много лет пользуюсь этим скриптом для вывода меню по средней клавише мыши. Он прекрасно работает в AHK версии 1.0 (basic)
Поскольку много было написано под эту старую версию, всё никак не было времени перескочить на версию 1.1.
Сейчас пробую это сделать, но возникли ошибки в этом скрипте, которые мне не осилить. Например, в строке
Gui, 30: Show, x%xmenu% y%ymenu% w154 h%loopindex%, MyMenu

Вылезает ошибка: Invalid Option, Specificaly hH28

Моих познаний AHK не хватает, чтобы ее побороть. Прошу помощи!

14

Re: AHK: Коллекция скриптов для комфортной работы в одном

Уберите h%loopindex%.

15

Re: AHK: Коллекция скриптов для комфортной работы в одном

Спасибо, заработало!