2

I am building a little HTA for personal use, and would like to be able to drag and drop a file to the interface. Once the file is dropped, I would either automatically run it (assuming it fits some parameters I set, like file extension), or at least fill in the input box on the HTA interface.

I've searched extensively, but can't find a solution. Thoughts?

6 Answers 6

5

Tomalak, is incorrect in his statement...there is way to do what you want except that you have to add the DropHandler in the registry for HTA files it's really easy to do and once done you will be able to do exactly what your trying to do. I couldn't find much documentation on it, but here is a link to an HTA that was written a long time ago by a guy named Michel Gallant, that shows you how to it: https://www.jensign.com/www/wsh/imager/

When the HTA is launched it looks to see if you have the DropHandler already configured. If you don't it gives you the option for it to configure it for you. Once configure all you have to do is close and reopen the HTA and wallah, there you go Drag and Drop support in HTA files.

0
2

I can confirm it is possible to obtain drag and drop functionality for files and folders in HTA window with "Web Browser" (no need to use any third party ActiveX objects, HTML5 or manipulations with the registry).

Its "RegisterAsDropTarget" parameter switched on allows such operations while "Web Browser" itself is built-in in every Windows since XP or 2000 by default. This way it works for input files named in any locale (Unicode names support) while, for example, WScript and CScript don't support this by default.

Below is a sample implemented as a self-contained component with many customized features including styles and backgrounds. It works both for 64 and 32 bit folder paths and can be inserted into DOM tree for certain window.

Save the source code below as a text file and then change its extension to "hta". Then launch the obtained application by double click on it.

<script>
/*
Extended Drop Target v1.1.4 (https://tastyscriptsforfree.wix.com/page/scripts)
Copyright 2017-2020 Vladimir Samarets. All rights reserved.
[email protected]

Release date: November 9, 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.
*/

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

if(!env('is64bit'))                                                                                                      //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('<hta:application showInTaskBar=0>'), 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 <ProcessId> by using WMI
        SWL:new ActiveXObject('WbemScripting.SWbemLocator'),
        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_('Create', CreateIn).ProcessId;
        }
    };
    WMI.PRC = (WMI.WM = WMI.SWL.ConnectServer('.', 'root/cimv2')).Get('Win32_Process');
    WMI.PS = WMI.WM.Get('Win32_ProcessStartup');
    WMI.CreateIn = WMI.PRC.Methods_('Create').InParameters;

    var ID = O('Scriptlet.TypeLib').GUID.substr(0, 38),                                             //the unique ID obtaining
    EV = 'is64bit='+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 += '?' + items.item();                                                                                  //obtaining all Environment variables for current process

    PID = WMI.Create                                                                                               //obtaining PID of 64 bit HTA instance
        (
            'mshta "' + decodeURIComponent(location.pathname) + '"',                     //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('?')                                                                                      //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
                            'is64bit='+ID,                                                                              //indicates that the application is launched as 64 bit
                            'SystemRoot='+env('SystemRoot'),                                           //for start
                            'SystemDrive='+env('SystemDrive'),                                         //for hyperlinks
                            'TEMP='+env('TEMP'),                                                                //for "mailto" links
                            'CommonProgramW6432='+env('CommonProgramW6432')     //for ADODB.Stream
                        ]
                        */
                }
            )
        );

    head.firstChild.insertAdjacentHTML('afterEnd', '<object id=' + ID + ' PID=' + PID +
        ' classid=clsid:8856F961-340A-11D0-A96B-00C04FD705A2><param name=RegisterAsBrowser value=1>');      //registering current HTA window in collection of windows

    showModalDialog('javascript:for(var ws=new ActiveXObject("Shell.Application").Windows(),i=ws.Count;i-->0;)if((w=ws.Item(i))&&w.id=="'+ID+'"){w.s=document.Script;break;}', 0,
        'dialogWidth:0;unadorned:1;');                                                                       //silent stop of the script and obtaining window focus for "AppActivate"
    close();onerror=function(){close();};throw 0;                                                     //declining any further attempts of executing the rest statements of the code
}

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

