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();
}
@Fernand-Delavy
Copy link

This work ;
FileOpenPicker picker = new FileOpenPicker() { CommitButtonText = "Valider", SuggestedStartLocation = PickerLocationId.ComputerFolder, FileTypeFilter = { ".jpg", ".jpeg" } }; WinUIConversionUtil.InitFileOpenPicker(picker); StorageFile fichier = await picker.PickSingleFileAsync();

But this do not work (MultipleFile)

FileOpenPicker picker = new FileOpenPicker() { CommitButtonText = "Valider", SuggestedStartLocation = PickerLocationId.ComputerFolder, FileTypeFilter = { ".jpg", ".jpeg" } }; WinUIConversionUtil.InitFileOpenPicker(picker); IReadOnlyList<StorageFile> fichiers = await picker.PickMultipleFilesAsync();
Crash System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
COMException: L’application a appelé une interface qui était maintenue en ordre pour un thread différent. (0x8001010E (RPC_E_WRONG_THREAD))

@wbokkers
Copy link
Author

wbokkers commented Mar 1, 2021

Thanks, @Fernand-Delavy. I never tested with PickMultipleFilesAsync. Hopefully this will be fixed in a future WinUI version.

@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