Search code examples
uwpwindows-store-appsuwp-xamlads

How to get the event when clicking the microsoft ad in uwp


I'm using Microsoft Advertising SDK for xaml. And my app can show the ad now. But I want to know the event when user click the ad.

None of the following event worked.

    <ads:AdControl x:Name="adAd" Grid.Row="3" ApplicationId="" AdUnitId=""
         Width="300" Height="250" AdRefreshed="OnAdRefreshed" 
         ErrorOccurred="OnErrorOccurred"
         Tapped="OnAdTapped" OnPointerDown="OnAdPointerDown" 
         PointerPressed="OnAdPointerPressed"/>

enter image description here


Solution

  • None of the following event worked.

    Actually, you could not use the above event directly, because it will be ignored by hyperlink click where displayed in the Ad WebView. enter image description here

    If you want detect click event of AdControl, you could use some indirect way that use VisualTreeHelper to get the AD WebView and listen it's NavigationStarting event

    public static T MyFindListBoxChildOfType<T>(DependencyObject root) where T : class
    {
        var MyQueue = new Queue<DependencyObject>();
        MyQueue.Enqueue(root);
        while (MyQueue.Count > 0)
        {
            DependencyObject current = MyQueue.Dequeue();
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
            {
                var child = VisualTreeHelper.GetChild(current, i);
                var typedChild = child as T;
                if (typedChild != null)
                {
                    return typedChild;
                }
                MyQueue.Enqueue(child);
            }
        }
        return null;
    }
    
    
    private void AdTest_AdRefreshed(object sender, RoutedEventArgs e)
    {
        var ADWebView = MyFindListBoxChildOfType<WebView>(AdTest);
        ADWebView.NavigationStarting += ADWebView_NavigationStarting;
    }
    
    private void ADWebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        System.Diagnostics.Debug.WriteLine("AD clicked---------------");
    }
    

    In order to avoid interference from page navigation, please unsubscribe NavigationStarting in OnNavigatedFrom override method.

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        ADWebView.NavigationStarting -= ADWebView_NavigationStarting;
    }