document.write('<body>');                                                                                      //obtaining body
if(w && w.id == env('is64bit'))
    w.s.close();                                                                                                         //closing previous 32 bit HTA instance while being in safe focus

document.body.appendChild(document.createTextNode('Debug screen (for test purposes only):'));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createElement('<textarea id=result cols=85 rows=5>'));
document.body.appendChild(document.createElement('p'));
document.body.appendChild(document.createTextNode('Extended Drop Target:'));
document.body.appendChild(document.createElement('br'));

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('<span style="' + dTStyle + '">'),

            ms = dropTarget.appendChild
            (
                doc.createElement('<span style="width:100%;height:100%;padding:10px;overflow:hidden;">')
            ),                                                                                                                  //message screen that hides Web Browser during dropped items processing

            WB = '<object classid=clsid:8856F961-340A-11D0-A96B-00C04FD705A2 style="width:100%;height:100%;"><param name=Location value="about:<body onload=\'b=0;\'' +
                ' ondragover=(function(){clearTimeout(b);b=setTimeout(\'location.reload();\',100);}()) bgColor=' + dMColor +
                ' style=\'width:100%;height:100%;position:absolute;margin:0;border:0;overflow:hidden;\'>'+ (description || '') +'">',
            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] : ''),      //"Drop a file or folder here."
            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 + '</div>', pMColor);                                              //show "Processing"
                        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>1000 ? 0 : 1000 - dt;
                        if(!e)                                                                                                 //no errors occured
                            setTimeout(function(){sM(msg[39] + createDropTarget.timeToHMSR(dt) + ' =-</div>', pMColor);}, delay);       //show "Processed in"
                        else                                                                                                 //an error occured
                        {
                            var err;
                            try{resolve(e);}catch(err){;}
                            setTimeout(function(){sM(msg[39] + createDropTarget.timeToHMSR(dt) + ' =-</div><br>' + msg[e], eMColor);}, delay);      //show "Processed in" with error
                            if(!redirect)
                                delay += 1000;
                        }
                    }
                    else                                                                                                     //the item can't be accessed
                    {
                        sM(msg[40] + msg[41] + allowedText + msg[42], eMColor);          //show "The item is not a file or folder, can't be accessed or its size is too big."
                        delay += 1000;
                    }

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

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

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

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

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

            NE = function()                                                                                             //catching "NavigateError" 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 = 'url(' + bgImage + ')';
                    ms.style.color = c;
                }
                else
                    ms.style.backgroundColor = c;
                m = '<div style="font:' + hdFont + ';">' + 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]) + '</div>', dMColor, dBgImage);}, delay + 100);     //show "Drop a file or folder
                                                                                                                                                                                                                                                             //here." or "Drop Target is
            }                                                                                                                                                                                                                                                //disabled."

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

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

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

            !(createDropTarget = function()
            {
                dropTarget.insertAdjacentHTML('beforeEnd', WB);
                with(dropTarget.children[1])
                {
                    RegisterAsDropTarget = Silent = Offline = 1;
                    attachEvent('DownloadBegin', DB);
                    attachEvent('StatusTextChange', STC);
                    attachEvent('NavigateComplete2', NC2);
                    attachEvent('NavigateError', 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 + 'h' : '') + (m ? (h ? ' ' : '') + m + 'm' : '') + (s ? (h || m ? ' ' : '') + s + 's' : '') + (r ? (h || m || s ? ' ' : '') + r + 'ms' : '')) || '0ms';
            },

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

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

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

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

            function(e)                                                                                                   //error resolving sample (error ID)
            {
                switch(e)
                {
                    case 1:
                        result.value = '\nCertain error 1 is catched.';                                  //additional action sample for certain error 1
                        updateData1();
                        break;
                    default:
                        result.value = '\nAn unknown error is catched.';                             //additional action sample for an unknown error
                        sendEmail();
                        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: 'Welcome!</div><br>Hello World!',                                                 //welcome message
                31: 'Drop a ',                                                                                           //31, 32, 33, 34, 35 - "Drop a file or folder here."
                32: 'file or folder',
                33: 'file',
                34: 'folder',
                35: ' here.',
                36: 'Drop Target is disabled.',
                37: '-= Analysing... =-</div>',
                38: '-= Processing =-</div><br><div style="text-align:left;">',
                39: '-= Processed in ',
                40: "-= Can't be processed =-</div><br>",
                41: 'The item is not a ',                                                                           //41, 32, 33, 34, 42 - "The item is not a file or folder,<br>can't be accessed or its size is too big."
                42: ",<br>can't be accessed or its size is too big.",
                43: 'An unknown error occured.',                                                            //unknown error message
                1: 'Certain error 1 occured.'                                                                   //certain error 1 message
                                                                                                                                //certain error # message
                                                                                                                                //...
            }

            //,'C:\\Windows\\Web\\Screen\\img103.png'                                               //default background image or "undefined" (optional)
            //,'C:\\Windows\\Web\\Screen\\img102.jpg'                                                //busy mode background image or "undefined" (optional)

            //,'<div style=\'font:10pt Tahoma;padding:20px;\'>List of files supported by default.</div>'
                                                                                                                                //description length depends on the message language or its actual bytes count or "undefined" (optional)

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

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

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

</script>
1
  • I gave +1. It's a decent example of enabling drag drop functionality in a HTA. It works for network paths as well. ( \\mynas\file.txt ). And large files are not a problem either. One big downside is that it's limited to only one path at a time. ( as all "iframe hacks" are ). I guess the example is a bit bloated, but i guess it was a intended as a "component". Commented Sep 4 at 23:28
1

If you don't want to enable the drop handler, I could imagine a way that this might be possible. It's a bit of a comedy chain, but I could see myself implementing this if I was backed into a corner and needed that functionality.

You can create an IFRAME which has its src as a temp folder somewhere. This folder will be displayed as an Explorer view. You can then drag files into that. Set up a polling routine against that folder to see if there are any new files. And voila, you have a lame way to support drag and drop operations with a given file.

0

An HTA obviously cannot be target of a shell drop operation – at least on my system, dropping something on an HTA is impossible.

This would imply you cannot directly do what you intend.

A .vbs can however be a drop target. Full paths of the dropped files are available via the WScript.Arguments.Unnamed collection.

HTA has access to it's command line arguments via the commandLine Property. This would mean you could build a small helper VBScript that translates the dropped files into a command line and calls the HTA for you.

Note that you cannot drop endless amounts of files on a .vbs, and command lines are not unlimited either. There will be a length limit in the area of a few kB (I have not tried to find where exactly the limit is, just be prepared to face a limit.)

3
  • Thanks for the answer! I was afraid of that. I think I might go with a Prism interface to an HTML page instead of the HTA.
    – Joshua
    Commented Apr 14, 2009 at 16:51
  • 2
    -1 "An HTA obviously cannot be target of a shell drop operation" is (now) incorrect. Enabling dropping onto an HTA file or shortcut, involves a simple registry change, and that's how it's always been. Supporting dropping on an HTA window is now simple with HTML5. Commented Mar 31, 2014 at 21:45
  • 1
    That's a nice addition but the second answer in line, which I upvoted, says exactly that and I have no idea why it hasn't been accepted. The whole thread is from 2009, so you are quite a bit late to the party and apparently you didn't read past this answer. Now combine that with the fact that it indeed does not work on a vanilla system - like the one you might want to ship your HTA to... you get the idea.
    – Tomalak
    Commented Apr 1, 2014 at 3:02
0

Go and try google gears which supplies drag and drop.

You can even use mysql in hta.

Google Gears is not available in hta, however, you can create the activexobject in a html file, then include it using an iframe(<iframe application="true" src=".."></iframe>)

After that, you can use the activexobject through the iframe.

0

Regarding …

would like to be able to drag and drop a file to the [HTA] interface

… which I interpret as a desire to drop files to the HTA’ running window, rather than dropping files on the HTA file itself or a shortcut to it.

With HTML5 the dropping itself is easy. Use e.g. a <div> element as a drop area. For this element handle the events dragenter, dragover and drop. E.g. the drop handler can look like this:

function on_drop( e )
{
    e.preventDefault();  // stops the browser from redirecting off to the file
    var dt = e.dataTransfer

    var is_file_transfer = false;
    for( var i = 0; i < dt.types.length; ++i )
    {
        if( dt.types[i].toLowerCase() == 'files' )
        {
            is_file_transfer = true;
        }
    }
    if( !is_file_transfer )
    {
        return false;
    }
    on_files_dropped( dt.files );
    return true;
}

… where on_files_dropped is a function defined by you that handles a files drop.

Adding the event handlers dynamically in the document loaded event, can look like this:

var dropbox = document.getElementById( 'blah' );
dropbox.addEventListener( 'dragenter', on_dragenter, false );
dropbox.addEventListener( 'dragover', on_dragover, false );
dropbox.addEventListener( 'drop', on_drop, false );

So far so good.

However, security intervenes with a restriction: you do not get direct knowledge of the original file paths, only the file names and the file sizes. For this functionality is designed for the web, not for local trusted HTML applications. So it may or may not necessarily be a problem.

  • For the purpose of using a dropped file as a source for an HTML element, and generally for reading a dropped file, HTML5 provides a FileReader (there are a number of tutorials available, which link further to technical documentation).

  • Where a local path is needed, e.g. for playing a file in Windows Mediaplayer, you can assume that the drag operation originated with Windows Explorer, now also called File Explorer, and then just check which Explorer window, if any, contains a file with that name and size.

Hopefully not more than one such originating window will be found.

var shell   = new ActiveXObject( "Shell.Application" );
var fso     = new ActiveXObject( "Scripting.FileSystemObject" );

function possible_paths_for( filename )
{
    var windows     = shell.windows();      // Windows Explorer windows.
    var n_windows   = windows.Count;

    var lowercase_filename = filename.toLowerCase();
    var paths = Array();
    for( var i = 0; i < n_windows; ++i )
    {
        var url     = windows.Item(i).LocationURL;
        var path    = decodeURI( url.substr( 8 ) ).replace( /\//g, '\\' );
        // The path can be the path of this HTML application (.hta file), so:
        if( fso.FolderExists( path ) )
        {
            var folder  = fso.GetFolder( path );
            for( var it = new Enumerator( folder.Files ); !it.atEnd(); it.moveNext() )
            {
                var file = it.item();
                if( file.Name.toLowerCase() == lowercase_filename )
                {
                    paths.push( file.Path.toLowerCase() );
                }
            }
        }
    }
    return paths;
}

Essentially that’s it. Except, maybe, since HTAs default to IE7, how does one get HTML5 functionality. Well may through doctype declaration, but so far in my little experimentation I just use the following:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <!-- A windows web control defaults to quirky IE7 semantics. Request for better: -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv="MSThemeCompatible" content="yes">

This gives you latest Internet Explorer engine, but at the cost of no HTA element, and hence no direct access to the command line. I found that the command line can be retrieved by running Windows’ wmic program, but that’s an awful hack. This whole problem area, with most apparently open roads turning out to be closed, appears to be a consequence of Microsoft now considering HTAs a legacy technology, to be quietly phased out in favor of fullscreen ad-ridden Windows 8 AppStore apps.

Anyway, good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.