Search code examples
c++winui-3

How to get pointer position from PointerRoutedEventArgs en C++/WinRT


I'm developing an apllication in WinUI 3 and C++, but I'm stuck with a problem, but I think it must be something simple. I try to get the mouse position in the event OnPointerPressed. Here is my code for the handler function:

void MyWindow:OnPointerPressed(IInspectable const& sender, PointerRoutedEventArgs const& e)
{
    auto tb = sender.try_as<TextBlock>();
    if (!tb) return;

    winrt::Windows::UI::Input::PointerPoint pp = e.GetCurrentPoint(tb);
    winrt::Windows::Foundation::Point pointerPosition = pp.Position();     // ERROR 

    // More code...
}

I assign the event over a TextBlock and try to get the coordinates of muse click relative to that TextBlock, but this code doesn't compile. They tell me an error in the call to pp.Position():

C3779 'winrt::impl::consume_Windows_UI_Input_IPointerPointwinrt::Windows::UI::Input::IPointerPoint::Position': Can't use a function returning 'auto' before being defined'

Maybe it is simple, but I can't see how to get click position.

Thanks!


Solution

  • Well, I achieve to compile. My mistake I think were in the spacename, because I used winrt::Windows::... when I need to use winrt::Microsoft::... for winui 3. Besides, I have include the correct header:

        #include <winrt/Microsoft.UI.Input.h>
        
        void MyWindow:OnPointerPressed(IInspectable const& sender, PointerRoutedEventArgs const& e)
        {
            auto tb = sender.try_as<TextBlock>();
            if (!tb) return;
        
            winrt::Microsoft::UI::Input::PointerPoint pp = e.GetCurrentPoint(tb);
            winrt::Microsoft::Foundation::Point pointerPosition = pp.Position();     // ERROR 
        
            // More code...
        }
    
    

    and it worked!