I'm trying to develop a .NET MAUI class library for folder picking. Following the instructions in Folder Picker .NET MAUI
- firstly, I develop an interface:
public interface IAskDirectory
{
Task<string> AskDirectory();
}
- secondly, I created the file DirectoryAsker.cs and saved in
Platform\Windows
which contains
public class DirectoryAsker : IAskDirectory
{
public async Task<string> AskDirectory()
{
var folderPicker = new FolderPicker();
// Might be needed to make it work on Windows 10
folderPicker.FileTypeFilter.Add("*");
// Get the current window's HWND by passing in the Window object
var hwnd = ((MauiWinUIWindow)App.Current.Windows[0].Handler.PlatformView).WindowHandle;
// Associate the HWND with the file picker
WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);
var result = await folderPicker.PickSingleFolderAsync();
return result?.Path;
}
}
The first question is about the second step: how can I get the current Window handle? The "App" object (see line var hwnd = ...
) is not recognized in a class library.
The second question is related to third step: interface registration with a generic host builder in the MauiProgram.cs
. Is there a way to do this step in the class library or I have to do it every time in my main project, after having added the .dll to the references?