Skip to content

Instantly share code, notes, and snippets.

@wbokkers
Last active October 26, 2021 07:37
Show Gist options
  • Save wbokkers/cc8bcc7bc5a646b82a4d41b337330c69 to your computer and use it in GitHub Desktop.
Save wbokkers/cc8bcc7bc5a646b82a4d41b337330c69 to your computer and use it in GitHub Desktop.
UWP to WinUI Desktop - FileOpenPicker
FileOpenPicker open = new();
open.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
open.FileTypeFilter.Add("*");
WinUIConversionUtil.InitFileOpenPicker(open);
var file = await open.PickSingleFileAsync();
if (file != null)
{
var text = await FileIO.ReadTextAsync(file);
MessageDialog dlg = new(text);
await dlg.ShowAsync();
}
public static class WinUIConversionUtil
{
public static void InitFileOpenPicker(FileOpenPicker picker)
{
if (Window.Current == null)
{
var initializeWithWindowWrapper = picker.As<IInitializeWithWindow>();
var hwnd = GetActiveWindow();
initializeWithWindowWrapper.Initialize(hwnd);
}
}
[ComImport, Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInitializeWithWindow
{
void Initialize([In] IntPtr hwnd);
}
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto, PreserveSig = true, SetLastError = false)]
public static extern IntPtr GetActiveWindow();
}
@VuQuang
Copy link

VuQuang commented Oct 26, 2021

Sometime, will have trouble with Member 'FileOpenPicker.As<WinUIConversionUtil.IInitializeWithWindow>()' cannot be accessed with an instance reference; qualify it with a type name instead.

Import using WinRT to resolve it.

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