Reputation: 157
I am trying to use Microsoft.Windows.SDK.Contracts to access the Windows10 API from .net framework WFP application. I want to use the FileOpenPicker() to select the image for OCR processing by Windows.Media.Ocr. But I met the 'Invalid window handle' error when using the picker
I found a post which met the similar a link issue with C++/WinRT. One of the answer point out " The program will crash because the FileOpenPicker looks for a CoreWindow on the current thread to serve as the owner of the dialog. But we are a Win32 desktop app without a CoreWindow." I think the root cause is the same. But I don't know how to fix from the my code based on .net framework side.
public async void Load()
{
var picker = new FileOpenPicker()
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" },
};
var file = await picker.PickSingleFileAsync();
if (file != null)
{
}
else
{
}
}
Error message: System.Exception: 'Invalid window handle.(Exception from HRESULT:0x80070578)'
Upvotes: 7
Views: 5063
Reputation: 1
Similar to @Cataurus !! bind handler with picker !!
private async void Button_Click_Choose_Left_Folder(object sender, RoutedEventArgs e)
{
var folderPicker = new FolderPicker();
// 获取当前窗口的句柄(在 WinUI 或桌面应用中)
IntPtr hwnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
// 将文件夹选择器与窗口句柄关联
WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hwnd);
folderPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
...
var folder = await folderPicker.PickSingleFolderAsync();
}
Upvotes: 0
Reputation: 78
Create a file with:
using System;
using System.Runtime.InteropServices;
namespace <standardnamespace>
{
[ComImport]
[Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IInitializeWithWindow
{
void Initialize(IntPtr hwnd);
}
}
change your code to:
public async void Load()
{
var picker = new FileOpenPicker()
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" },
};
((IInitializeWithWindow)(object)picker).Initialize(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
var file = await picker.PickSingleFileAsync();
if (file != null)
{
}
else
{
}
}
Upvotes: 6