c# - “Invalid window handle” 使用 C# .net 框架 4.7.2 中的 FileOpenPicker 和 Microsoft.Windows.SDK.Contracts 而没有 UWP 时出现错误

标签 c# wpf winforms fileopenpicker

我正在尝试使用 Microsoft.Windows.SDK.Contracts 从 .net 框架 WFP 应用程序访问 Windows10 API。
我想使用 FileOpenPicker() 选择图像以供 Windows.Media.Ocr 进行 OCR 处理。但是我在使用选择器时遇到了“无效的窗口句柄”错误

我找到了一个遇到类似 a link 的帖子C++/WinRT 的问题。答案之一指出“程序将崩溃,因为 FileOpenPicker 在当前线程上寻找一个 CoreWindow 作为对话框的所有者。但我们是一个没有 CoreWindow 的 Win32 桌面应用程序。”我认为根本原因是一样的。但我不知道如何从基于.net 框架端的代码修复。

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
    {

    }
}

错误消息:System.Exception:'无效的窗口句柄。(来自 HRESULT 的异常:0x80070578)'

最佳答案

创建一个文件:

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);
    }
}

将您的代码更改为:
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
    {

    }
}

关于c# - “Invalid window handle” 使用 C# .net 框架 4.7.2 中的 FileOpenPicker 和 Microsoft.Windows.SDK.Contracts 而没有 UWP 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57161258/

相关文章:

c# - 将外键映射为主键 Fluent NHibernate

c# - 'run all tests' 发现但未运行 XUnit 测试

c# - 在 C# 中强制命名空间之间的类型可见性

wpf - 如何构建一个 Windows 应用程序来拦截击键和鼠标点击并将其传递给其他应用程序?

c# - 如何将标签添加到 DataGridView 单元格

c# - 如何中断正在运行的线程并使其运行另一个方法?

WPF 相当于 Windows 窗体中的 'Control.CheckForIllegalCrossThreadCalls'

c# - 在带有用户控件的主窗口中使用 RoutedCommand

c# - 滑动效果不流畅

winforms - DataGridViewCheckBoxCell 类型的 DataGridView 列始终处于只读/禁用状态