/[cvs]/nfo/projects/mess/src/client/windows/context_menu.py
ViewVC logotype

Diff of /nfo/projects/mess/src/client/windows/context_menu.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.3 by joko, Sat Jun 3 15:11:27 2006 UTC revision 1.8 by joko, Sat Jun 3 23:09:56 2006 UTC
# Line 1  Line 1 
1  # A sample context menu handler.  # Derived from Python24\Lib\site-packages\win32comext\shell\demos\servers\context_menu.py
2  # Adds a 'Hello from Python' menu entry to .py files.  When clicked, a  # >> a bit more complex <<
3  # simple message box is displayed.  
4  #  # Acknowledgements to Mark Hammond for his "Python for Windows extensions"
5  # To demostrate:  # http://python.net/crew/mhammond/
6  # * Execute this script to register the context menu.  
7  # * Open Windows Explorer, and browse to a directory with a .py file.  # ... and Michael Dunn for his
8  # * Right-Click on a .py file - locate and click on 'Hello from Python' on  # "The Complete Idiot's Guide to Writing Shell Extensions"-series at "The Code Project"
9  #   the context menu.  # http://www.codeproject.com/shell/shellextguideindex.asp
10    
11    # You're great guys!
12    
13    
14  import pythoncom  import pythoncom
15  from win32com.shell import shell, shellcon  from win32com.shell import shell, shellcon
16  import win32gui  import win32gui, win32gui_struct
17  import win32con  import win32con
18    import win32api, winerror
19    
20  IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]  IContextMenu_Methods = ["QueryContextMenu", "InvokeCommand", "GetCommandString"]
21  IShellExtInit_Methods = ["Initialize"]  IShellExtInit_Methods = ["Initialize"]
22    
23  class ShellExtension:  class ShellExtension:
24      _reg_progid_ = "Python.ShellExtension.ContextMenu"      _reg_progid_ = "Mess.ShellExtension.ContextMenu"
25      _reg_name_ = "MessClient"      _reg_name_ = "MessClient"
26      _reg_desc_ = "Mess Shell Extension"      _reg_desc_ = "Mess Shell Extension"
27      _reg_clsid_ = "{CED0336C-C9EE-4a7f-8D7F-C660393C381F}"      _reg_clsid_ = "{CED0336C-C9EE-4a7f-8D7F-C660393C381F}"
28      _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]      _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
29      _public_methods_ = IContextMenu_Methods + IShellExtInit_Methods      _public_methods_ = IContextMenu_Methods + IShellExtInit_Methods
30    
31      def Initialize(self, folder, dataobj, hkey):      def Initialize(self, pidlFolder, dataobj, hkey):
32          print "Init", folder, dataobj, hkey          print "Init", pidlFolder, dataobj, hkey
33          self.dataobj = dataobj          self.dataobj = dataobj
34    
35      def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):      def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
36                    
37          # debug          # debug
38          print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags          print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags
39    
40            # clicking on a directory background leaves us with dataobj == None
41            if self.dataobj:
42              
43              # query the items clicked on
44              format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
45              sm = self.dataobj.GetData(format_etc)
46              
47              # how many items are selected
48              num_files = shell.DragQueryFile(sm.data_handle, -1)
49                    
50          # query the items clicked on            # grab all items
51          format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL            self.files_selected = []
52          sm = self.dataobj.GetData(format_etc)            for i in range(0, num_files):
53          num_files = shell.DragQueryFile(sm.data_handle, -1)              fname = shell.DragQueryFile(sm.data_handle, i)
54                        if fname == 0: continue
55          #if num_files>1:              self.files_selected.append(fname)
         #    msg = "&Hello from Python (with %d files selected)" % num_files  
         #else:  
         #    fname = shell.DragQueryFile(sm.data_handle, 0)  
         #    msg = "&Hello from Python (with '%s' selected)" % fname  
         self.files_selected = []  
         for i in range(0, num_files):  
           fname = shell.DragQueryFile(sm.data_handle, i)  
           if fname == 0: continue  
           self.files_selected.append(fname)  
56    
57          # build context menu(s)  
58          msg = "A&rchiveMe"          # calculate items to be added to context menu
         idCmd = idCmdFirst  
