Compartilhar via


Quickstart: Publishing and subscribing to messages using tapping (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This topic shows you how to use the PublishMessage and SubscribeForMessageProximity APIs to exchange messages between two devices using tapping.

Roadmap: How does this topic relate to others? See:

Objective: Publish and subscribe to messages by using Proximity tapping.

Prerequisites

Microsoft Visual Studio Express 2012 for Windows 8

Instructions

1. Create a new project and enable Proximity

  1. Open Visual Studio Express 2012 for Windows 8 and select New Project from the File menu. In the Visual C# section, select Blank app (XAML) template. Name the app ProximityMessages and click OK.
  2. Open the Package.appxmanifest file and select the Capabilities tab. Select the Proximity capability to enable Proximity. Close and save the manifest file.

2. Add HTML UI

Open the MainPage.xaml file and add the following XAML to the Grid element.

<StackPanel Margin="20">
    <StackPanel Orientation="Horizontal">
        <TextBox x:Name="MessageTextBox" Width="200" />
        <Button x:Name="PublishMessageButton" Click="PublishMessageButton_Click">Publish Message</Button>
        <Button x:Name="SubscribeForMessageButton" Click="SubscribeForMessageButton_Click">Subscribe For Message</Button>
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Button x:Name="StopPublishingMessageButton" Click="StopPublishingMessageButton_Click">Stop Publishing Message</Button>
        <Button x:Name="StopSubscribingForMessageButton" Click="StopSubscribingForMessageButton_Click">Stop Subscribing For Message</Button>
    </StackPanel>
    <StackPanel>
        <TextBlock>Enter a message and click "Publish Message". On another computer, click
        "Subscribe For Message". Enter proximity to transmit the message.</TextBlock>
    </StackPanel>
    <StackPanel>
        <TextBlock x:Name="MessageBlock"></TextBlock>
    </StackPanel>
</StackPanel>

3. Add initialization code

Add a reference in the initialization code to the default Proximity device that you will use to publish and subscribe to messages.

Open the MainPage.xaml.cs or MainPage.xaml.vb file and replace the default BlankPage constructor and OnNavigatedTo event handler with the following code.

private Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
public BlankPage()
{
    this.InitializeComponent();

    initializeProximitySample();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}

// Write a message to MessageBlock on the UI thread.
private Windows.UI.Core.CoreDispatcher messageDispatcher = Window.Current.CoreWindow.Dispatcher;

async private void WriteMessageText(string message, bool overwrite = false)
{
    await messageDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        () =>
        {
            if (overwrite)
                MessageBlock.Text = message;
            else
                MessageBlock.Text += message;
        });
}

private void initializeProximitySample() 
{
    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

    if (proximityDevice == null)
        WriteMessageText("Failed to initialized proximity device.\n" +
                         "Your device may not have proximity hardware.");
}
Private proximityDevice As Windows.Networking.Proximity.ProximityDevice

Public Sub New()
    Me.InitializeComponent()

    InitializeProximitySample()
End Sub

