Share via


TransferTargetWatcher Class

Definition

The TransferTargetWatcher class enables applications to discover and monitor available transfer targets (other apps) in real time. It provides events and methods to manage the discovery process and interact with transfer targets dynamically.

public ref class TransferTargetWatcher sealed
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 1245184)]
/// [Windows.Foundation.Metadata.Experimental]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class TransferTargetWatcher final
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 1245184)]
[Windows.Foundation.Metadata.Experimental]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class TransferTargetWatcher
Public NotInheritable Class TransferTargetWatcher
Inheritance
Object Platform::Object IInspectable TransferTargetWatcher
Attributes

Windows requirements

Requirements Description
Device family
Windows 11, version 24H2 (introduced in 10.0.26100.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v19.0)

Examples

For a complete sample demonstrating the use of the TransferTargetWatcher and related APIs, refer to the Transfer Target Watcher Sample.

Initializing and configuring a TransferTargetWatcher

This code sample shows how to initialize and configure a TransferTargetWatcher to discover five app targets and manage them based on a provided data package. It also sets up event handlers to track the addition, removal, and updating of transfer targets, and to handle the completion of the enumeration process.

public class TransferTargetWatcherInitializer
{
    private List<TransferTarget> m_transferTargets;

    public void InitializeTransferTargetWatcher(DataPackage dataPackage)
    {
        // Check if the application supports TransferTargetWatcher
        if (!TransferTargetWatcher.IsSupported(dataPackage.GetView()))
        {
            return;
        }

        // Initialize a global list to store the discovered transfer targets
        m_transferTargets = new List<TransferTarget>();

        // Create a filter to customize the transfer targets discovery
        var transferTargetDiscoveryOptions = new TransferTargetDiscoveryOptions(dataPackageView)
        {
            MaxAppTargets = 5
        };

        // Initialize TransferTargetWatcher using the configured filter
        var transferTargetWatcher = TransferTarget.CreateWatcher(transferTargetDiscoveryOptions);

        // Add a callback for the Added event to handle newly discovered transfer targets
        transferTargetWatcher.Added += (sender, args) =>
        {
            m_transferTargets.Add(args.Target);
        };

        // Add a callback for the Removed event to handle removed transfer targets
        transferTargetWatcher.Removed += (sender, args) =>
        {
            m_transferTargets.Remove(args.Target);
        };

        // Add a callback for the Updated event to handle updated transfer targets
        transferTargetWatcher.Updated += (sender, args) =>
        {
            // Handle the update of targets to allow targets to change their display over time
        };

        // Add a callback for the EnumerationCompleted event to handle the completion of the enumeration process
        transferTargetWatcher.EnumerationCompleted += (sender, args) =>
        {
            // The enumeration process has completed, and the application can now display the discovered transfer targets in the UI.
        };

        // Start the TransferTargetWatcher to begin discovering transfer targets
        transferTargetWatcher.Start();
    }
}

Invoking a transfer target

This code sample demonstrates how to use properties of TransferTarget and invoke a transfer target by using the InvokeAsync method on a TransferTargetWatcher. The OnTargetButtonClick method takes a TransferTarget and a DataPackage as parameters. It ensures that the TransferTargetWatcher is initialized before proceeding. The method handles the progress and completion of the invoke operation, providing feedback on the progress percentage and the final status of the invocation. If the invocation completes successfully, it prints the invoke status; otherwise, it indicates that the operation didn't complete successfully.

<Button
    x:Name="TargetButton"
    Click="OnTargetButtonClick">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid>
            <ImageIcon
                x:Name="TargetPicture"
                Grid.Row="0"
                Width="32"
                Height="32"
                HorizontalAlignment="Center"
                Source="{x:Bind Target.DisplayIcon}" />

            <FontIcon
                x:Name="TargetPicturePlaceholder"
                Grid.Row="0"
                FontSize="32"
                VerticalAlignment="Center"
                HorizontalAlignment="Center"
                Glyph="&#xECAA;" />
        </Grid>

        <TextBlock
            x:Name="TargetTitleText"
            Grid.Row="1"
            Text="{x:Bind Target.Label, Mode=OneWay}" />
    </Grid>
</Button>
// Invoking a transfer target
public async Task OnTargetButtonClick(TransferTarget target)
{
    if (m_transferTargetWatcher == null)
    {
        throw new InvalidOperationException("TransferTargetWatcher is not initialized.");
    }

    IntPtr handle = GetForegroundWindow();
    WindowId windowId = WindowId.FromWindowHandle(handle);

    var invokeOperation = m_transferTargetWatcher.TransferToAsync(target, windowId).AsTask();
    var result = await invokeOperation;

    if (result.Succeeded)
    {
        Console.WriteLine("Invoke successful");
    }
    else
    {
        // Log or handle the HRESULT error from result.ExtendedError
        Console.WriteLine($"Invoke failed with error: {result.ExtendedError}");
    }
}

Remarks

The TransferTargetWatcher is a key component of the Transfer Target Platform API. It supports asynchronous discovery of transfer targets and notifies applications about changes in the available targets through events.

Key features

  • Real-time discovery: Dynamically discovers transfer targets at runtime.
  • Event notifications: Provides events such as Added, Removed, Updated, Stopped, and EnumerationCompleted to keep applications informed about changes.
  • Seamless integration: Simplifies the process of integrating sharing functionalities into applications.

Events

  • Added: Triggered when a new transfer target is discovered.
  • Removed: Triggered when a transfer target is no longer available.
  • Updated: Triggered when a transfer target's properties are updated.
  • Stopped: Triggered when the watcher stops monitoring.
  • EnumerationCompleted: Triggered when the initial enumeration of transfer targets is complete.

Methods

Name Description
IsSupported(DataPackageView)

The IsSupported method determines whether the specified data package is supported by any transfer targets. This method helps applications verify compatibility before initiating a sharing operation.

Start()

The Start method begins the discovery of transfer targets by the TransferTargetWatcher. Once started, the watcher raises events such as Added, Removed, and Updated to notify the application about changes in available transfer targets.

Stop()

The Stop method stops the discovery of transfer targets by the TransferTargetWatcher. Once stopped, the watcher no longer raises events such as Added, Removed, or Updated.

TransferToAsync(TransferTarget, WindowId)

The TransferToAsync method asynchronously invokes a transfer target with the specified data package. This method facilitates the sharing of content to a selected target.

Events

Name Description
Added

The Added event occurs when a new transfer target is discovered by the TransferTargetWatcher. This event provides details about the added target through the TransferTargetChangedEventArgs.

EnumerationCompleted

The EnumerationCompleted event occurs when the TransferTargetWatcher completes the initial enumeration of transfer targets. This event indicates that all currently available targets have been discovered.

Removed

The Removed event occurs when a transfer target is no longer available. This event is raised by the TransferTargetWatcher to notify applications about the removal of a previously discovered target.

Stopped

The Stopped event occurs when the TransferTargetWatcher stops monitoring for transfer targets. This event is raised to notify applications that the watcher has been stopped, either programmatically or due to an error.

Updated

The Updated event occurs when the properties of a transfer target are updated. This event is raised by the TransferTargetWatcher to notify applications about changes to an existing transfer target.

Applies to

See also