1

I was following https://stackoverflow.com/a/57599016/8800839 to register the window to the filepicker, because I ran into the same problem. While doing so, I get an "Access Denied" error while calling Initialize on IInitializeWithWindow

Output right before the window closes:

[src\main.rs:22] interop.WindowHandle() = Ok(
    HWND(
        12259034,
    ),
)
[src\main.rs:23] file_picker_i.Initialize(hwnd) = Err(
    Error {
        code: 0x80070005,
        message: Access is denied.
        ,
    },

main.rs:

#![allow(non_snake_case)]
use windows::core::*;
use windows::ApplicationModel::Activation::LaunchActivatedEventArgs;
use windows::ApplicationModel::Package;
use windows::Storage::Pickers::{FileOpenPicker, PickerLocationId, PickerViewMode};
use windows::UI::Xaml::*;
use windows::Win32::Foundation::HWND;
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx};
use windows::Win32::System::WinRT::ICoreWindowInterop;
use windows::Win32::UI::WindowsAndMessaging::{MB_ICONSTOP, MB_OK, MessageBoxW};
use windows::Win32::UI::Shell::IInitializeWithWindow;

#[implement(IApplicationOverrides)]
struct App ();
impl IApplicationOverrides_Impl for App {
    fn OnLaunched(&self, _: &Option<LaunchActivatedEventArgs>) -> Result<()> {
        let window = Window::Current()?;
        let interop = window.CoreWindow()?.cast::<ICoreWindowInterop>()?;
        let file_picker = FileOpenPicker::new()?;
        let file_picker_i = file_picker.cast::<IInitializeWithWindow>()?;
        unsafe {
            let hwnd = dbg!(interop.WindowHandle())?;
            dbg!(file_picker_i.Initialize(hwnd))
        }
    }
}
fn main() -> Result<()> {
    unsafe {
        CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED)?;
        if let Err(result) = Package::Current() {
            MessageBoxW(
                HWND::default(),
                "This sample must be registered (via register.cmd) and launched from Start.",
                "Error",
                MB_ICONSTOP | MB_OK,
            );
            return Err(result);
        }
    }
    Application::Start(ApplicationInitializationCallback::new(move |_| {
        Application::compose(App())?;
        Ok(())
    }))
}

Cargo.toml:

...
[dependencies.windows]
version = "0.35.0"
features = [
    "alloc",
    "implement",
    "ApplicationModel_Activation",
    "UI_Core",
    "UI_Xaml_Controls",
    "UI_Xaml",
    "Storage",
    "Storage_Pickers",
    "System",
    "Win32_System_WinRT",
    "Foundation_Collections",
    "UI_Xaml_Controls_Primitives",
    "Win32_Foundation",
    "Win32_Storage_Packaging_Appx",
    "Win32_System_Com",
    "Win32_UI_Shell",
    "Win32_UI_WindowsAndMessaging",
]
...

What is the cause of this error, and how can I overcome this error (to successfully use the FileOpenPicker)?

JFFIGK
  • 632
  • 1
  • 7
  • 24
  • 1
    IIRC, the file/directory pickers in Win32 can only be called from a single-threaded apartment (STA). I don't know if that's the case with WinRT as well, but I wouldn't be surprised if it was. Try changing `COINIT_MULTITHREADED` to `0` or to `COINIT_APARTMENTTHREADED`. – Francis Gagné Apr 21 '22 at 02:22
  • I believe it is possible to use the `FileOpenPicker` with `COINIT_MULTITHREADED`, because I ([and somone else](https://github.com/microsoft/windows-rs/issues/1708)) have already used it without registering the window handle ... running into a deadlock, which lead me to [registering a window handle manually](https://github.com/microsoft/windows-rs/issues/1596). Using `COINIT_APARTMENTTHREADED` does neither work with any of my apps nor with [the official sample app](https://github.com/microsoft/windows-rs/tree/master/crates/samples/xaml_app): the app opens and immediately closes again – JFFIGK Apr 21 '22 at 10:00
  • Since you have CoreWindow why do you want pass a native handle? – Simon Mourier Apr 21 '22 at 13:25
  • @SimonMourier I linked to a StackOverflow Question that is about the same problem which I have had, i.e. I got a "Invalid window handle" exception (respectively error), which suggests this solution. See also [Retrieve a window handle \(HWND\)](https://learn.microsoft.com/en-us/windows/apps/develop/ui-input/retrieve-hwnd). This seems to happen, because I try to use the `FileOpenPicker` outside a callback from the UI (probably executed on the UI Thread) using tokio... – JFFIGK Apr 21 '22 at 14:19
  • Link in question is about WPF and this link is about WinUI3. You don't use these do you? – Simon Mourier Apr 21 '22 at 14:22
  • I don't, I think. However, it seems like it [should work this way with a CoreWindow](https://github.com/microsoft/windows-rs/issues/1596). And all these resources are about the same API (at least it seems like it). What are you suggesting? – JFFIGK Apr 21 '22 at 14:35
  • WinUI3, UWP, WPF and WinRT are different things (UWP sits on WinRT and adds sandbox, and is more or less deprecated). Documentation on Microsoft's site is not always clear... – Simon Mourier Apr 21 '22 at 14:44
  • so, how to properly register a windows handle then? – JFFIGK Apr 21 '22 at 14:52
  • Can you post all files somewhere? – Simon Mourier Apr 21 '22 at 14:55
  • You say that you're using tokio, but the code doesn't. Can you show a [mcve]? – IInspectable Apr 21 '22 at 16:00
  • @Iinspectable I removed everything, since the above issue remained despite removing everything. I am going to show a more complete example and post the link here – JFFIGK Apr 21 '22 at 16:13
  • On a second thought, as I understand the generated source code of the `windows` crate, types from the `UI::Xaml` namespace reference the UI framework that's part of the OS (i.e. neither WinUI2 nor WinUI3). To my knowledge, this UI framework is only supported when targeting the UWP. Are you targeting the UWP or is this a classic desktop application? – IInspectable Apr 21 '22 at 16:17
  • @Simon Mourier I uploaded the project [here](https://github.com/aWeinzierl/SO). – JFFIGK Apr 21 '22 at 20:06
  • @IInspectable I think I am targeting UWP. You can determine what I actually target from the uploaded project, should I be in the wrong – JFFIGK Apr 21 '22 at 20:09
  • 1
    Yes, that's targeting the UWP indeed. Which is curious, too. Unless you're developing for the XBox, HoloLens, or a Windows 10 Mobile device, there's hardly any reason to target the UWP. Irrespective of that, the GitHub repo doesn't actually use the `FileOpenPicker`. Is this intentional? – IInspectable Apr 21 '22 at 20:50
  • The repository is in the state where I try to use a `FileOpenPicker`. I marked the possible locations (Option 1 and Option 2 in comments). Didn't see a point in including the not working code, though I can add a few branches tomorrow which demonstrate multiple failed attempts (including the one of this SO question) if it helps you. I don't have strong opinions on UWP vs ... , WinUI3/windows-app-sdk-rs which I'd consider moving to at some point seems to be pretty alpha atm. – JFFIGK Apr 21 '22 at 22:50

0 Answers0