''' <summary>
''' Invoked when this page is about to be displayed in a Frame.
''' </summary>
''' <param name="e">Event data that describes how this page was reached.  The Parameter
''' property is typically used to configure the page.</param>
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)

End Sub

' Write a message to MessageBlock on the UI thread.
Private Async Sub WriteMessageText(message As String, Optional overwrite As Boolean = False)
    Await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
        Sub()
            If (overwrite) Then
                MessageBlock.Text = message
            Else
                MessageBlock.Text &= message
            End If
        End Sub)
End Sub

Private Sub InitializeProximitySample()
    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()

    If proximityDevice Is Nothing Then
        WriteMessageText("Failed to initialized proximity device." & vbCrLf &
                         "Your device may not have proximity hardware.")
    End If
End Sub

4. Add click event handlers

In this step, you add the code for the click events of the XAML buttons. The code in the event handler for the PublishMessageButton button calls the PublishMessage method, to publish a message to the default Proximity device. The code in the event handler for the SubscribeToMessageButton button calls the SubscribeForMessage method, to receive any messages published by proximate devices. You should always use the Windows. prefix for Proximity message types published using the PublishMessage method. In this sample, only messages of type Windows.SampleMessage are received. You should always use the Windows. prefix for Proximity message types published using the PublishMessage method. To simplify this sample, only one message is published or subscribed to at a time. However, you can publish and subscribe to multiple messages at the same time.

You can also publish Uris using the PublishUriMessage method, or publish binary data using the PublishBinaryMessage method. For a list of the types of messages that can be published using the PublishBinaryMessage method, see PublishBinaryMessage(String, IBuffer).

In the MainPage.xaml.cs or MainPage.xaml.vb file, add the following code after the initializeProximitySample function.

  • long publishedMessageId = -1;
    long subscribedMessageId = -1;
    
    private void PublishMessageButton_Click(object sender, RoutedEventArgs e)
    {
        // Stop publishing the current message.
        if (publishedMessageId != -1)
            proximityDevice.StopPublishingMessage(publishedMessageId);
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBox.Text);
    }
    
    private void SubscribeForMessageButton_Click(object sender, RoutedEventArgs e)
    {
        // Only subscribe for the message one time.
        if (subscribedMessageId == -1)
        {
            subscribedMessageId =
        proximityDevice.SubscribeForMessage("Windows.SampleMessage", messageReceived);
        }
    }
    
    private void messageReceived(Windows.Networking.Proximity.ProximityDevice device,
                                 Windows.Networking.Proximity.ProximityMessage message)
    {
        WriteMessageText("Message received: " + message.DataAsString + "\n");
    }
    
    private void StopPublishingMessageButton_Click(object sender, RoutedEventArgs e)
    {
    proximityDevice.StopPublishingMessage(publishedMessageId);
    }
    
    private void StopSubscribingForMessageButton_Click(object sender, RoutedEventArgs e)
    {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);            
    }
    
    Dim publishedMessageId As Long = -1
    Dim subscribedMessageId As Long = -1
    
    Private Sub PublishMessageButton_Click()
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBox.Text)
    End Sub
    
    Private Sub SubscribeForMessageButton_Click()
        ' Only subscribe for the message one time.
        If subscribedMessageId = -1 Then
            subscribedMessageId =
                proximityDevice.SubscribeForMessage("Windows.SampleMessage", AddressOf messageReceived)
        End If
    End Sub
    
    Private Sub messageReceived(device As Windows.Networking.Proximity.ProximityDevice,
                                message As Windows.Networking.Proximity.ProximityMessage)
    
        WriteMessageText("Message received: " & message.DataAsString & vbCrLf)
    End Sub
    
    Private Sub StopPublishingMessageButton_Click()
        proximityDevice.StopPublishingMessage(publishedMessageId)
    End Sub
    
    Private Sub StopSubscribingForMessageButton_Click()
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
    End Sub
    

5. Run the app

To see the app in action, run it on two computers that have Proximity enabled. Enter a message and click the Publish Message button on one computer, click the Subscribe For Message button on the other computer, and then tap them together.

Important  

This quickstart must be run on two devices. For scenarios that use a tap gesture, each device must have a Proximity device, such as an NFC radio, installed. If you don't have hardware that supports Proximity tapping such as Near-Field Communication (NFC) radio, you can use the Proximity driver sample that is part of the Windows Driver Kit (WDK) samples. You can use the sample driver to simulate a tap gesture over a network connection between two Windows devices. For information on how to download the WDK, see Windows Driver Kit (WDK). After you have installed the WDK and samples, you can find the Proximity driver sample in the src\nfp directory in the location where you installed the WDK samples. See the NetNfpProvider.html file in the src\nfp\net directory for instructions on building and running the simulator. After you start the simulator, it runs in the background while your Proximity app is running in the foreground. Your app must be in the foreground for the tap simulation to work.

 

Summary and next steps

In this tutorial, you created an app to publish and subscribe to messages between devices using a tap.

You can also use a tap gesture to connect to another device. For an example, see Quickstart: Connecting applications using tapping or browsing.

Quickstart: Connecting applications using tapping or browsing

Proximity and tapping overview

Quickstart: Connecting apps using tapping or browsing

Guidelines for Proximity

Testing and troubleshooting Proximity in apps

Windows.Networking.Proximity namespace

Samples

Proximity sample