Can anyone tell me why should I use System.Runtime.InteropServices.Marshal.ReleaseComObject(WordObject)


Re: Visual Studio Tools for Office Word Marshal.ReleaseComObject

Douglas H. Troy

Because you can!

... ok, just kidding, there is a good reason ...

Under certain circumstances, you need to release the reference counter on a COM object programmatically. COM objects uses these 'ref counters' to determine when it is safe to unload.

As an example, lets say I have an MS Forms based OptionsButton in my document that I want to hook into so I can set the caption (text) of that control. When we're done using it, we release the object, so the ref counter is decremented.

Example code:
object controlButton = "Forms.OptionButton.1";
object selectionRange = selection.Range;

// create an instance of the control in the document
Word.InlineShape ishape = selection.InlineShapes.AddOLEControl(ref controlButton, ref selectionRange);

// -- Cast the COM object to an MSForms OptionButton Interface
MSForms.OptionButton ob = ishape.OLEFormat.Object as MSForms.OptionButton;

// -- set the GroupName, caption & autosize properties on the ctrl
ob.GroupName = guid.ToString();
ob.Caption = "this is my radio group button";
ob.AutoSize = true;
// -- release ref ptr to obj

Hope that answers your question ...

Re: Visual Studio Tools for Office Word Marshal.ReleaseComObject


I think you have answered my quesiton. Just to make sure does my code below in finally is the best way to clean up word objects

WordApp = New Word.Application
WordDoc =
New Word.Document


 'Do word related tasks


 WordDoc =
 WordApp = Nothing

End Try

Re: Visual Studio Tools for Office Word Marshal.ReleaseComObject

Douglas H. Troy

My example was for dealing with Word objects in general, not the application object itself.

In your circumstance, you are dealing with the actual Word Application object, you might want to refer to the following MSDN article on the subject:

Quiting Office Application