アプリからコンテンツを共有する - Windows共有を統合する

Windows共有シートは、ユーザーがアプリから他のWindows アプリにコンテンツを送信できるシステム提供の UI です。 このガイドでは、パッケージ アプリ (MSIX)、プログレッシブ Web Apps (PWA)、およびパッケージ化されていない Win32 アプリ間で共有コントラクトを実装する方法について説明します。

この記事で

セクション あなたが見つけるもの
共有アプローチを選択する UWP、デスクトップ、または PWA アプリに適した API セットを選択する
UWP アプリ用の共有を実装する DataTransferManager.GetForCurrentView および ShowShareUI
PWA の共有機能を実装する Web 共有 API の統合
デスクトップ アプリ用の共有を実装する IDataTransferManagerInteropWinUI 3、WPF、WinForms のウィンドウごとの共有
ソース側のイベント ターゲットの選択、完了、取り消しを観察する
共有のベスト プラクティス 信頼できるソース側の動作に関する推奨事項

共有アプローチを選択する

アプリの種類 Approach API セット
UWP アプリ DataTransferManager.GetForCurrentViewShowShareUI を使用する Windows.ApplicationModel.DataTransfer
デスクトップ アプリ (WinUI 3、WPF、WinForms) ウィンドウごとの共有 (パッケージ化またはパッケージ化されていない) に IDataTransferManagerInterop を使用する COM 相互運用機能を使用したWindows ランタイム
プログレッシブ Web アプリ (PWA) Web 共有 API + Windows統合を使用する W3C Web Share

UWP アプリ用の共有を実装する

Important

DataTransferManager.GetForCurrentView および ShowShareUI は、UWP アプリでのみサポートされます。 デスクトップ アプリ (WinUI 3、WPF、または WinForms - パッケージ化またはパッケージ化されていない) では、「IDataTransferManagerInteropする」に示されている パターンを使用する必要があります。

1. DataTransferManager を取得する

ページの初期化で、 DataTransferManagerへの参照を取得します。

using Windows.ApplicationModel.DataTransfer;

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        DataTransferManager dtm = DataTransferManager.GetForCurrentView();
        dtm.DataRequested += OnDataRequested;
    }
}

2. DataPackage にデータを入力する

ユーザーが共有を開始するときに (たとえば、[共有] ボタンをクリック)、コンテンツとメタデータを含む DataPackage を作成します。

private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
    DataRequest request = args.Request;
    DataPackage data = request.Data;

    // Set a title (required)
    data.Properties.Title = "My shared content";

    // Set content - choose one or more:
    data.SetText("Here's some text to share");

    // For URLs, use SetWebLink to enable rich link previews:
    // data.SetWebLink(new Uri("https://example.com"));

    // For files or images:
    // IStorageItem item = await StorageFile.GetFileFromPathAsync(filePath);
    // data.SetStorageItems(new[] { item });

    // Optional: add description and thumbnail
    data.Properties.Description = "A brief description";
    // data.Properties.Thumbnail = /* RandomAccessStreamReference */;
}

Tip

URL を共有する場合は、SetWebLinkではなくSetApplicationLink (ディープ リンクの場合はSetText) を使用します。 ターゲット アプリでは、リッチ リンク プレビューを生成し、プレーン テキストとして扱うのではなく、ナビゲーションを正しく処理できます。

3. 共有 UI を表示する

ボタンのクリックまたはメニュー コマンドからシートの共有をトリガーします。

private void ShareButton_Click(object sender, RoutedEventArgs e)
{
    // ShowShareUI is a static method on DataTransferManager.
    // The DataRequested handler was registered in step 1.
    DataTransferManager.ShowShareUI();
}

プログレッシブ Web Apps (PWA) の共有を実装する

PWA は W3C Web 共有 API を使用します。 PWA に、Windowsと統合するために必要なマニフェスト プロパティがあることを確認します。

{
  "name": "My PWA",
  "short_name": "MyPWA",
  "share_target": {
    "action": "/share",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "files": [
        {
          "name": "media",
          "accept": ["image/*"]
        }
      ]
    }
  }
}

PWA JavaScript で、Web 共有 API を使用します。

async function shareContent() {
  if (navigator.share) {
    try {
      await navigator.share({
        title: 'Check this out',
        text: 'Great content',
        url: 'https://example.com/page'
      });
    } catch (err) {
      if (err.name !== 'AbortError') {
        console.error('Share failed:', err);
      }
    }
  }
}

デスクトップ アプリ用の共有を実装する (WinUI 3、WPF、WinForms)

デスクトップ アプリは、パッケージ化されているかパッケージ化されていないかにかかわらず、 IDataTransferManagerInterop インターフェイスを使用してウィンドウごとに共有シートにアクセスします。 これは、WinUI 3、WPF、および WinForms アプリに適用されます。

1. 相互運用インターフェイスを宣言し、DataTransferManager を取得する

using Windows.ApplicationModel.DataTransfer;

