【问题标题】:“Invalid window handle” error when using FileOpenPicker from C# .net framwork 4.7.2 with Microsoft.Windows.SDK.Contracts without UWP使用 C# .net 框架 4.7.2 中的 FileOpenPicker 和没有 UWP 的 Microsoft.Windows.SDK.Contracts 时出现“无效的窗口句柄”错误
【发布时间】:2019-07-23 09:44:19
【问题描述】:

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

我发现一篇帖子遇到了与 C++/WinRT 类似的 a link 问题。答案之一指出“程序将崩溃,因为 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)'

【问题讨论】:

    标签: c# wpf winforms fileopenpicker


    【解决方案1】:

    创建一个文件:

    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
        {
    
        }
    }
    

    【讨论】:

    • 酷!它正在工作! google了很久,终于放弃了。非常感谢。这将帮助很多人了解如何在 .net frameworks WPF 应用程序中初始化 UWP 窗口。
    • 这行得通。我想知道@Cataurus 你是怎么找到这个解决方案的。我在microsoft.com 上没有看到任何相关文件。有没有通用的解决方案或地方可以解决此类问题?
    • 此解决方案适用于 .net 框架。但它无法在 .net.net core 上正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多