How should I use AddHandler in cppwinrt with Handler objects?

250 views Asked by At

In the C++/WinRT reflection, the API AddHandler is defined as

UIElement::AddHandler(Windows::UI::Xaml::RoutedEvent const& routedEvent, Windows::foundation::IInspectable const& handler, bool handledEventsToo) const

But the handlers seems to only inherit from IUnknown. For example, this is the declaration of KeyEventHandler:

struct KeyEventHandler : Windows::foundation::IUnknown

What is the solution for registering an event handler?

2

There are 2 answers

0
iohanson On BEST ANSWER

It seems like we need to call box_value(handler) which will convert it into an IInspectable. It is not obvious at all, and you cannot find any samples on MSDN.

0
Ryan Shepherd On

To elaborate on iohanson's answer, yes, the delegate needs to be boxed up. WinRT delegates are IUnknown, not IInspectable. AddHandler expects to get an IReference<T> where T is a delegate for a RoutedEvent.

I opened an issue on cppwinrt to see if we can get some more helpful overloads, since cppwinrt we don't do the same magic boxing CX users enjoyed. https://github.com/microsoft/cppwinrt/issues/776