3

I have some C# code that is used in a win32 application via ComInterop, it is embedded as an OleControl.

In my win32 app I send through the handle to the containing window for the C# control (win32 app code):

oControl:ShowPreview(5, 3, INT(_CAST, SELF:Handle(0)))

In my C# code I pick this up and store it in an IntPtr (C# code):

private IntPtr _parentWindowPtr;

public int ShowPreview(int someVar1, int someVar2, int parent)
{
    ...
    _parentWindowPtr = new IntPtr(parent);
    ...
}

Should I be releasing or destroying the IntPtr in the C# code?

Andrew
  • 691
  • 6
  • 17

1 Answers1

3

This is a summary of my comment above


Should I be releasing or destroying the IntPtr in the C# code?

Quite simply, you should not be releasing window handles when dealing with Ole/COM. Ole Controls/COM ActiveX can be thought of as a higher-level UI abstraction (involving protocols along IOleControl; IOleControlSite) above mere windows. Instead of releasing window handles, you release COM references which ultimately result in the window being destroyed and the handle released.

In your particular case, you pass through the handle of a native window to your COM control to embed itself into. Best practice is that the calling process (native exe) has ownership of the containing window and so the COM control should not take upon itself to destroy the container.

How to release a COM object in c#

As a reminder, to release COM objects in c# best practice is to:

Marshal.ReleaseComObject(someComObject);

An Excel chart embedded into Microsoft Word does not take it upon itself to close Word.

Tell me more

  • Hmm not saying I doubt you but Would you please post a link to a source regarding this. Also, it would be perfect if you post a snippet of how to release a COM ref. – CodingYoshi Apr 27 '18 at 04:09
  • @CodingYoshi Thanks. See update. Found a few links that might be helpful –  Apr 27 '18 at 04:29