Share via


C++/CLI : IntPtr to an HWND

I was fed up with always having to write different code for x86 or x64 so I wrote intptr_cast<>.

Still a lot of things to think about here but I wrote those couple of lines as a sample.

I thought this might not only give you ideas but maybe trigger some comments:

// Cheap static_assert

template <bool> class static_assert;

template <> class static_assert<true> {};

template <typename T>

T intptr_cast(System::IntPtr intPtr) {

static_assert< sizeof(T) == sizeof(void *) >();

return reinterpret_cast<T>(intPtr.ToPointer());

}

(10/15/2007: I changed the code above to use ToPointer())

 

 

 

And a code sample on how to use this: 

void Cache::Pin(array<String ^> ^ pathsToPin, PinningBehaviour pinningBehaviour, bool pinSubdirectories, bool asynchronously, IntPtr parentWindow ) {

   LastPinningEventRaised = LastEventRaised::None;

   const wchar_t * * paths = NULL;

   try {

      paths = ConstructSingleNativeBuffer(pathsToPin);

      if (!_pinningProgress) {

         _pinningProgress = new Progress(this, ProgressSource::Pinning);

      }

      Tif(_cache->Pin(intptr_cast<HWND>(parentWindow),

  paths,

                      pathsToPin->Length,

                      pinSubdirectories,

                      asynchronously,

                      safe_cast<DWORD>(pinningBehaviour),

                      safe_cast<IOfflineFilesSyncProgress *>(_pinningProgress)));

   } finally {

      delete [] paths;

   }

}

Of course, you could use this for HBRUSH, HPEN, HANDLE, ...

 

May the force be with you.