[System.Runtime.InteropServices.ComImport]
[System.Runtime.InteropServices.Guid("3A3DCD6C-3EAB-43DC-BCDE-45671CE800C8")]
[System.Runtime.InteropServices.InterfaceType(
    System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
interface IDataTransferManagerInterop
{
    IntPtr GetForWindow([System.Runtime.InteropServices.In] IntPtr appWindow,
        [System.Runtime.InteropServices.In] ref Guid riid);
    void ShowShareUIForWindow(IntPtr appWindow);
}

public sealed partial class MainWindow // WinUI 3 Window, WPF Window, or WinForms Form
{
    // IID of DataTransferManager, passed as the riid to GetForWindow:
    static readonly Guid _dtm_iid =
        new Guid(0xa5caee9b, 0x8708, 0x49d1, 0x8d, 0x36, 0x67, 0xd2, 0x5a, 0x8d, 0xa0, 0x0c);

    private DataTransferManager _dtm;

    // Call this from your window or form constructor (or load handler):
    private void InitializeShare()
    {
        // Retrieve the window handle (HWND) for the current window:
        //   WinUI 3:  IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
        //   WPF:      IntPtr hWnd = new System.Windows.Interop.WindowInteropHelper(this).Handle;
        //   WinForms: IntPtr hWnd = this.Handle;
        IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);

        IDataTransferManagerInterop interop =
            DataTransferManager.As<IDataTransferManagerInterop>();
        _dtm = WinRT.MarshalInterface<DataTransferManager>.FromAbi(
            interop.GetForWindow(hWnd, _dtm_iid));

        _dtm.DataRequested += (sender, args) => OnDataRequested(args);
    }
}

2. 入力して表示する

private void OnDataRequested(DataRequestedEventArgs args)
{
    DataRequest request = args.Request;
    DataPackage data = request.Data;

    data.Properties.Title = "Share from my desktop app";
    data.SetText("Shared content");

    // For URLs:
    // data.SetWebLink(new Uri("https://example.com"));

    // For files:
    // var item = await StorageFile.GetFileFromPathAsync(filePath);
    // data.SetStorageItems(new[] { item });
}

// In your Share button handler:
private void ShareButton_Click()
{
    var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
    var interop = DataTransferManager.As<IDataTransferManagerInterop>();
    interop.ShowShareUIForWindow(hWnd);
}

完全な例については、WPF共有ソースのサンプルを参照してください。

ソース側のイベント

ソース アプリでこれらのイベントを使用して、ユーザーが共有を開いた後に何が起こったかを観察します。

API 起動時 使用する理由
DataTransferManager.DataRequested ユーザーが共有操作を開始する DataPackage をビルドしてアタッチする
DataTransferManager.TargetApplicationChosen ユーザーがターゲット アプリを選択する ターゲットの選択に関するオプションのテレメトリ
DataPackage.ShareCompleted 共有の完了 省略可能な成功テレメトリ
DataPackage.ShareCanceled ユーザーが共有を取り消す オプションのキャンセル テレメトリ

Note

この例では、簡潔にするために GetForCurrentView を使用します。これは UWP アプリに適用されます。 デスクトップ アプリで、前に示したDataTransferManagerを通じてIDataTransferManagerInterop.GetForWindowを取得し、同じイベントをアタッチします。

private void RegisterShareEvents()
{
  var dtm = DataTransferManager.GetForCurrentView();
  dtm.DataRequested += OnDataRequested;
  dtm.TargetApplicationChosen += OnTargetChosen;
}

private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
  DataRequest request = args.Request;
  request.Data.Properties.Title = "Share from my app";
  request.Data.SetText("Hello from Windows Share");

  request.Data.ShareCompleted += OnShareCompleted;
  request.Data.ShareCanceled += OnShareCanceled;
}

private void OnTargetChosen(DataTransferManager sender, TargetApplicationChosenEventArgs args)
{
  // Optional: telemetry only
  Debug.WriteLine($"Target app: {args.ApplicationName}");
}

private void OnShareCompleted(DataPackage sender, ShareCompletedEventArgs args)
{
  Debug.WriteLine("Share completed");
}

private void OnShareCanceled(DataPackage sender, object args)
{
  Debug.WriteLine("Share canceled");
}

Note

DataPackage.OperationCompleted および DataPackage.Destroyed は、主にクリップボードと貼り付けワークフロー用です。 一般に、共有ソース のシナリオでは必要ありません。

共有のベスト プラクティス

このチェックリストを使用して、ソース側の動作を予測可能な状態に保ちます。

推奨 避ける 共同作業の重要性
URL に SetWebLink または SetApplicationLink を使用する URL に SetText を使用する リンクがターゲット アプリで正しくレンダリングおよびルーティングされる
Titleと省略可能なメタデータ (Description、サムネイル) を設定する メタデータなしでコンテンツを送信する 共有 UI のわかりやすさとターゲット レンダリングが向上します
テレメトリが必要な場合は、 TargetApplicationChosenShareCompleted、および ShareCanceled を処理する これらの信号がソース アプリの ShareOperation から来ると仮定する これらは、共有後の分析情報のソース側シグナルです
共有ペイロードにフォーカスを合わせ、選択したアクションに対して有効な状態を維持する 既定で無関係または特大のペイロードを送信する 失敗を減らし、共有の成功率を向上させる