Windows - Drag & drop on Python script?

Roger Burnham roger.burnham at gte.net
Wed Jun 23 22:06:45 EDT 1999


On Thu, 24 Jun 1999 12:04:16 +1200, Greg Ewing <greg.ewing at compaq.com> wrote:

>How can I create an icon onto which I can drop a file,
>and have it run a Python script with the dropped file
>as an argument?
>
>I've tried myriad combinations of .bat files, shortcuts,
>etc., but nothing seems to work.
>
>The obvious thing would seem to be to use a .bat
>file, but the dropped file seems to end up as the
>standard input or something, rather than getting
>passed as an argument.
>
>There *must* be a way of doing this, surely?
>

Greg,

One choice would be to hack up Pythonwin\pywin\framework\app.py and modify the
OnDropFiles method to do your thing rather than opening the dropped file in the
editor.  Then you could drop files onto the PythonWin icon.

I played a bit with this, the best I could come up with is the following dialog
app, which must be running, and will accept files dropped onto it and print its
output into an edit window.


# adapted from Pythonwin\pywin\Demos\app\dlgappdemo.py

from pywin.framework import dlgappcore, app
import win32ui, win32con, win32api
import sys
import regsub

class DropScriptDialogApp(dlgappcore.DialogApp):
    def CreateDialog(self):
        return DropScriptAppDialog()

class DropScriptAppDialog(dlgappcore.AppDialog):
    def __init__(self):
        self.edit = None
        dlgappcore.AppDialog.__init__(self, win32ui.IDD_LARGE_EDIT)
        
    def OnInitDialog(self):
        self.SetWindowText('Drop script application')
        self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
        self.DragAcceptFiles()
        self.HookMessage(self.OnDropFiles, win32con.WM_DROPFILES)
        return 1

    def OnDropFiles(self, msg):
        hDropInfo = msg[2]
        nFiles = win32api.DragQueryFile(hDropInfo)
        try:
            for iFile in range(0, nFiles):
                fileName = win32api.DragQueryFile(hDropInfo, iFile)
                print '%s dropped...' % fileName
        finally:
            win32api.DragFinish(hDropInfo);
        return 0
                
    def PreDoModal(self):
        sys.stdout = sys.stderr = self

    def write(self, str):
        if self.edit:
            self.edit.SetSel(-2)
            # translate \n to \n\r
            self.edit.ReplaceSel(regsub.gsub('\n','\r\n',str))
        else:
            win32ui.OutputDebug(
                'dlgapp - no edit control! >>\n%s\n<<\n' % str )

app.AppBuilder = DropScriptDialogApp

if __name__=='__main__':
    import demoutils
    demoutils.NeedApp()
        

Roger Burnham   
Cambridge Research & Instrumentation   
rburnham at cri-inc.com   
http://www.cri-inc.com/   
http://starship.python.net/crew/roger/   
PGP Key: http://www.nai.com/default_pgp.asp   
PGP Fingerprint: 5372 729A 9557 5F36 177F  084A 6C64 BE27 0BC4 CF2D   




More information about the Python-list mailing list