7

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 File­Open­Picker looks for a Core­Window on the current thread to serve as the owner of the dialog. But we are a Win32 desktop app without a Core­Window." 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)'

Cataurus
  • 78
  • 4
Yuzhe Zhou
  • 157
  • 2
  • 11

1 Answers1

6

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
    {

    }
}
Cataurus
  • 78
  • 4
  • Cool! It's working! I google it for quite long time and finally give up. Thanks a lot. This will help many people about how to Initializing a UWP window in .net frameworks WPF application. – Yuzhe Zhou Aug 26 '19 at 12:37
  • This works. I am wondering @Cataurus how did you find this solution. I didn't see any related documents on `microsoft.com`. Is there a generic solution or place we can get to solve such type of issues? –  Jul 07 '21 at 11:03
  • 1
    This solution works correctly for **.net framework**. But it could not work correctly on **.net** or **.net core**. –  Jul 08 '21 at 04:23
  • https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/winrt-com-interop-csharp – Mihai Socaciu Apr 19 '23 at 05:51