LoginSignup
2
1

More than 3 years have passed since last update.

[Rust/WinRT] 既定のプログラムを使用してファイルを開く

Last updated at Posted at 2020-10-04

任意のファイル [テキスト (.txt), 画像 (.jpeg, .png, etc.), 音声 (.mp3, etc.), 動画 (.mp4, etc.), PowerPoint (.pptx), PDF (.pdf) 等なんでもよいです] を, 既定のプログラムで開く Rust/WinRT プログラムです.

環境

本記事の執筆環境は以下の通りです.

  • Windows 10 v1909
  • Rust 1.46.0 (stable-x86_64-pc-windows-msvc)
  • winrt 0.7.2

コード

import

winrt::import!(
    dependencies
        os
    types
        windows::system::Launcher
);

既定のプログラムを使用して開く

コマンドライン引数としてファイルのパスを与えると, 既定のプログラムでそれを開くプログラムです (つまり cmd/PS の start コマンドとほぼ同じものです). ただしファイルパスはフルパスでなければ動きません.

use windows::{
    storage::StorageFile,
    system::Launcher,
};

fn main() -> winrt::Result<()> {
    let path = std::env::args().nth(1).expect("ファイルパスを引数に指定してください.");

    // ファイルパスから `StorageFile` オブジェクトを取得
    let file = StorageFile::get_file_from_path_async(path)?.get()?;

    // 既定のプログラムを使用して `file` を開く
    Launcher::launch_file_async(file)?.get()?;
    Ok(())
}

使用するプログラムを選択して開く (動かなかった)

参考文献によると, アプリ選択画面を表示してユーザーに使用するアプリを選択させることも可能なはずですが, 私の環境ではうまく動きませんでした (ビルドは成功して実行できるもののアプリ選択画面が表示されずに終了してしまう). 一応コードを載せておきます.

use windows::{
    storage::StorageFile,
    system::{Launcher, LauncherOptions},
};

fn main() -> winrt::Result<()> {
    let path = std::env::args().nth(1).expect("ファイルパスを引数に指定してください.");

    // ファイルパスから `StorageFile` オブジェクトを取得
    let file = StorageFile::get_file_from_path_async(path)?.get()?;

    // プログラム選択画面を表示するようにオプションを指定
    let options = LauncherOptions::new()?;
    options.set_display_application_picker(true)?;

    Launcher::launch_file_with_options_async(file, options)?.get()?;
    Ok(())
}

私としては既定のプログラムで起動できれば十分だったのでこれ以上追及しませんでしたが, うまく動かないのは気持ちよくないので, 気が向いたら SO あたりに質問を投げたりして解決しておきたいところです.

参考文献

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1