使用 C# .net framwork 4.7.2 中的 FileOpenPicker 与 Microsoft.Windows.SDK.Contracts(不带 UWP)时出现“无效窗口句柄”错误

问题描述 投票:0回答:2

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

我发现一篇文章遇到了与 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)”

c# wpf winforms fileopenpicker
2个回答
6
投票

创建一个文件:

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
    {

    }
}

0
投票

类似于@Cataurus !!将处理程序与选择器绑定!!

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();
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.