0

I'm creating a COM object that needs a HWND for a window handle coming from WPF (HwndHost). All I have is IntPtr which comes from HwndHost.Handle.

How do I pass this correctly to my COM object? I'm not using P/Invoke.

I don't care whether the conversion happens in .NET or C++, but prefer whichever is best practice.

Deanna
  • 23,876
  • 7
  • 71
  • 156
DaveO
  • 1,909
  • 4
  • 33
  • 63

1 Answers1

3

Since type safety is out of the window already anyway, can't you just pass it as an int? A hwnd is just a 32-bit value (not sure if it's 64 bits on 64 bit Windows versions?). Pass it as an int to your COM object, cast it to an HWND there and you're good to go.

Roel
  • 19,338
  • 6
  • 61
  • 90
  • Yes, an `HWND` is a pointer. It's going to be 64 bits on a 64-bit version of Windows. You can't just use an `int`; you'll chop off part of the pointer. – Cody Gray - on strike Dec 20 '11 at 08:55
  • @Cody: `HWND`s are not real pointers, they can be truncated to 32-bit, see http://stackoverflow.com/questions/1822667/how-can-i-share-hwnd-between-32-and-64-bit-applications-in-win-x64 – Roman R. Dec 20 '11 at 09:20
  • @Roman: Not according to the documentation. I'm not sure what you're looking at. Someone asserting that because of backwards compatibility, it will probably work? Not exactly what I want to rely on when writing a new application. – Cody Gray - on strike Dec 20 '11 at 09:28
  • @Cody: http://msdn.microsoft.com/en-us/library/aa384203%28VS.85%29.aspx "... only the lower 32 bits are significant, so it is safe to truncate the handle... that... include handles to user objects such as windows (HWND)..." – Roman R. Dec 20 '11 at 09:33
  • @RomanR. - Forgot the following statement - **or sign-extend the handle (when passing it from 32-bit to 64-bit).** – Security Hound Dec 20 '11 at 19:10
  • As an addition and in response to the comments, it's probably more portable (and maybe it's what I meant but slipped up, I'm not sure) to stuff the HWND value into an IntPtr or another pointer value (I'm not sure how that works when mixing CLR/COM) since that'll give you 64 bits on 64 bits Windows and 32 bits on 32 bits Windows (meaning never having to worry about chopping off the HWND, although Roman's link confirms what I would have expected - otherwise 32 bit applications running on 64 bit Windows couldn't communicate with other windows through windows messages). – Roel Dec 21 '11 at 09:17