mhammond / pywin32

Python for Windows (pywin32) Extensions
5.07k stars 799 forks source link

By using Python win 32 I'm not able to bind event using SAP GUI Scripting API. #2433

Open girish-kadambari opened 2 days ago

girish-kadambari commented 2 days ago

For all bugs, please provide the following information:

Code:

Expected behavior and actual behavior

Steps to reproduce the problem

  1. ...
  2. ...
  3. ...
import win32com.client
import pythoncom

class SAPSessionEvents:
    """Class to handle SAP GUI events."""

    def OnChange(self, session, component, command_array):
        """Handles the Change event."""
        print("Change event triggered:")
        print(f"Session: {session}")
        print(f"Component: {component}")
        print(f"CommandArray: {command_array}")

def connect_to_sap():
    """Connect to the SAP GUI scripting engine."""
    try:
        # Connect to the SAP GUI Scripting Engine
        sap_gui = win32com.client.GetObject("SAPGUI")
        if not sap_gui:
            raise Exception("SAP GUI is not running. Please start SAP GUI and log in to a system.")

        # Access the scripting engine
        application = sap_gui.GetScriptingEngine
        if not application:
            raise Exception("Could not access the SAP scripting engine.")

        # Get the first active connection
        connection = application.Connections(0)
        if not connection:
            raise Exception("No active SAP GUI connection found.")

        # Get the first active session
        session = connection.Sessions(0)
        if not session:
            raise Exception("No active SAP GUI session found.")

        print("Connected to SAP GUI session.")
        return session

    except Exception as e:
        print(f"Error connecting to SAP: {e}")
        return None

def main():
    """Main function to connect and handle SAP GUI events."""
    session = connect_to_sap()
    if not session:
        return

    try:
        # Attach the event handler to the session
        print("Setting up event handling...")
        events_handler = win32com.client.WithEvents(session, SAPSessionEvents)

        print("Listening for SAP GUI events. Press Ctrl+C to stop.")
        while True:
            pythoncom.PumpWaitingMessages()

    except Exception as e:
        print(f"Error setting up event handling: {e}")

if __name__ == "__main__":
    main()

System information

Python version and distribution:

pywin32 version:

Installed from PyPI or exe installer:

Windows Version:

DLL locations: