Last active
October 26, 2021 07:37
-
-
Save wbokkers/cc8bcc7bc5a646b82a4d41b337330c69 to your computer and use it in GitHub Desktop.
UWP to WinUI Desktop - FileOpenPicker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.