Skip to content

Instantly share code, notes, and snippets.

@mjfusa
Last active November 21, 2021 06:37
Show Gist options
  • Save mjfusa/6da7e0138d91cd1e9d0ce2f2fb6a7540 to your computer and use it in GitHub Desktop.
Save mjfusa/6da7e0138d91cd1e9d0ce2f2fb6a7540 to your computer and use it in GitHub Desktop.
Project Reunion 0.5 WinUI Desktop - Store IAP and Window Initialization
using Microsoft.UI.Xaml;
using System;
using System.Runtime.InteropServices;
using Windows.Services.Store;
using WinRT;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace App12Reunion
{
/// <summary>
/// An empty window that can be used on its own or navigated to within a Frame.
/// </summary>
[ComImport]
[Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInitializeWithWindow
{
void Initialize(IntPtr hwnd);
}
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
public StoreContext m_StoreContext { get; private set; }
private void myButton_Click(object sender, RoutedEventArgs e)
{
myButton.Content = "Clicked";
DoInAppPurchase();
}
public async void DoInAppPurchase()
{
// initialize m_StoreContext in Window_Activated
var result = await m_StoreContext.RequestPurchaseAsync("9NWMTMH9PNGB");
if (result.Status == StorePurchaseStatus.Succeeded)
{
textBlock.Text = $"Store purchase succeeded: {result.Status}";
} else
{
textBlock.Text = $"Store purchase failed: {result.Status}";
}
}
bool bActivated = false;
private void Window_Activated(object sender, WindowActivatedEventArgs args)
{
IntPtr hwnd = PInvoke.User32.GetActiveWindow();
if ( (hwnd == (IntPtr)0) || (bActivated) )
{
return;
}
m_StoreContext = StoreContext.GetDefault();
IInitializeWithWindow initializeWithWindowWrapper = ((object)m_StoreContext).As<IInitializeWithWindow>();
initializeWithWindowWrapper.Initialize(hwnd);
bActivated = true;
}
}
}
@shuice
Copy link

shuice commented Nov 21, 2021

It works, but i do not know why the old style do not works, it saids type cast error.

IInitializeWithWindow initWindow = (IInitializeWithWindow)(object)m_StoreContext;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment