I am using Windows Forms and C# to access a COM object. The COM object
(“tablet” in the code examples below) requires a window handle. I am using
the form handle (this.Handle) to pass to the COM object. I had assumed that
I would have to use a GCHandle to pass to the COM object but I can’t get it
to work. See below for examples;
This doesn’t work (COM object chokes the moment it uses the hWnd:
GCHandle gch;
gch = GCHandle.Alloc( this.Handle, GCHandleType.Pinned );
int hWnd = (int)gch.AddrOfPinnedObject();
tablet.set_hWnd( ref hWnd );
The following code works just fine:
int hWnd = (int)this.Handle;
tablet.set_hWnd( ref hWnd );
Can anyone shed any light on whether I should be using GCHandle and why it’s
not working for me?
Bill
Mattias Sj?gren - 10 Dec 2004 23:50 GMT
>Can anyone shed any light on whether I should be using GCHandle
Not in this case, no.
Mattias

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
liggett78 - 13 Dec 2004 13:37 GMT
Try this:
GCHandle gch = GCHandle(this.Handle);
tablet.set_hWnd( (IntPtr) gch);
You should free the handle after finished, e.g. gch.Free(). Generally
GCHandle is used to prevent something from being collected by the GC in the
meanwhile (see example code in SDK). I think in your case it's better to use
either direct handle or wrap it in HandleRef() and pass to the COM component.
Regards, Joerg
> I am using Windows Forms and C# to access a COM object. The COM object
> (“tablet” in the code examples below) requires a window handle. I am using
[quoted text clipped - 18 lines]
>
> Bill