[python-win32] Creating python com objects

Tim Golden mail at timgolden.me.uk
Fri Apr 25 18:16:34 CEST 2008


Well, for those of you still watching this show (!) and
just in case anyone comes along in the future with the
same question, I attach below a small working example
which will accept one or more files dropped onto its
Window. It doesn't do anything with the files, bar pull
their names from the relevant data structure, but that's
up to the specific application.

Many thanks to Roger for the critical info to get this
working and to Alex for asking the question which started
it off.

TJG

<code>
import os, sys
import win32gui
import win32con
import pythoncom
import win32com.server.policy
from win32com.shell import shell, shellcon

# clsid generated by pythoncom.CreateGuid ()
CLSID = '{89DD545A-2C83-4103-AFE3-6CEB7FF5ECA4}'
PROGID = "Tim.DropTarget"
DESC = "Drop target handler for Tim"

class DropTarget (win32com.server.policy.DesignatedWrapPolicy):
   _reg_clsid_ = CLSID
   _reg_progid_ = PROGID
   _reg_desc_ = DESC
   _public_methods_ = ['DragEnter', 'DragOver', 'DragLeave', 'Drop']
   _com_interfaces_ = [pythoncom.IID_IDropTarget]

   def __init__ (self, hWnd):
     self._wrap_ (self)
     self.hWnd = hWnd

   def DragEnter (self, data_object, key_state, point, effect):
     if data_object.QueryGetData ((15, None, 1, -1, 1)):
       return shellcon.DROPEFFECT_COPY
     else:
       return shellcon.DROPEFFECT_NONE
   def DragOver (self, key_state, point, effect):
     pass
   def DragLeave (self):
     pass
   def Drop (self, data_object, key_state, point, effect):
     data = data_object.GetData ((15, None, 1, -1, 1))
     n_files = shell.DragQueryFileW (data.data_handle, -1)
     filenames = [
       shell.DragQueryFileW (data.data_handle, n_file) \
         for n_file in range (n_files)
     ]

def create_window ():
   def OnDestroy (hwnd, msg, wparam, lparam):
     win32gui.PostQuitMessage (0)

   wc = win32gui.WNDCLASS ()
   hinst = win32gui.GetModuleHandle(None)
   wc.lpszClassName = "DragDrop"
   wc.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW;
   wc.hCursor = win32gui.LoadCursor (0, win32con.IDC_ARROW)
   wc.hbrBackground = win32con.COLOR_WINDOW
   wc.lpfnWndProc = {win32con.WM_DESTROY : OnDestroy}
   classAtom = win32gui.RegisterClass (wc)
   style = win32con.WS_VISIBLE | win32con.WS_OVERLAPPED \
     | win32con.WS_SYSMENU
   return win32gui.CreateWindow (
     classAtom,
     "Drag & Drop demo",
     style,
     0, 0, 100, 100,
     0, 0, hinst, None
   )

if __name__ == '__main__':
   pythoncom.OleInitialize ()
   hWnd = create_window ()
   drop_target = DropTarget (hWnd)
   pythoncom.RegisterDragDrop (
     hWnd,
     pythoncom.WrapObject (
       drop_target,
       pythoncom.IID_IDropTarget,
       pythoncom.IID_IDropTarget
     )
   )
   win32gui.PumpMessages ()

</code>


More information about the python-win32 mailing list