[IronPython] COM Interop: Why does this code only work in IronPython Console?

Michael Foord fuzzyman at voidspace.org.uk
Wed Sep 12 19:31:18 CEST 2007

Hello Kelie,

Not sure, but it looks to me like your program will just exit after the 
last line... Try doing a while True loop with a Thread.Sleep() in it to 
keep the interpreter alive...

Michael Foord

Kelie wrote:
> Hello,
> The following code works when typed into IronPython console. But when
> I save the code into a file named excel.py and run ipy.exe excel.py,
> the event handling does not seem to work. Nothing happens when a new
> workbook is created.
> Any suggestion? Thanks a lot.
> import clr
> clr.AddReference("Microsoft.Office.Interop.Excel")
> import Microsoft.Office.Interop.Excel as Excel
> clr.AddReference('System.Windows.Forms')
> import System.Windows.Forms.MessageBox as MessageBox
> def getActiveObject(appId):
> 	from System.Runtime.InteropServices import Marshal
> 	return Marshal.GetActiveObject(appId)
> def getActiveExcelApplication():
> 	return getActiveObject("Excel.Application")
> def onNewWorkbook(workbook):
>     print "Creating a new workbook..."
>     MessageBox.Show("Creating a new workbook...")
> xlApp = getActiveExcelApplication()
> MessageBox.Show(xlApp.ActiveWorkbook.Name) #This line works.
> Excel.AppEvents_Event.add_NewWorkbook(xlApp, onNewWorkbook) #This line
> does not work.

More information about the Ironpython-users mailing list