codekingpro/portable-devtools
114k
1# -*- coding: latin-1 -*-2 3# PyWin32 Internet Explorer Button4#5# written by Leonard Ritter (paniq@gmx.net)6# and Robert F�rtsch (info@robert-foertsch.com)7 8 9"""10This sample implements a simple IE Button COM server11with access to the IWebBrowser2 interface.12 13To demonstrate:14* Execute this script to register the server.15* Open Pythonwin's Tools -> Trace Collector Debugging Tool, so you can16 see the output of 'print' statements in this demo.17* Open a new IE instance. The toolbar should have a new "scissors" icon,18 with tooltip text "IE Button" - this is our new button - click it.19* Switch back to the Pythonwin window - you should see:20 IOleCommandTarget::Exec called.21 This is the button being clicked. Extending this to do something more22 useful is left as an exercise.23 24Contribtions to this sample to make it a little "friendlier" welcome!25"""26 27# imports section28 29import pythoncom30import win32api31import win32com32import win32com.server.register33from win32com import universal34from win32com.client import Dispatch, DispatchWithEvents, constants, gencache, getevents35 36# This demo uses 'print' - use win32traceutil to see it if we have no37# console.38try:39 win32api.GetConsoleTitle()40except win32api.error:41 import win32traceutil42 43import array44 45from win32com.axcontrol import axcontrol46 47# ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on48win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)49 50 51#52IObjectWithSite_methods = ["SetSite", "GetSite"]53IOleCommandTarget_methods = ["Exec", "QueryStatus"]54 55_iebutton_methods_ = IOleCommandTarget_methods + IObjectWithSite_methods56_iebutton_com_interfaces_ = [57 axcontrol.IID_IOleCommandTarget,58 axcontrol.IID_IObjectWithSite, # IObjectWithSite59]60 61 62class Stub:63 """64 this class serves as a method stub,65 outputting debug info whenever the object66 is being called.67 """68 69 def __init__(self, name):70 self.name = name71 72 def __call__(self, *args):73 print("STUB: ", self.name, args)74 75 76class IEButton:77 """78 The actual COM server class79 """80 81 _com_interfaces_ = _iebutton_com_interfaces_82 _public_methods_ = _iebutton_methods_83 _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER84 _button_text_ = "IE Button"85 _tool_tip_ = "An example implementation for an IE Button."86 _icon_ = ""87 _hot_icon_ = ""88 89 def __init__(self):90 # put stubs for non-implemented methods91 for method in self._public_methods_:92 if not hasattr(self, method):93 print("providing default stub for %s" % method)94 setattr(self, method, Stub(method))95 96 def QueryStatus(self, pguidCmdGroup, prgCmds, cmdtextf):97 # 'cmdtextf' is the 'cmdtextf' element from the OLECMDTEXT structure,98 # or None if a NULL pointer was passed.99 result = []100 for id, flags in prgCmds:101 flags |= axcontrol.OLECMDF_SUPPORTED | axcontrol.OLECMDF_ENABLED102 result.append((id, flags))103 if cmdtextf is None:104 cmdtext = None # must return None if nothing requested.105 # IE never seems to want any text - this code is here for106 # demo purposes only107 elif cmdtextf == axcontrol.OLECMDTEXTF_NAME:108 cmdtext = "IEButton Name"109 else:110 cmdtext = "IEButton State"111 return result, cmdtext112 113 def Exec(self, pguidCmdGroup, nCmdID, nCmdExecOpt, pvaIn):114 print(pguidCmdGroup, nCmdID, nCmdExecOpt, pvaIn)115 print("IOleCommandTarget::Exec called.")116 # self.webbrowser.ShowBrowserBar(GUID_IETOOLBAR, not is_ietoolbar_visible())117 118 def SetSite(self, unknown):119 if unknown:120 # first get a command target121 cmdtarget = unknown.QueryInterface(axcontrol.IID_IOleCommandTarget)122 # then travel over to a service provider123 serviceprovider = cmdtarget.QueryInterface(pythoncom.IID_IServiceProvider)124 # finally ask for the internet explorer application, returned as a dispatch object125 self.webbrowser = win32com.client.Dispatch(126 serviceprovider.QueryService(127 "{0002DF05-0000-0000-C000-000000000046}", pythoncom.IID_IDispatch128 )129 )130 else:131 # lose all references132 self.webbrowser = None133 134 def GetClassID(self):135 return self._reg_clsid_136 137 138def register(classobj):139 import winreg140 141 subKeyCLSID = (142 "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s"143 % classobj._reg_clsid_144 )145 try:146 hKey = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)147 subKey = winreg.SetValueEx(148 hKey, "ButtonText", 0, winreg.REG_SZ, classobj._button_text_149 )150 winreg.SetValueEx(151 hKey, "ClsidExtension", 0, winreg.REG_SZ, classobj._reg_clsid_152 ) # reg value for calling COM object153 winreg.SetValueEx(154 hKey, "CLSID", 0, winreg.REG_SZ, "{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}"155 ) # CLSID for button that sends command to COM object156 winreg.SetValueEx(hKey, "Default Visible", 0, winreg.REG_SZ, "Yes")157 winreg.SetValueEx(hKey, "ToolTip", 0, winreg.REG_SZ, classobj._tool_tip_)158 winreg.SetValueEx(hKey, "Icon", 0, winreg.REG_SZ, classobj._icon_)159 winreg.SetValueEx(hKey, "HotIcon", 0, winreg.REG_SZ, classobj._hot_icon_)160 except WindowsError:161 print("Couldn't set standard toolbar reg keys.")162 else:163 print("Set standard toolbar reg keys.")164 165 166def unregister(classobj):167 import winreg168 169 subKeyCLSID = (170 "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s"171 % classobj._reg_clsid_172 )173 try:174 hKey = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)175 subKey = winreg.DeleteValue(hKey, "ButtonText")176 winreg.DeleteValue(hKey, "ClsidExtension") # for calling COM object177 winreg.DeleteValue(hKey, "CLSID")178 winreg.DeleteValue(hKey, "Default Visible")179 winreg.DeleteValue(hKey, "ToolTip")180 winreg.DeleteValue(hKey, "Icon")181 winreg.DeleteValue(hKey, "HotIcon")182 winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)183 except WindowsError:184 print("Couldn't delete Standard toolbar regkey.")185 else:186 print("Deleted Standard toolbar regkey.")187 188 189#190# test implementation191#192 193 194class PyWin32InternetExplorerButton(IEButton):195 _reg_clsid_ = "{104B66A9-9E68-49D1-A3F5-94754BE9E0E6}"196 _reg_progid_ = "PyWin32.IEButton"197 _reg_desc_ = "Test Button"198 _button_text_ = "IE Button"199 _tool_tip_ = "An example implementation for an IE Button."200 _icon_ = ""201 _hot_icon_ = _icon_202 203 204def DllRegisterServer():205 register(PyWin32InternetExplorerButton)206 207 208def DllUnregisterServer():209 unregister(PyWin32InternetExplorerButton)210 211 212if __name__ == "__main__":213 win32com.server.register.UseCommandLine(214 PyWin32InternetExplorerButton,215 finalize_register=DllRegisterServer,216 finalize_unregister=DllUnregisterServer,217 )218 