<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; HTA & JScript: Extended Drop Target - Юникод-приемник файлов и папок]]></title>
	<link rel="self" href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=15779&amp;type=atom" />
	<updated>2020-11-09T22:34:26Z</updated>
	<generator>PunBB</generator>
	<id>http://forum.script-coding.com/viewtopic.php?id=15779</id>
		<entry>
			<title type="html"><![CDATA[Re: HTA & JScript: Extended Drop Target - Юникод-приемник файлов и папок]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143399#p143399" />
			<content type="html"><![CDATA[<p>На моем сайте доступна обновленная версия &quot;Extended Drop Target&quot; и новый продукт &quot;<strong>Enhanced Drop Target</strong>&quot;.</p><p>Обновление для &quot;Extended Drop Target&quot; включает небольшой прирост производительности во время инициализации приемника и его покидания без бросания на него файла или папки, а также увеличение доступной длины пользовательского описания продукта.</p><p>&quot;Enhanced Drop Target&quot; имеет ту же функциональность, что и &quot;Extended Drop Target&quot;, но в нем убрано ограничение на фон в виде изображения для Web Browser (истинного приемника файлов) за счет исключения пользовательского описания продукта.<br />Таким образом, улучшенная (enhanced) версия позволяет использовать пользовательское изображение в качестве фона истинного приемника, что обеспечивает плавный и незаметный переход на приемник при наведении.</p>]]></content>
			<author>
				<name><![CDATA[lifeflame]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=40203</uri>
			</author>
			<updated>2020-11-09T22:34:26Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143399#p143399</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: HTA & JScript: Extended Drop Target - Юникод-приемник файлов и папок]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143076#p143076" />
			<content type="html"><![CDATA[<p>Дальнейшее исследование позволило устранить возможное мерцание плитки приложения на панели задач во время его запуска.<br />Обновленную версию скрипта вы можете найти на моем сайте.<br />Подробности о возникновении мерцания разобраны в теме <a href="http://forum.script-coding.com/viewtopic.php?id=15788">HTA &amp; JScript: HTA silent stop and close - тихая остановка и закрытие</a>.</p>]]></content>
			<author>
				<name><![CDATA[lifeflame]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=40203</uri>
			</author>
			<updated>2020-11-01T13:26:47Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143076#p143076</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[HTA & JScript: Extended Drop Target - Юникод-приемник файлов и папок]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=143022#p143022" />
			<content type="html"><![CDATA[<p>Вот мы и подошли вплотную к интерфейсной составляющей HTML приложения <a href="http://forum.script-coding.com/viewtopic.php?id=15725">&quot;Resource Extractor&quot;</a>.</p><p>Речь пойдет о встроенной поддержке drag and drop (перетаскивания и бросания) файлов и папок в окно HTA.</p><p><strong>Вступление. Что сейчас известно о drag and drop в HTA.</strong><br /></p><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><p>Стоит отметить, что в HTA с поддержкой функциональности drag and drop для файлов и папок в окно, на первый взгляд, все выглядит достаточно безнадежно - по крайней мере таких примеров мне встретить не удалось.</p><p>Уточню еще раз, что ни о каком HTML5 говорить здесь не приходится, а о сторонних ActiveX объектах Windows ничего не знает: их нужно устанавливать и регистрировать, что выходит за рамки данной темы.</p><p>Чаще всего предлагается, как после манипуляций с реестром можно добиться, чтобы HTML приложение принимало на вход файлы и папки, брошенные на его значок.<br />Аналогичным образом работают скрипты с хостами WScript и CScript.<br />Неприятности такого подхода - стороннее вмешательство, либо изменение системных настроек напрямую, отсутствие UI для данной операции, тогда как задумка HTA уходит в интерактивность посредством пользовательского интерфейса, и в довершение WScript и CScript, как мне удалось убедиться, не поддерживают пути после drag and drop на Юникоде.</p><p>Удавалось также встречать экперименты drag and drop на textarea, но там все ограничивается текстовыми файлами.</p></div></div><p><strong>Дальше в лес - больше дров. Проблемы Web Browser, JScript и VBScript.</strong><br /></p><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><p>Единственный известный мне встроенный в любую версию Windows, начиная с XP (возможно и 2000), ActiveX объект с поддержкой drag and drop файлов и папок это Web Browser.</p><p>Есть у Web Browser такое интересное свойство как &quot;RegisterAsDropTarget&quot; - оно-то и позволяет превратить его в приемник файлов и папок.<br />А дальше сталкиваемся с тем, что, во-первых, Web Browser дает обратную связь с собой только через свои события, а во-вторых, обработка этих событий находится под большим вопросом.</p><p>Казалось бы, отменить событие &quot;BeforeNavigate2&quot; и взять с него путь брошенного на приемник файла или папки - вот и вся задача. Но не тут-то было.</p><p>VBScript умеет ловить события и отменять их для runtime-объекта, но беспомощен для объекта, представленного в виде HTML-ноды, так как не предоставляет в этом случае корректных методов для обработки событий.<br />JScript умеет ловить события для объекта, представленного в виде HTML-ноды, но не может отменять их в силу ограничения на передачу объектов по ссылке.</p><p>Ко всему прочему, даже поймать событие &quot;BeforeNavigate2&quot; в Windows XP можно только для runtime-объекта и причем на VBScript, тогда как JScript его не увидит.<br />Анализ приводит к описаниям схожих проблем с &quot;BeforeNavigate2&quot; в Windows XP от Microsoft:</p><p>h t t p://support.microsoft.com/kb/311298/EN-US/ или h t t p://c-bit.net/kb/311298/EN-US/<br />и<br />h t t p://support.microsoft.com/kb/325079/EN-US/ или h t t p://c-bit.net/kb/325079/EN-US/</p><p>В описаниях перечислены другие платформы, но и желающих отправить отчет по HTA на эту тему, как представляется, было в то время немного. Таким образом, проблема c событием &quot;BeforeNavigate2&quot; в Windows XP осталась и в Service Pack 3.</p><p>Стоит отметить, что событие &quot;BeforeNavigate2&quot; уже ловится на VBScript и JScript как для runtime-объекта, так и для объекта, представленного в виде HTML-ноды, в Windows 7 и 10, что значительно позволяет сократить код по сравнению с обходом данной проблемы.</p><p>Глубокое исследование показало, что все эти проблемы можно обойти.</p></div></div><p><strong>Создание компонента drag and drop.</strong></p><p>Проблемы удалось обойти за счет жесткой переинициализации Web Browser с предшествующим ей разрушением объекта.<br />При этом стоит отметить, что от разрушенного Web Browser, по всей видимости, остаются потоки в памяти, которые временно блокируют изменение обработанных им файлов сторонними программами до завершения скрипта.<br />Но это ложка дегтя в бочке меда, так как drag and drop файлов и папок в окно HTA да и еще с поддержкой путей на Юникоде оказывается возможным встроенными средствами.</p><p>Дальше мне пришлось столкнуться с анализом череды большого количества событий Web Browser, которые отличаются и количеством, и структурой, и временем появления, и порядком их возникновения на разных версиях Windows.<br />Тем не менее, я поставил себе цель обеспечить поддержку drag and drop файлов и папок в окно HTA для Windows XP.</p><p>Глубокое исследование позволило совместить всю эту цепь событий в единое целое.<br />В результате получился компонент &quot;<strong>Extended Drop Target</strong>&quot;, поддерживающий drag and drop файлов и папок в окно HTA как для Windows XP, так и для Windows 7 и 10 (поддержка других версий ожидается, но не тестировалась).</p><p>Данная работа представляет собой расширенную, доработанную и настраиваемую под пользователя версию, представленную в виде уединенного компонента, возвращаемого функцией &quot;createDropTarget&quot;, который можно поместить в любое место дерева DOM определенного окна с передачей на вход всех настроек в виде стилей, сообщений, функций обработки данных и ошибок.</p><p>Поддерживается и графика - при желании можно установить изображения в качестве фона.</p><p>Со всеми возможностями можно ознакомиться подробнее ниже.</p><p><strong>Скриптовый пример имеет следующие специальные возможности:</strong><br /></p><div class="fancy_spoiler_switcher"><div class="fancy_spoiler_switcher_header" data-lang-open="открыть спойлер" data-lang-close="скрыть спойлер"><strong>+</strong>&nbsp;открыть спойлер</div><div class="fancy_spoiler"><ul><li><p>не требует установки какого-либо стороннего программного обеспечения и поддерживает любую версию Windows, начиная с XP (возможно и 2000) с определенными ActiveX объектами, не запрещенными по умолчанию;</p></li><li><p>полностью написан на JScript в файле скриптового формата HTA и использует следующие ActiveX объекты: WScript.Shell, Scriptlet.TypeLib, WbemScripting.SWbemLocator, Shell.Application и Shell.Explorer.2, также известный как Microsoft Web Browser;</p></li><li><p>тестировался и адаптирован для Windows XP, Windows 7 и Windows 10;</p></li><li><p>не пишет каких-либо записей в реестр и не сохраняет каких-либо персональных данных на вашем жестком диске;</p></li><li><p>не выходит в сеть каким-либо способом;</p></li><li><p>поддерживает функциональность drag and drop для папок и файлов;</p></li><li><p>работает с именами входящих файлов на любой локали (поддержка символов Юникода в именах);</p></li><li><p>работает как с 32-битными, так и с 64-битными путями папок;</p></li><li><p>реализован как автономный компонент, который может быть вставлен в дерево DOM для определенного окна;</p></li><li><p>имеет множество возможностей, которые можно настроить, включая стили, принятием соответствующих входных параметров;</p></li><li><p>поддерживает показ дополнительного пользовательского описания продукта;</p></li><li><p>отправляет результаты в соответствующую функцию на входе;</p></li><li><p>разрешает неизвестные и пользовательские ошибки, передавая их в соответствующую функцию на входе;</p></li><li><p>имеет встроенную скрытую обработку ошибок в случае, если какой-либо метод устранения ошибок все еще недоступен;</p></li><li><p>может быть легко переведен на другие языки принятием входного блока сообщений;</p></li><li><p>поддерживает перенаправление drag and drop сообщений;</p></li><li><p>разделяет с основным скриптом функцию timeToHMSR для преобразования даты в представление в виде часов, минут, секунд и остатка (миллисекунд);</p></li><li><p>не требует какой-либо вложенной структуры для 64-битной части скрипта (новый код может быть просто добавлен в конец);</p></li><li><p>получает все необходимые паузы и фокусы для того, чтобы приложение оставалось поверх других окон при старте;</p></li><li><p>получает собственный PID, который может быть использован вновь позже;</p></li><li><p>не требует никаких системных путей или деклараций, которые могут отсутствовать в некоторых версиях Windows (например, &quot;SysNative&quot; неизвестен для Windows XP 32 bit).</p></li></ul></div></div><p><strong>Скриптовый пример демонстрирует:</strong><br /></p><ul><li><p>как скрыть HTA во время его динамического создания;</p></li><li><p>как запустить HTA в виде 64-битного процесса без использования системных путей или деклараций;</p></li><li><p>как получить скрытую остановку скрипта в HTA;</p></li><li><p>как поддерживать функциональность drag and drop для файлов и папок в HTA;</p></li><li><p>как бороться с подтвержденной проблемой &quot;BeforeNavigate2&quot; для Web Browser в Windows XP;</p></li><li><p>как решить подтвержденные проблемы с немедленным вызовом &lt;moveTo&gt; или &lt;resizeTo&gt; при старте в Windows XP</p></li><li><p>и как передать и использовать переменные среды для процесса, созданного с помощью WMI.</p></li></ul><p><strong>Работа с исходным кодом.</strong><br /></p><ol class="decimal"><li><p>Для запуска скриптового примера скопируйте его исходный код и сохраните его в текстовом файле, сменив его расширение на &quot;hta&quot;.</p></li><li><p>Запуск скриптового примера осуществляется двойным нажатием, как и в случае с обычной программой.</p></li></ol><p>Рекомендую использовать <a href="http://akelpad.sourceforge.net/en/download.php">AkelPad</a> для просмотра сохраненного исходного кода примера <span class="bbu">с правильными отступами</span>.</p><p>Вы можете использовать скриптовый пример на свое усмотрение, но, пожалуйста, оставьте комментарий с прямой ссылкой на <a href="https://tastyscriptsforfree.wix.com/page/scripts">tastyscriptsforfree.wix.com/page/scripts</a> в этом случае.</p><div class="codebox"><pre><code>&lt;script&gt;
/*
Extended Drop Target v1.1.2 (h t t p s://tastyscriptsforfree.wix.com/page/scripts)
Copyright 2017-2020 Vladimir Samarets. All rights reserved.
tastyscriptsforfree@protonmail.com

Release date: October 30, 2020.


Use this script sample entirely at your own risk.
This script sample is copyrighted freeware and I am not responsible for any damage or data loss it could unintentionally cause.
You may modify it but please leave a comment with direct link to https://tastyscriptsforfree.wix.com/page/scripts in that case.


*******
The purpose of this script sample:
the script sample is intendent to maintain drag and drop functionality for files and folders in HTA with support of 64 and 32 bit folder paths and Unicode file names.

*******
The script sample has the following special features:

it requires no third party software installation and supports any Windows version since XP with certain ActiveX objects not restricted by default;
it is entirely written in JScript in HTA scripting file format and uses the following ActiveX objects: WScript.Shell, Scriptlet.TypeLib, WbemScripting.SWbemLocator, Shell.Application
    and Shell.Explorer.2 also known as Microsoft Web Browser;
it was tested and adapted for Windows XP, Windows 7 and Windows 10;
it writes no registry values and stores no personal settings on your hard disk;
it doesn&#039;t access network in any way;
it supports drag and drop functionality for files and folders;
it works for input files named in any locale (Unicode names support);
it works both for 64 and 32 bit folder paths;
it is implemented as self-contained component that could be inserted into DOM tree for certain window;
it has many features that could be customized including styles by accepting corresponding input parameters;
it supports showing an additional custom product description;
it passes its results to corresponding input function;
it resolves unknown and custom errors by passing them into corresponding input function;
it has built-in silent catching of errors if certain error resolving method is still inaccessible;
it could be easily translated to other languages by accepting input block of messages;
it supports redirecting of drag and drop messages;
it shares with the main script &quot;timeToHMSR&quot; function for converting date to hours, minutes, seconds and remainder (milliseconds) notation;
it requires no nested structure for 64 bit instance scripting (new code can be simply added to the end);
it obtains all necessary pauses and focuses in order for the application to stay on top of other windows during its start;
it obtains the application PID which can be reused later;
it requires no system paths or declarations which could be absent in some versions of Windows (for example, &quot;SysNative&quot; is unknown for Windows XP 32 bit).

*******
The script sample demonstrates:

how to hide HTA while having it dynamically created;
how to launch HTA as 64 bit without using system paths or declarations;
how to obtain hidden stop for script in HTA;
how to maintain drag and drop functionality for files and folders in HTA;
how to deal with confirmed &quot;BeforeNavigate2&quot; issue of Web Browser in Windows XP;
how to deal with confirmed immediate &quot;moveTo&quot; or &quot;resizeTo&quot; issues at application start in Windows XP
and how to pass and use environment variables for process created by WMI.

*******
The script sample has the following current limitations:

maximum file size for processing based on Windows 7 and Windows 10 limitations is 3.99 GB (4,293,918,718 bytes);
all successfully processed files are treated as in use under any circumstances until the script is closed;
it is possible to set some image as a background for Web Browser but it is not currently supported because it ruins Extended Drop Target functionality;
a third party error is shown in Windows 7 and Windows 10 for dropped HTML files if they have errors in their scripts with &quot;async&quot; property;
an excessive Web Browser error is shown in case the folder path is valid no more.

*******
Basic documentation and articles I used:

&#039;VBScript Scripting Techniques: Environment Variables&#039; by Rob van der Woude
    (h t t p s://w w w.robvanderwoude.com/vbstech_data_environment.php);
&#039;Using Win32_ProcessStartup to change environment&#039; post by Rico Rosenlund
    (h t t p s://microsoft.public.scripting.wsh.narkive.com/hW1GURnH/using-win32-processstartup-to-change-environment);

&#039;WSH: exchanging data and objects between scripts - 2&#039; by Xameleon (March, 2011) in Russian
    (h t t p://forum.script-coding.com/viewtopic.php?id=5573);

&#039;VBScript Scripting Techniques: HTAs&#039; by Rob van der Woude
    (h t t p s://w w w.robvanderwoude.com/vbstech_hta.php);

&#039;InternetExplorer and WebBrowser objects&#039; by Ludogovskiy Aleksander in Russian
    (h t t p s://script-coding.com/WSH/WebBrowser.html);

&#039;Windows Script 5.6 Documentation&#039; (script56.chm) by Microsoft Corporation
    (h t t p s://w w w.microsoft.com/en-us/download/confirmation.aspx?id=2764);
&#039;MSDN&#039; related documentation by Microsoft Corporation
    (h t t p s://docs.microsoft.com/en-us/);

Windows XP BeforeNavigate2 issue:
&#039;BUG: The BeforeNavigate2 event of the WebBrowser control does not fire if hosted in a Visual Basic .NET 2002 application&#039;
on c-bit.net and support.microsoft.com (September 14, 2005)
    (h t t p://c-bit.net/kb/311298/EN-US/, h t t p://support.microsoft.com/kb/311298/EN-US/);
&#039;BUG: The BeforeNavigate2 Event of WebBrowser Control Does Not Fire If Hosted in a Visual C# .NET Application&#039;
on c-bit.net and support.microsoft.com (June 25, 2004)
    (h t t p://c-bit.net/kb/325079/EN-US/, h t t p://support.microsoft.com/kb/325079/EN-US/);

Windows XP moveTo and resizeTo issues:
&#039;&quot;Access is denied&quot; by executing .hta file with JScript on Windows XP x64&#039; discussion on stackoverflow.com (January 21, 2009)
    (h t t p s://stackoverflow.com/questions/464679/access-is-denied-by-executing-hta-file-with-jscript-on-windows-xp-x64);
&#039;Something strange with HTAs&#039; discussion on social.technet.microsoft.com (September 19, 2011)
    (h t t p s://social.technet.microsoft.com/Forums/officeocs/en-US/92bf1e76-ebd5-4462-bd52-533e69305a5c/something-strange-with-htas?forum=ITCG).

*******
Basic software I used:

AkelPad 4.9.8 by Aleksander Shengalts and Alexey Kuznetsov (as development environment)
    (h t t p://akelpad.sourceforge.net/en/download.php);
OLE/COM Object Viewer v2.10.059 (oleview.exe) by Charlie Kindel, Michael Nelson, and Michael Antonio (for documentation purposes).
*/

offscreenBuffering = true;                                                                                       //postpone the application window appearance till its UI is ready
var O = function(o){return new ActiveXObject(o);},
WSS = O(&#039;WScript.Shell&#039;),
env = WSS.Environment(&#039;Process&#039;),
head = document.documentElement.firstChild,                                                      //head
PID;                                                                                                                         //PID of 64 bit HTA instance

if(!env(&#039;is64bit&#039;))                                                                                                      //indicates whether the application is launched as 64 bit or not
{
    !function hide(e){try{moveTo(10000, 10000);}catch(e){try{hide();}catch(e){hide();}}}();                                  //hiding the application window
    head.insertBefore(document.createElement(&#039;&lt;hta:application showInTaskBar=0&gt;&#039;), head.firstChild);        //hiding the application in the Taskbar

    var WMI=                                                                                                            //a small library written by me for obtaining WMI instance, its common methods and properties
    {                                                                                                                           //below is a sample of creating a process with certain window shifts and environment variables
                                                                                                                                //and obtaining its &lt;ProcessId&gt; by using WMI
        SWL:new ActiveXObject(&#039;WbemScripting.SWbemLocator&#039;),
        PRMS:function(p)
        {
            var s = WMI.PS.SpawnInstance_();
            for(var i in p)
                s[i] = p[i];
            return s;
        },
        Create:function(c, s, d)
        {
            var CreateIn = WMI.CreateIn.SpawnInstance_();
            CreateIn.CommandLine = c;
            CreateIn.ProcessStartupInformation = s;
            CreateIn.CurrentDirectory = d;
            return WMI.PRC.ExecMethod_(&#039;Create&#039;, CreateIn).ProcessId;
        }
    };
    WMI.PRC = (WMI.WM = WMI.SWL.ConnectServer(&#039;.&#039;, &#039;root/cimv2&#039;)).Get(&#039;Win32_Process&#039;);
    WMI.PS = WMI.WM.Get(&#039;Win32_ProcessStartup&#039;);
    WMI.CreateIn = WMI.PRC.Methods_(&#039;Create&#039;).InParameters;

    var ID = O(&#039;Scriptlet.TypeLib&#039;).GUID.substr(0, 38),                                             //the unique ID obtaining
    EV = &#039;is64bit=&#039;+ID;                                                                                              //passing the unique ID to 64 bit HTA instance as an Environment variable
    for(var items = new Enumerator(env); !items.atEnd(); items.moveNext())
        EV += &#039;?&#039; + items.item();                                                                                  //obtaining all Environment variables for current process

    PID = WMI.Create                                                                                               //obtaining PID of 64 bit HTA instance
        (
            &#039;mshta &quot;&#039; + decodeURIComponent(location.pathname) + &#039;&quot;&#039;,                     //current path
            WMI.PRMS
            (
                {
                    X:10000, Y:10000,                                                                              //hiding the application window before it is shown in order to resize it smoothly
                    EnvironmentVariables:
                        EV.split(&#039;?&#039;)                                                                                      //obtaining an array of all Environment variables by using this approach is universal for different
                                                                                                                                //versions of Windows
                        /*
                        [                                                                                                       //another way to pass certain Environment variables
                            &#039;is64bit=&#039;+ID,                                                                              //indicates that the application is launched as 64 bit
                            &#039;SystemRoot=&#039;+env(&#039;SystemRoot&#039;),                                           //for start
                            &#039;SystemDrive=&#039;+env(&#039;SystemDrive&#039;),                                         //for hyperlinks
                            &#039;TEMP=&#039;+env(&#039;TEMP&#039;),                                                                //for &quot;mailto&quot; links
                            &#039;CommonProgramW6432=&#039;+env(&#039;CommonProgramW6432&#039;)     //for ADODB.Stream
                        ]
                        */
                }
            )
        );

    head.firstChild.insertAdjacentHTML(&#039;afterEnd&#039;, &#039;&lt;object id=&#039; + ID + &#039; PID=&#039; + PID +
        &#039; classid=clsid:8856F961-340A-11D0-A96B-00C04FD705A2&gt;&lt;param name=RegisterAsBrowser value=1&gt;&#039;);      //registering current HTA window in collection of windows
    showModalDialog(0, 0, &#039;dialogWidth:0;unadorned:1;&#039;);                                     //stopping the script and obtaining window focus for &quot;AppActivate&quot;
}

var w,dt=new Date();
head.insertBefore(document.createElement(&#039;&lt;hta:application contextMenu=no selection=no scroll=no&gt;&#039;), head.firstChild);      //adding custom HTA header dynamically
document.title=&#039;Extended Drop Target&#039;;
resizeTo(800, 400);
for(var ws = O(&#039;Shell.Application&#039;).Windows(), i = ws.Count; i -- &gt; 0;)
    if((w = ws.Item(i)) &amp;&amp; w.id == env(&#039;is64bit&#039;))
    {
        PID = w.PID;
        w.document.Script.WSS.AppActivate(PID);                                                                                                                            //using &quot;WScript.Shell&quot; in focus to activate
                                                                                                                                                                                                          //the application window of 64 bit HTA instance;
                                                                                                                                                                                                          //remember that &quot;WScript.Shell&quot; should be
                                                                                                                                                                                                          //in focus in order &quot;AppActivate&quot; to work properly
        break;
    }

document.write(&#039;&lt;body&gt;&#039;);                                                                                      //obtaining body
if(w &amp;&amp; w.id == env(&#039;is64bit&#039;))
    w.document.Script.close();                                                                                 //closing previous 32 bit HTA instance while being in safe focus

document.body.appendChild(document.createTextNode(&#039;Debug screen (for test purposes only):&#039;));
document.body.appendChild(document.createElement(&#039;br&#039;));
document.body.appendChild(document.createElement(&#039;&lt;textarea id=result cols=85 rows=5&gt;&#039;));
document.body.appendChild(document.createElement(&#039;p&#039;));
document.body.appendChild(document.createTextNode(&#039;Extended Drop Target:&#039;));
document.body.appendChild(document.createElement(&#039;br&#039;));

document.body.appendChild
(
    (
        function createDropTarget(doc, filesAllowed, foldersAllowed, dTStyle, hdFont, wMColor, dMColor, pMColor, eMColor, process, resolve, msg, dBgImage, bBgImage,
            description, redirect)
        {
            var dropTarget = doc.createElement(&#039;&lt;span style=&quot;&#039; + dTStyle + &#039;&quot;&gt;&#039;),

            ms = dropTarget.appendChild
            (
                doc.createElement(&#039;&lt;span style=&quot;width:100%;height:100%;padding:10px;overflow:hidden;&quot;&gt;&#039;)
            ),                                                                                                                  //message screen that hides Web Browser during dropped items processing

            WB = &#039;&lt;object classid=clsid:8856F961-340A-11D0-A96B-00C04FD705A2 style=&quot;width:100%;height:100%;&quot;&gt;&lt;param name=Location value=&quot;about:&lt;body bgColor=&#039; +
                dMColor + &#039; style=\&#039;width:100%;height:100%;position:absolute;margin:0px;border:0px;overflow:hidden;\&#039;&gt;&#039; + (description || &#039;&#039;) + &#039;&lt;script&gt;var b=document.body;&#039; +
                &#039;b.ondragenter=b.ondragover=b.onmouseenter=b.onmouseover=b.onmousemove=function(){clearTimeout(b);b=setTimeout(\&#039;location.reload();\&#039;,100);}&lt;\/script&gt;&quot;&gt;&#039;,
            processing = 1,                                                                                           //indicates whether a dropped item processing is started or not
            processed = 1,                                                                                            //indicates whether a dropped item is processed or not
            DBcatched = 1,                                                                                            //indicates whether DownloadBegin Web Browser event has been catched or not
            allowed,                                                                                                       //indicates whether drop target is allowed or not
            allowedText = (filesAllowed ? foldersAllowed ? msg[32] : msg[33] : foldersAllowed ? msg[34] : &#039;&#039;),      //&quot;Drop a file or folder here.&quot;
            WBTReset,                                                                                                  //timeout for Web Browser reset

            startProcessing = function(p)                                                                      //processing the item path received after item drop (item path)
            {
                clearTimeout(WBTReset);
                dropTarget.children[processed = 1].removeNode();
                createDropTarget();
                setTimeout(function()
                {
                    var delay = 0;
                    if(p)                                                                                                      //the item can be accessed
                    {
                        sM(msg[38] + p + &#039;&lt;/div&gt;&#039;, pMColor);                                              //show &quot;Processing&quot;
                        var dt = new Date(),                                                                         //date before processing
                        e;                                                                                                     //error ID
                        try{e = process(p);}catch(e){e = 43;}                                               //unknown error occured
                        dt = new Date() - dt;                                                                         //date after processing
                        delay += dt&gt;1000 ? 0 : 1000 - dt;
                        if(!e)                                                                                                 //no errors occured
                            setTimeout(function(){sM(msg[39] + createDropTarget.timeToHMSR(dt) + &#039; =-&lt;/div&gt;&#039;, pMColor);}, delay);       //show &quot;Processed in&quot;
                        else                                                                                                 //an error occured
                        {
                            var err;
                            try{resolve(e);}catch(err){;}
                            setTimeout(function(){sM(msg[39] + createDropTarget.timeToHMSR(dt) + &#039; =-&lt;/div&gt;&lt;br&gt;&#039; + msg[e], eMColor);}, delay);      //show &quot;Processed in&quot; with error
                            if(!redirect)
                                delay += 1000;
                        }
                    }
                    else                                                                                                     //the item can&#039;t be accessed
                    {
                        sM(msg[40] + msg[41] + allowedText + msg[42], eMColor);          //show &quot;The item is not a file or folder, can&#039;t be accessed or its size is too big.&quot;
                        delay += 1000;
                    }

                    sDM(delay + 1000);
                }, 1000);
            },

            setWBTReset = function(r)                                                                          //setting a timeout for Web Browser reset (reset)
            {
                if(!processing)
                {
                    processing = 1;
                    ms.style.display = &#039;&#039;;
                    if(r)
                        WBTReset = setTimeout(startProcessing, 1000);
                }
            },

            DB = function()                                                                                            //catching &quot;DownloadBegin&quot; Web Browser event
            {
                DBcatched = 1;
                setWBTReset(1);
            },

            STC = function(p)                                                                                         //catching &quot;StatusTextChange&quot; Web Browser event (item path)
            {
                setWBTReset(p);
                if(!processed &amp;&amp; /file:|&lt;/.test(p))
                {
                    if(/file:/.test(p))
                        startProcessing(filesAllowed ? decodeURIComponent(p).replace(/.+:((?:\/{3})|(?=\/{2}))(.+)...$/,&#039;$2&#039;).replace(/\//g,&#039;\\&#039;) : 0);
                    else if(/&lt;/.test(p))
                    {
                        if(!DBcatched)                                                                                  //indicates that drop target is leaved without drop
                        {
                            clearTimeout(WBTReset);
                            sM(msg[31] + allowedText + msg[35] + &#039;&lt;/div&gt;&#039;, dMColor, dBgImage);      //show &quot;Drop a file or folder here.&quot;
                            allowed = 1;
                            ms.style.display = &#039;&#039;;
                        }
                        else                                                                                                 //shortcuts with complex structure
                            startProcessing();
                    }
                }
            },

            NC2 = function(o, p)                                                                                     //catching &quot;NavigateComplete2&quot; Web Browser event (Web Browser object, item path)
            {
                if(!processed)
                    startProcessing(foldersAllowed &amp;&amp; typeof p == &#039;string&#039; &amp;&amp; p.match(/^[^:]/) ? p : 0);
            },

            NE = function()                                                                                             //catching &quot;NavigateError&quot; Web Browser event
            {
                if(!processed)
                    startProcessing();
            },

            sM = function(m, c, bgImage)                                                                      //show message (message, background or text color, background image)
            {
                if(dBgImage || bBgImage)
                {
                    if(bgImage)
                        ms.style.backgroundImage = &#039;url(&#039; + bgImage + &#039;)&#039;;
                    ms.style.color = c;
                }
                else
                    ms.style.backgroundColor = c;
                m = &#039;&lt;div style=&quot;font:&#039; + hdFont + &#039;;&quot;&gt;&#039; + m;
                if(!redirect)
                    ms.innerHTML = m;
                else
                    redirect(m);
            },

            sDM = function(delay)                                                                                 //show default message (delay)
            {
                setTimeout(function(){allowed = 1;}, delay);
                setTimeout(function(){if(allowed)sM((allowedText ? msg[31] + allowedText + msg[35] : msg[36]) + &#039;&lt;/div&gt;&#039;, dMColor, dBgImage);}, delay + 100);     //show &quot;Drop a file or folder
                                                                                                                                                                                                                                                             //here.&quot; or &quot;Drop Target is
            }                                                                                                                                                                                                                                                //disabled.&quot;

            sM(msg[30], wMColor, dBgImage);                                                             //show welcome message

            ms.ondragenter=function()
            {
                if(allowed &amp;&amp; (filesAllowed || foldersAllowed) &amp;&amp; !event.dataTransfer.getData(&#039;text&#039;))      //text dropping is not allowed
                {
                    event.dataTransfer.dropEffect=&#039;move&#039;;
                    return false;
                }
            }

            ms.ondragover = function()
            {
                if(allowed &amp;&amp; (filesAllowed || foldersAllowed) &amp;&amp; !event.dataTransfer.getData(&#039;text&#039;))      //text dropping is not allowed
                {
                    event.dataTransfer.dropEffect=&#039;move&#039;;
                    if(!Math.abs(event.x - this.x) &amp;&amp; !Math.abs(event.y - this.y))              //accepting only slow mouse motion
                    {
                        this.style.display = &#039;none&#039;;
                        DBcatched = allowed = processing = processed = 0;
                        sM(msg[37], dMColor, bBgImage);                                                 //show &quot;Analysing...&quot;
                    }
                    this.x = event.x;
                    this.y = event.y;
                    return false;
                }
            }

            !(createDropTarget = function()
            {
                dropTarget.insertAdjacentHTML(&#039;beforeEnd&#039;, WB);                                 //Web Browser reset is needed because its events can&#039;t be declined further in JavaScript,
                with(dropTarget.children[1])                                                                        //BeforeNavigate2 event has also a confirmed issue and can&#039;t be catched in Windows XP
                {                                                                                                                   //by default while VBScript provides no working methods to catch them for ActiveX objects
                    RegisterAsDropTarget = Silent = Offline = 1;                                         //represented as HTML nodes
                    attachEvent(&#039;DownloadBegin&#039;, DB);
                    attachEvent(&#039;StatusTextChange&#039;, STC);
                    attachEvent(&#039;NavigateComplete2&#039;, NC2);
                    attachEvent(&#039;NavigateError&#039;, NE);
                }
            })();

            createDropTarget.timeToHMSR = function(d)                                             //convert date to hours, minutes, seconds and remainder (milliseconds) notation (date)
            {
                var r = d % 3600000,
                h = d / 3600000 ^ 0,                                                                                 //hours
                m = r / 60000 ^ 0,                                                                                     //minutes
                s = r % 60000 / 1000 ^ 0;                                                                         //seconds
                r = d % 1000;                                                                                           //remainder (milliseconds)
                return ((h ? h + &#039;h&#039; : &#039;&#039;) + (m ? (h ? &#039; &#039; : &#039;&#039;) + m + &#039;m&#039; : &#039;&#039;) + (s ? (h || m ? &#039; &#039; : &#039;&#039;) + s + &#039;s&#039; : &#039;&#039;) + (r ? (h || m || s ? &#039; &#039; : &#039;&#039;) + r + &#039;ms&#039; : &#039;&#039;)) || &#039;0ms&#039;;
            },

            sDM(3000);                                                                                                  //postponing Web Browser access while it generates its events at start

            return dropTarget;
        }
        (
            //BEGIN of Extended Drop Target custom settings

            document,                                                                                                   //&quot;document&quot; object of certain window
            1,                                                                                                                 //indicates whether processing of files is allowed or not
            1,                                                                                                                 //indicates whether processing of folders is allowed or not
            &#039;width:350px;height:150px;border:2px blue solid;font:bold 10pt Arial;text-align:center;cursor:default;overflow:hidden;word-break:break-all;&#039;,       //drop target style
            &#039;bold 12pt Tahoma&#039;,                                                                                    //message header font
            &#039;yellow&#039;,                                                                                                       //welcome message background color if background image is not set or text color otherwise
            &#039;mediumaquamarine&#039;,                                                                                 //default message background color if background image is not set or text color otherwise
            &#039;limegreen&#039;,                                                                                                 //processing message background color if background image is not set or text color otherwise
            &#039;salmon&#039;,                                                                                                     //error message background color if background image is not set or text color otherwise

            function(p)                                                                                                   //data processing sample (file or folder path)
            {
                alert(&#039;Here goes data processing sample.\n\nProcessing:\n&#039; + p);
                //throw 1;                                                                                                 //unknown error occured
                //return 1;                                                                                                //certain error 1 occured
                //return &#039;error 2&#039;;                                                                                     //certain error 2 occured
                return 0;                                                                                                  //no errors
            },

            function(e)                                                                                                   //error resolving sample (error ID)
            {
                switch(e)
                {
                    case 1:
                        result.value = &#039;\nCertain error 1 is catched.&#039;;                                  //additional action sample for certain error 1
                        updateData1();                                                                                //built-in silent catching of errors if certain error resolving method is still inaccessible
                        break;
                    case &#039;error 2&#039;:
                        result.value = &#039;\nCertain error 2 is catched.&#039;;                                  //additional action sample for certain error 2
                        updateData2();                                                                                //built-in silent catching of errors if certain error esolving method is still inaccessible
                        break;
                    default:
                        result.value = &#039;\nAn unknown error is catched.&#039;;                             //additional action sample for an unknown error
                        sendEmail();                                                                                    //built-in silent catching of errors if certain error resolving method is still inaccessible
                        break;
                }
                file.Close();                                                                                              //built-in silent catching of errors if certain error resolving method is still inaccessible
            },

            {                                                                                                                   //list of all messages for Extended Drop Target
                30: &#039;Welcome!&lt;/div&gt;&lt;br&gt;Hello World!&#039;,                                                 //welcome message
                31: &#039;Drop a &#039;,                                                                                           //31, 32, 33, 34, 35 - &quot;Drop a file or folder here.&quot;
                32: &#039;file or folder&#039;,
                33: &#039;file&#039;,
                34: &#039;folder&#039;,
                35: &#039; here.&#039;,
                36: &#039;Drop Target is disabled.&#039;,
                37: &#039;-= Analysing... =-&lt;/div&gt;&#039;,
                38: &#039;-= Processing =-&lt;/div&gt;&lt;br&gt;&lt;div style=&quot;text-align:left;&quot;&gt;&#039;,
                39: &#039;-= Processed in &#039;,
                40: &quot;-= Can&#039;t be processed =-&lt;/div&gt;&lt;br&gt;&quot;,
                41: &#039;The item is not a &#039;,                                                                           //41, 32, 33, 34, 42 - &quot;The item is not a file or folder,&lt;br&gt;can&#039;t be accessed or its size is too big.&quot;
                42: &quot;,&lt;br&gt;can&#039;t be accessed or its size is too big.&quot;,
                43: &#039;An unknown error occured.&#039;,                                                            //unknown error message
                1: &#039;Certain error 1 occured.&#039;,                                                                   //certain error 1 message
                &#039;error 2&#039;: &#039;Certain error 2 occured.&#039;                                                         //certain error 2 message
                                                                                                                                //certain error # message
                                                                                                                                //certain error # message
                                                                                                                                //certain error # message
                                                                                                                                //...
            }

            //,&#039;C:\\Windows\\Web\\Screen\\img103.png&#039;                                                 //default background image or &quot;undefined&quot; (optional)
            //,&#039;C:\\Windows\\Web\\Screen\\img102.jpg&#039;                                                  //busy mode background image or &quot;undefined&quot; (optional)

            //,&#039;&lt;div style=\&#039;font:10pt Tahoma;padding:20px;\&#039;&gt;List of files supported by default:&lt;ul&gt;&lt;li&gt;Bitmap Files (*.bmp;*.dib)&lt;li&gt;JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)&lt;li&gt;GIF(*.gif)&lt;/ul&gt;&lt;/div&gt;&#039;
                                                                                                                                //description length depends on the message language or its actual bytes count or &quot;undefined&quot; (optional)

            //,function(m){result.value = m;}                                                                  //sample for receiving messages or &quot;undefined&quot; (optional)

            //END of Extended Drop Target custom settings
        )
    )
);

result.value = &#039;\nLoading time for 64 bit instance (if possible): &#039; + createDropTarget.timeToHMSR(new Date() - dt) + &#039;.&#039;;
moveTo(screen.availWidth / 2 - 400, screen.availHeight / 2 - 200);

/*
    some built-in in Windows 10 background samples:
    &#039;C:\\Windows\\Web\\Screen\\img103.png&#039;
    &#039;C:\\Windows\\Web\\Screen\\img102.jpg&#039;

    some built-in in Windows 7 background samples:
    &#039;C:\\Windows\\Web\\Wallpaper\\Nature\\img3.jpg&#039;
    &#039;C:\\Windows\\Web\\Wallpaper\\Landscapes\\img10.jpg&#039;

    some built-in in Windows XP background samples:
    &#039;C:\\WINDOWS\\Zapotec.bmp&#039;
    &#039;C:\\WINDOWS\\Soap Bubbles.bmp&#039;
*/

&lt;/script&gt;</code></pre></div><p><strong>Перевод &quot;Extended Drop Target&quot; на русский язык и примеры настроек.</strong></p><p>Все настройки &quot;Extended Drop Target&quot; находятся в разделе между &quot;//BEGIN of Extended Drop Target custom settings&quot; и &quot;//END of Extended Drop Target custom settings&quot;.</p><p>Для перевода на русский язык замените блок английских сообщений на блок русских сообщений:</p><div class="codebox"><pre><code>
        {
            30: &#039;Добро пожаловать!&lt;/div&gt;&lt;br&gt;Здравствуй, Мир!&#039;,
            31: &#039;Сюда принимается &#039;,
            32: &#039;файл или папка&#039;,
            33: &#039;файл&#039;,
            34: &#039;папка&#039;,
            35: &#039;.&#039;,
            36: &#039;Приемник элементов отключен.&#039;,
            37: &#039;-= Анализ... =-&lt;/div&gt;&#039;,
            38: &#039;-= Обработка =-&lt;/div&gt;&lt;br&gt;&lt;div style=&quot;text-align:left;&quot;&gt;&#039;,
            39: &#039;-= Обработано за &#039;,
            40: &#039;-= Невозможно обработать =-&lt;/div&gt;&lt;br&gt;&#039;,
            41: &#039;Данный элемент это не &#039;,
            42: &#039;,&lt;br&gt;не может быть доступен&lt;br&gt;или его размер слишком велик.&#039;,
            43: &#039;Произошла неизвестная ошибка.&#039;,
            1: &#039;Произошла определенная ошибка 1.&#039;,
            &#039;error 2&#039;: &#039;Произошла определенная ошибка 2.&#039;
        }
</code></pre></div><p>Для дальнейшей обработки результатов замените функцию с комментарием &quot;//data processing sample (file or folder path)&quot; на свою.<br />Возникающие исключения в функции ловятся скрыто и автоматически.<br />Возвращенные функцией ID ошибок обрабатываются отдельно как пользовательские ошибки.<br />Пользовательские ID ошибок задаются в конце общего блока сообщений.</p><p>Для встраивания &quot;Extended Drop Target&quot; в другое окно передайте на вход &quot;document&quot; соответствующего окна.</p><p>Для включения/отключения поддержки drag and drop для файлов или папок измените соответствующий флаг (1 или true; 0, undefined или false):</p><div class="codebox"><pre><code>
            1,      //indicates whether processing of files is allowed or not
            1,      //indicates whether processing of folders is allowed or not
</code></pre></div><br /><p>Для изменения размеров &quot;Extended Drop Target&quot;, параметров границы, параметров шрифта заголовка сообщений, текста, а также выравнивания обратитесь к строкам:</p><div class="codebox"><pre><code>
            &#039;width:350px;height:150px;border:2px blue solid;font:bold 10pt Arial;text-align:center;cursor:default;overflow:hidden;word-break:break-all;&#039;,       //drop target style
            &#039;bold 12pt Tahoma&#039;,     //message header font
</code></pre></div><p>Для изменения цвета фона, на котором показывается сообщение определенной группы, или цвета текста обратитесь к строкам:</p><div class="codebox"><pre><code>
            &#039;yellow&#039;,               //welcome message background color if background image is not set or text color otherwise
            &#039;mediumaquamarine&#039;,     //default message background color if background image is not set or text color otherwise
            &#039;limegreen&#039;,            //processing message background color if background image is not set or text color otherwise
            &#039;salmon&#039;,               //error message background color if background image is not set or text color otherwise
</code></pre></div><p>Если в качестве фона выбрано изображение, то изменяется цвет текста.</p><p>Для обработки ошибок замените функцию с комментарием &quot;//error resolving sample (error ID)&quot; на свою.<br />Возникающие исключения в функции ловятся скрыто и автоматически.<br />Пользовательские ID ошибок задаются в конце общего блока сообщений.</p><p>Для показа изображений в качестве фона раскомментируйте соответствующие строки:<br /></p><div class="codebox"><pre><code>
            ,&#039;C:\\Windows\\Web\\Screen\\img103.png&#039;     //default background image or &quot;undefined&quot; (optional)
            ,&#039;C:\\Windows\\Web\\Screen\\img102.jpg&#039;      //busy mode background image or &quot;undefined&quot; (optional)
</code></pre></div><p>Важно сохранять порядок следования передаваемых параметров, поэтому <strong>вместо предшествующих нераскомментированных</strong> строк в настройках всегда прописывайте:</p><div class="codebox"><pre><code>
            ,undefined
</code></pre></div><p>При необходимости используйте картинки для вашей версии Windows из блока ниже, либо замените раскомментированные строки на пути к своим изображениям:<br /></p><div class="codebox"><pre><code>
/*
    some built-in in Windows 10 background samples:
    &#039;C:\\Windows\\Web\\Screen\\img103.png&#039;
    &#039;C:\\Windows\\Web\\Screen\\img102.jpg&#039;

    some built-in in Windows 7 background samples:
    &#039;C:\\Windows\\Web\\Wallpaper\\Nature\\img3.jpg&#039;
    &#039;C:\\Windows\\Web\\Wallpaper\\Landscapes\\img10.jpg&#039;

    some built-in in Windows XP background samples:
    &#039;C:\\WINDOWS\\Zapotec.bmp&#039;
    &#039;C:\\WINDOWS\\Soap Bubbles.bmp&#039;
*/
</code></pre></div><p>Для показа <strong>произвольного</strong> пользовательского описания продукта раскомментируйте:</p><div class="codebox"><pre><code>
            ,&#039;&lt;div style=\&#039;font:10pt Tahoma;padding:20px;\&#039;&gt;List of files supported by default:&lt;ul&gt;&lt;li&gt;Bitmap Files (*.bmp;*.dib)&lt;li&gt;JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)&lt;li&gt;GIF(*.gif)&lt;/ul&gt;&lt;/div&gt;&#039;
</code></pre></div><p>Это пример дополнительной информации для пользователя, который <strong>не ограничивает</strong> текущую функциональность.</p><p>Для показа произвольного пользовательского описания продукта на русском языке замените эту запись на:</p><div class="codebox"><pre><code>
        ,&#039;&lt;div style=\&#039;font:10pt Tahoma;padding:20px;\&#039;&gt;Список поддерживаемых файлов по умолчанию:&lt;ul&gt;&lt;li&gt;Bitmap Files (*.bmp)&lt;li&gt;JPEG (*.jpg;*.jpeg)&lt;li&gt;GIF(*.gif)&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;&#039;
</code></pre></div><p>Длина описания ограничена возможностями Web Browser.</p><p>Для перенаправления drag and drop сообщений в другую область или окно раскомментируйте:<br /></p><div class="codebox"><pre><code>
            ,function(m){result.value = m;}     //sample for receiving messages or &quot;undefined&quot; (optional)
</code></pre></div><p>Данный пример перенаправит сообщения в textarea, расположенную выше &quot;Extended Drop Target&quot;. При этом сообщения в &quot;Extended Drop Target&quot; больше показаны не будут, хотя по-прежнему может происходить смена фона как ответная реакция на происходящие события.</p><p>Если показ сообщений не нужен, но и их перенаправление не требуется, то можно поставить простую заглушку:<br /></p><div class="codebox"><pre><code>
            ,function(m){;}     //sample for receiving messages or &quot;undefined&quot; (optional)
</code></pre></div><p>Желаю вам приятной работы с функциональностью drag and drop для файлов и папок в окне HTA.</p>]]></content>
			<author>
				<name><![CDATA[lifeflame]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=40203</uri>
			</author>
			<updated>2020-10-30T19:52:58Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=143022#p143022</id>
		</entry>
</feed>
