def register(self): """Register to listen to network events.""" # call the CoInitialize to allow the registration to run in an other # thread pythoncom.CoInitialize() # interface to be used by com manager_interface = pythoncom.WrapObject(self) event_system = Dispatch(PROGID_EventSystem) # register to listent to each of the events to make sure that # the code will work on all platforms. for current_event in SUBSCRIPTIONS: # create an event subscription and add it to the event # service event_subscription = Dispatch(PROGID_EventSubscription) event_subscription.EventClassId = SENSGUID_EVENTCLASS_NETWORK event_subscription.PublisherID = SENSGUID_PUBLISHER event_subscription.SubscriptionID = current_event[0] event_subscription.SubscriptionName = current_event[1] event_subscription.MethodName = current_event[2] event_subscription.SubscriberInterface = manager_interface event_subscription.PerUser = True # store the event try: event_system.Store(PROGID_EventSubscription, event_subscription) except pythoncom.com_error as e: service_logger.error('Error registering to event %s', current_event[1])
def OnInitDialog (self, hwnd, msg, wparam, lparam): ur"""Attempt to position the dialog box more or less in the middle of its parent (possibly the desktop). Then force a resize of the dialog controls which should take into account the different label lengths and the dialog's new size. """ self.hwnd = hwnd # # If you want to have a translucent dialog, # enable the next block. # if False: wrapped ( win32gui.SetWindowLong, self.hwnd, win32con.GWL_EXSTYLE, win32con.WS_EX_LAYERED | wrapped ( win32gui.GetWindowLong, self.hwnd, win32con.GWL_EXSTYLE ) ) wrapped ( win32gui.SetLayeredWindowAttributes, self.hwnd, 255, (255 * 80) / 100, win32con.LWA_ALPHA ) pythoncom.RegisterDragDrop ( hwnd, pythoncom.WrapObject ( _DropTarget (hwnd), pythoncom.IID_IDropTarget, pythoncom.IID_IDropTarget ) ) for i, (field, default, callback) in enumerate (self.fields): id = self.IDC_FIELD_BASE + i self._set_item (id, default) parent = self.parent_hwnd or DESKTOP l, t, r, b = self.corners (*wrapped (win32gui.GetWindowRect, self.hwnd)) r = min (r, l + self.MAX_W) dt_l, dt_t, dt_r, dt_b = wrapped (win32gui.GetWindowRect, parent) cx = int (round ((dt_r - dt_l) / 2)) cy = int (round ((dt_b - dt_t) / 2)) centre_x, centre_y = wrapped (win32gui.ClientToScreen, parent, (cx, cy)) dx = int (round (centre_x - (r / 2))) dy = int (round (centre_y - (b / 2))) wrapped (win32gui.MoveWindow, self.hwnd, dx, dy, r - l, b - t, 0) l, t, r, b = wrapped (win32gui.GetClientRect, self.hwnd) self._resize (r - l, b - t, 0) return True
def _CreateInstance_(self, clsid, reqIID): """Creates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@) """ try: classSpec = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regSpec % clsid) except win32api.error: raise error( "The object is not correctly registered - %s key can not be read" % (regSpec % clsid)) myob = call_func(classSpec) self._wrap_(myob) try: return pythoncom.WrapObject(self, reqIID) except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, arg) = xxx_todo_changeme.args from win32com.util import IIDToInterfaceName desc = ("The object '%r' was created, but does not support the " "interface '%s'(%s): %s" % (myob, IIDToInterfaceName(reqIID), reqIID, desc)) raise pythoncom.com_error(hr, desc, exc, arg)
def wrap(ob, iid=None, usePolicy=None, useDispatcher=None): """Wraps an object in a PyGDispatch gateway. Returns a client side PyI{iid} interface. Interface and gateway support must exist for the specified IID, as the QueryInterface() method is used. """ if usePolicy is None: usePolicy = policy.DefaultPolicy if useDispatcher == 1: # True will also work here. import win32com.server.dispatcher useDispatcher = win32com.server.dispatcher.DefaultDebugDispatcher if useDispatcher is None or useDispatcher == 0: ob = usePolicy(ob) else: ob = useDispatcher(usePolicy, ob) # get a PyIDispatch, which interfaces to PyGDispatch ob = pythoncom.WrapObject(ob) if iid is not None: # Ask the PyIDispatch if it supports it? ob = ob.QueryInterface(iid) return ob
def register(self): try: pythoncom.RegisterDragDrop( self.hwnd, pythoncom.WrapObject(self, pythoncom.IID_IDropTarget, pythoncom.IID_IDropTarget)) except pywintypes.com_error: global text_list text_list = ["COM failure!"]
def NewCollection(seq, cls=Collection): """Creates a new COM collection object This function creates a new COM Server that implements the common collection protocols, including enumeration. (_NewEnum) A COM server that can enumerate the passed in sequence will be created, then wrapped up for return through the COM framework. Optionally, a custom COM server for enumeration can be passed (the default is @Collection@). """ return pythoncom.WrapObject(policy.DefaultPolicy(cls(seq)), pythoncom.IID_IDispatch, pythoncom.IID_IDispatch)
def SvcDoRun(self): ''' Main service loop ''' try: initCfg() logger.debug('running SvcDoRun') servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) # call the CoInitialize to allow the registration to run in an other # thread logger.debug('Initializing com...') pythoncom.CoInitialize() # ******************************************************** # * Ask brokers what to do before proceding to main loop * # ******************************************************** while True: brokerConnected = self.interactWithBroker() if brokerConnected is False: logger.debug( 'Interact with broker returned false, stopping service after a while' ) self.notifyStop() win32event.WaitForSingleObject(self.hWaitStop, 5000) return elif brokerConnected is True: break # If brokerConnected returns None, repeat the cycle self.doWait(16000) # Wait for a looong while if self.interactWithBroker() is False: logger.debug( 'Interact with broker returned false, stopping service after a while' ) self.notifyStop() win32event.WaitForSingleObject(self.hWaitStop, 5000) return if self.isAlive is False: logger.debug( 'The service is not alive after broker interaction, stopping it' ) self.notifyStop() return if self.rebootRequested is True: logger.debug('Reboot has been requested, stopping service') self.notifyStop() return self.initIPC() except Exception: # Any init exception wil be caught, service must be then restarted logger.exception() logger.debug('Exiting service with failure status') os._exit(-1) # pylint: disable=protected-access # ******************************** # * Registers SENS subscriptions * # ******************************** logevent('Registering ISensLogon') subscription_guid = '{41099152-498E-11E4-8FD3-10FEED05884B}' sl = SensLogon(self) subscription_interface = pythoncom.WrapObject(sl) event_system = win32com.client.Dispatch(PROGID_EventSystem) event_subscription = win32com.client.Dispatch(PROGID_EventSubscription) event_subscription.EventClassID = SENSGUID_EVENTCLASS_LOGON event_subscription.PublisherID = SENSGUID_PUBLISHER event_subscription.SubscriptionName = 'UDS Actor subscription' event_subscription.SubscriptionID = subscription_guid event_subscription.SubscriberInterface = subscription_interface event_system.Store(PROGID_EventSubscription, event_subscription) logger.debug('Registered SENS, running main loop') # Execute script in c:\\windows\\post-uds.bat after interacting with broker, if no reboot is requested ofc # This will be executed only when machine gets "ready" try: if os.path.isfile(POST_CMD): subprocess.call([ POST_CMD, ]) else: logger.info('POST file not found & not executed') except Exception as e: # Ignore output of execution command logger.error('Executing post command give') # ********************* # * Main Service loop * # ********************* # Counter used to check ip changes only once every 10 seconds, for # example counter = 0 while self.isAlive: counter += 1 # Process SENS messages, This will be a bit asyncronous (1 second # delay) pythoncom.PumpWaitingMessages() if counter >= 15: # Once every 15 seconds counter = 0 try: self.checkIpsChanged() except Exception as e: logger.error('Error checking ip change: {}'.format(e)) # In milliseconds, will break win32event.WaitForSingleObject(self.hWaitStop, 1000) logger.debug('Exited main loop, deregistering SENS') # ******************************************* # * Remove SENS subscription before exiting * # ******************************************* event_system.Remove(PROGID_EventSubscription, "SubscriptionID == " + subscription_guid) self.endIPC() # Ends IPC servers self.endAPI() # And deinitializes REST api if needed self.notifyStop()
def _CreateInstance_(self, clsid, reqIID): self._wrap_({}) return pythoncom.WrapObject(self, reqIID)
def _CreateInstance_(self, clsid, reqIID): try: self.policy._CreateInstance_(clsid, reqIID) return pythoncom.WrapObject(self, reqIID) except: return self._HandleException_()
def EditSecurity(self, owner_hwnd=0): """Creates an ACL editor dialog based on parameters returned by interface methods""" isi=pythoncom.WrapObject(self, authorization.IID_ISecurityInformation, pythoncom.IID_IUnknown) authorization.EditSecurity(owner_hwnd, isi)
def SvcDoRun(self): ''' Main service loop ''' try: initCfg() logger.debug('running SvcDoRun') servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) # call the CoInitialize to allow the registration to run in an other # thread logger.debug('Initializing com...') pythoncom.CoInitialize() # ******************************************************** # * Ask brokers what to do before proceding to main loop * # ******************************************************** if self.interactWithBroker() is False: logger.debug( 'Interact with broker returned false, stopping service after a while' ) self.notifyStop() win32event.WaitForSingleObject(self.hWaitStop, 5000) return if self.isAlive is False: logger.debug( 'The service is not alive after broker interaction, stopping it' ) self.notifyStop() return if self.rebootRequested is True: logger.debug('Reboot has been requested, stopping service') self.notifyStop() return self.initIPC() except Exception: # Any init exception wil be caught, service must be then restarted logger.exception() logger.debug('Exiting service with failure status') os._exit(-1) # pylint: disable=protected-access # ******************************** # * Registers SENS subscriptions * # ******************************** logevent('Registering ISensLogon') subscription_guid = '{41099152-498E-11E4-8FD3-10FEED05884B}' sl = SensLogon(self) subscription_interface = pythoncom.WrapObject(sl) event_system = win32com.client.Dispatch(PROGID_EventSystem) event_subscription = win32com.client.Dispatch(PROGID_EventSubscription) event_subscription.EventClassID = SENSGUID_EVENTCLASS_LOGON event_subscription.PublisherID = SENSGUID_PUBLISHER event_subscription.SubscriptionName = 'UDS Actor subscription' event_subscription.SubscriptionID = subscription_guid event_subscription.SubscriberInterface = subscription_interface event_system.Store(PROGID_EventSubscription, event_subscription) logger.debug('Registered SENS, running main loop') # ********************* # * Main Service loop * # ********************* # Counter used to check ip changes only once every 10 seconds, for # example counter = 0 while self.isAlive: counter += 1 # Process SENS messages, This will be a bit asyncronous (1 second # delay) pythoncom.PumpWaitingMessages() if counter % 10 == 0: self.checkIpsChanged() # In milliseconds, will break win32event.WaitForSingleObject(self.hWaitStop, 1000) logger.debug('Exited main loop, deregistering SENS') # ******************************************* # * Remove SENS subscription before exiting * # ******************************************* event_system.Remove(PROGID_EventSubscription, "SubscriptionID == " + subscription_guid) self.endIPC() # Ends IPC servers self.endAPI() # And deinitializes REST api if needed self.notifyStop()
def CreateSink(): return pythoncom.WrapObject(TransferAdviseSink(), shell.IID_ITransferAdviseSink, shell.IID_ITransferAdviseSink)
def CreateSink(): return pythoncom.WrapObject(FileOperationProgressSink(), shell.IID_IFileOperationProgressSink)
def SvcDoRun(self) -> None: # pylint: disable=too-many-statements, too-many-branches ''' Main service loop ''' servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) # call the CoInitialize to allow the registration to run in an other # thread logger.debug('Initializing coms') pythoncom.CoInitialize() # pylint: disable=no-member if not self.initialize(): self.finish() win32event.WaitForSingleObject(self._hWaitStop, 5000) return # Stop daemon if initializes told to do so # # ******************************** # # * Registers SENS subscriptions * # # ******************************** logger.debug('Registering isens logon') subscription_guid = '{41099152-498E-11E4-8FD3-10FEED05884B}' sl = SensLogon(self) subscription_interface = pythoncom.WrapObject(sl) # pylint: disable=no-member event_system = win32com.client.Dispatch(PROGID_EventSystem) event_subscription = win32com.client.Dispatch(PROGID_EventSubscription) event_subscription.EventClassID = SENSGUID_EVENTCLASS_LOGON event_subscription.PublisherID = SENSGUID_PUBLISHER event_subscription.SubscriptionName = 'UDS Actor subscription' event_subscription.SubscriptionID = subscription_guid event_subscription.SubscriberInterface = subscription_interface event_system.Store(PROGID_EventSubscription, event_subscription) logger.debug('Registered SENS') logger.debug('Initialized, setting ready') # Initialization is done, set machine to ready for UDS, communicate urls, etc... self.setReady() # ********************* # * Main Service loop * # ********************* # Counter used to check ip changes only once every 10 seconds counter = 0 while self._isAlive: counter += 1 try: # Process SENS messages, This will be a bit asyncronous (1 second delay) pythoncom.PumpWaitingMessages() # pylint: disable=no-member if counter >= 10: # Once every 10 seconds counter = 0 self.checkIpsChanged() except Exception as e: logger.error('Got exception on main loop: %s', e) # Continue after a while... # In milliseconds, will break if event hWaitStop is set win32event.WaitForSingleObject(self._hWaitStop, 1000) logger.debug('Exited main loop, deregistering SENS') # ******************************************* # * Remove SENS subscription before exiting * # ******************************************* event_system.Remove(PROGID_EventSubscription, "SubscriptionID == " + subscription_guid) self.finish()
def new(self): return pythoncom.WrapObject(self)