從你的應用程式分享內容 - 整合 Windows 分享

Windows 分享表是系統提供的介面,讓使用者能將你的應用程式內容傳送到其他 Windows 應用程式。 本指南說明如何在打包應用程式(MSIX)、漸進式 Web Apps(PWA)及未封裝的 Win32 應用程式間實作 Share 合約。

本文內容

章節 你會發現什麼
選擇你的分享方式 為 UWP、桌面或 PWA 應用程式選擇合適的 API 組合
為 UWP 應用程式實作分享 DataTransferManager.GetForCurrentViewShowShareUI
為 PWA 實作共享功能 網路分享 API 整合
為桌面應用程式實作 Share(共享) IDataTransferManagerInteropWinUI 3、WPF、WinForms 的每個視窗共享
來源端事件 觀察目標選取、完成與取消
分享的最佳實務 可靠源端行為的建議

選擇你的分享方式

應用程式類型 方法 API 集合
UWP 應用程式 使用 DataTransferManager.GetForCurrentViewShowShareUI Windows.ApplicationModel.DataTransfer
桌面應用程式(WinUI 3、WPF、WinForms) 使用 IDataTransferManagerInterop 來進行每個視窗共用(封裝或未封裝) Windows 執行階段 透過 COM Interop
漸進式 Web 應用程式 (PWA) 使用 Web Share API 和 Windows 整合功能 W3C 網路分享

為 UWP 應用程式實作分享功能

Important

DataTransferManager.GetForCurrentViewShowShareUI 僅支援於 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. 填充資料包

當使用者發起分享(例如點擊分享按鈕)時,請建立包含內容與元資料的 a 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

當你分享網址時,請使用 SetWebLink (或 SetApplicationLink 用於深度連結)而非 SetText。 目標應用程式則能產生豐富連結預覽並正確處理導覽,而非將其視為純文字。

3. 顯示分享介面

透過按一下按鈕或選單命令來觸發分享表單:

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();
}

為漸進式網路應用程式(PWA)實作分享功能

PWA 使用 W3C Web Share 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 Share 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 )實作 Share。

桌面應用程式——無論是打包或未打包——都透過介面 IDataTransferManagerInterop 逐視窗存取 Share Sheet。 這適用於 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 Share Source 範例

來源端事件

在原始應用程式中利用這些事件觀察使用者開啟 Share 後發生了什麼。

API 當它發射時 使用原因
DataTransferManager.DataRequested 使用者會啟動分享操作 建立並附加 DataPackage
DataTransferManager.TargetApplicationChosen 使用者選擇目標應用程式 可選的遙測功能用於目標選擇
DataPackage.ShareCompleted 分享完成 可選成功遙測
DataPackage.ShareCanceled 使用者取消分享 可選的取消遙測

Note

此範例為求簡潔而使用 GetForCurrentView,這適用於 UWP 應用程式。 在桌面應用程式中,如前所述取得 DataTransferManager Through 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.OperationCompletedDataPackage.Destroyed 主要用於剪貼簿和貼上工作流程。 它們通常不需要用於 Share Source 情境。

分享的最佳實務

使用此檢查清單保持來源端行為可預測。

建議使用 避免 為何如此重要
URL 請使用 SetWebLinkSetApplicationLink 網址請使用 SetText 連結在目標應用程式中可正確顯示並導向
設定 Title 與可選的元資料(Description、縮圖) 傳送無元資料的內容 提升分享介面的清晰度與目標顯示效果
如果你需要遙測,請處理 TargetApplicationChosenShareCompletedShareCanceled 假設這些訊號來自來源應用程式中的 ShareOperation 這些是用於分享後洞察的來源端訊號
讓共用承載資料保持精簡,並適用於所選動作 預設傳送無關或過大有效載荷 減少失敗並提升股份成功率