59          items = []          items = []
60          if (uFlags & 0x000F) == shellcon.CMF_NORMAL: # Check == here, since CMF_NORMAL=0          
61              print "CMF_NORMAL..."          # CMF_NORMAL: e.g. files on desktop
62              items.append(msg)          # CMF_VERBSONLY: e.g. shortcuts
63          elif uFlags & shellcon.CMF_VERBSONLY:          # CMF_EXPLORE: regular files/folders via explorer
64              print "CMF_VERBSONLY..."          
65              items.append(msg + " - shortcut")          # Check == here, since CMF_NORMAL=0
66          elif uFlags & shellcon.CMF_EXPLORE:          if ((uFlags & 0x000F) == shellcon.CMF_NORMAL) or (uFlags & shellcon.CMF_VERBSONLY) or (uFlags & shellcon.CMF_EXPLORE):
67              print "CMF_EXPLORE..."              if self.dataobj:
68              #items.append(msg + " - normal file, right-click in Explorer")                items.append("Add to A&rchive")
69              items.append(msg)                items.append("Named Shortcut &1")
70                  items.append("Named Shortcut &2")
71          elif uFlags & CMF_DEFAULTONLY:          elif uFlags & CMF_DEFAULTONLY:
72              print "CMF_DEFAULTONLY...\r\n"              print "CMF_DEFAULTONLY...\r\n"
73              items.append("hello world - 1!")              items.append("hello world - 1!")
74          else:          else:
75              print "** unknown flags", uFlags              print "** unknown flags", uFlags
76              items.append("hello world - 2!")              items.append("hello world - 2!")
77    
78    
79            # build context menu(s)
80            idCmd = idCmdFirst
81    
82            # add seperator line
83          win32gui.InsertMenu(hMenu, indexMenu,          win32gui.InsertMenu(hMenu, indexMenu,
84                              win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,                              win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
85                              0, None)                              idCmd, None)
86          indexMenu += 1          indexMenu += 1
87            idCmd += 1
88            
89            # create main menu entries
90          for item in items:          for item in items:
91              win32gui.InsertMenu(hMenu, indexMenu,              win32gui.InsertMenu(hMenu, indexMenu,
92                                  win32con.MF_STRING|win32con.MF_BYPOSITION,                                  win32con.MF_STRING|win32con.MF_BYPOSITION,
93                                  idCmd, item)                                  idCmd, item)
94              indexMenu += 1              indexMenu += 1
95              idCmd += 1              idCmd += 1
96            
97            # create submenu entries
98            hSubmenu = win32gui.CreatePopupMenu()
99            win32gui.InsertMenu(hSubmenu, 0,
100                                win32con.MF_BYPOSITION,
101                                idCmd, "&Settings...")
102            idCmd += 1
103            
104            # insert the submenu into a new container menu entry
105            item, extras = win32gui_struct.PackMENUITEMINFO(
106              wID = idCmd,
107              hSubMenu = hSubmenu,
108              text = "&Mess"
109            )
110            win32gui.InsertMenuItem(hMenu, indexMenu, 1, item)        
111            indexMenu += 1
112            idCmd += 1
113    
114            # add seperator line
115          win32gui.InsertMenu(hMenu, indexMenu,          win32gui.InsertMenu(hMenu, indexMenu,
116                              win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,                              win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
117                              0, None)                              idCmd, None)
118          indexMenu += 1          indexMenu += 1
119            idCmd += 1
120    
121          return idCmd-idCmdFirst # Must return number of menu items we added.          return idCmd-idCmdFirst # Must return number of menu items we added.
122    
123        def GetCommandString(self, cmdId, typ):
124            #if cmdId == 0:
125            #  return "Hello from Python!!"
126            #else:
127            #  return "abc"
128            return self._reg_name_ + "_" + cmdId;
129    
130      def InvokeCommand(self, ci):      def InvokeCommand(self, ci):
131          mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci          mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
         win32gui.MessageBox(hwnd, "\n".join(self.files_selected), "ArchiveMe", win32con.MB_OK)  
132    
133      def GetCommandString(self, cmd, typ):          # If lpVerb really points to a string, ignore this function call and bail out.
134          return "Hello from Python!!"          if win32api.HIWORD( verb ) != 0:
135              return winerror.E_INVALIDARG
136            
137            function_id = win32api.LOWORD(verb)
138            # TODO: establish mapping with building the context menus in "QueryContextMenu"
139            if function_id == 1:
140              method = "Add to archive"
141            elif function_id == 2:
142              method = "Shortcut 1"
143            elif function_id == 3:
144              method = "Shortcut 2"
145            else:
146              method = "Unknown"
147    
148            # do action(s)
149            if hasattr(self, 'files_selected'):
150              win32gui.MessageBox(hwnd, "\n".join(self.files_selected), method, win32con.MB_OK)
151            else:
152              win32gui.MessageBox(hwnd, "No selection!", method, win32con.MB_OK)
153    
154    
155  def DllRegisterServer():  def DllRegisterServer():
# Line 99  def DllRegisterServer(): Line 157  def DllRegisterServer():
157            
158      # extended (via http://mail.python.org/pipermail/python-list/2003-December/198390.html)      # extended (via http://mail.python.org/pipermail/python-list/2003-December/198390.html)
159    
160        # for directory background
161        background_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Directory\\Background\\shellex")
162        background_subkey = _winreg.CreateKey(background_key, "ContextMenuHandlers")
163        background_subkey2 = _winreg.CreateKey(background_subkey, ShellExtension._reg_name_)
164        _winreg.SetValueEx(background_subkey2, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
165    
166      # for folders      # for folders
167      folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Folder\\shellex")      folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Folder\\shellex")
168      folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers")      folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers")
# Line 120  def DllUnregisterServer(): Line 184  def DllUnregisterServer():
184      # extended (via http://mail.python.org/pipermail/python-list/2003-December/198390.html)      # extended (via http://mail.python.org/pipermail/python-list/2003-December/198390.html)
185    
186      try:      try:
187            # for directory background
188            background_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
189                                    "Directory\\Background\\shellex\\ContextMenuHandlers\\" + ShellExtension._reg_name_)
190          # for folders          # for folders
191          folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,          folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
192                                  "Folder\\shellex\\ContextMenuHandlers\\" + ShellExtension._reg_name_)                                  "Folder\\shellex\\ContextMenuHandlers\\" + ShellExtension._reg_name_)

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.8

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed