ProximityDevice ProximityDevice ProximityDevice ProximityDevice Class

Enables you to publish messages to proximate devices or subscribe to messages from proximate devices.

Syntax

Declaration

public sealed class ProximityDevicepublic sealed class ProximityDevicePublic NotInheritable Class ProximityDevice

Remarks

The ProximityDevice class enables applications to communicate with running applications on devices, typically within a range of 3 centimeters to 4 centimeters.

You can create an instance of ProximityDevice by using the GetDefault() or FromId(System.String) static method.

The ProximityDevice class uses publish/subscribe semantics and is useful for advertising and receiving small blocks of data. For larger amounts of data, or for persistent communications, use the PeerFinder and @Windows.Networking.Sockets.StreamSocket.#ctor classes. For Windows Store app, publications and subscriptions are active only if the calling app is in the foreground.

Important

The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

Examples

Windows.Networking.Proximity.ProximityDevice proximityDevice;

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

    if (proximityDevice != null) {
        proximityDevice.DeviceArrived += ProximityDeviceArrived;
        proximityDevice.DeviceDeparted += ProximityDeviceDeparted;

        WriteMessageText("Proximity device initialized.\n");
    }
    else
    {
        WriteMessageText("Failed to initialized proximity device.\n");
    }
}

private void ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)
{
    WriteMessageText("Proximate device arrived. id = " + device.DeviceId + "\n");
}

private void ProximityDeviceDeparted(Windows.Networking.Proximity.ProximityDevice device)
{
    WriteMessageText("Proximate device departed. id = " + device.DeviceId + "\n");
}

// 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;
        });
}
function id(elementId) {
    return document.getElementById(elementId);
}

var proximityDevice;

function initializeProximityDevice() {
    proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();

    if (proximityDevice) {
        proximityDevice.addEventListener("devicearrived", proximityDeviceArrived);
        proximityDevice.addEventListener("devicedeparted", proximityDeviceDeparted);

        id("messageDiv").innerHTML += "Proximity device initialized.<br />";
    }
    else {
        id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
    }
}

function proximityDeviceArrived(device) {
    id("messageDiv").innerHTML += "Proximate device arrived. id = " + device.deviceId + "<br />";
}

function proximityDeviceDeparted(device) {
    id("messageDiv").innerHTML += "Proximate device departed. id = " + device.deviceId + "<br />";
}
Dim proximityDevice As Windows.Networking.Proximity.ProximityDevice

Private Sub InitializeProximityDevice()

    proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()

    If proximityDevice IsNot Nothing Then
        AddHandler proximityDevice.DeviceArrived, AddressOf ProximityDeviceArrived
        AddHandler proximityDevice.DeviceDeparted, AddressOf ProximityDeviceDeparted

        WriteMessageText("Proximity device initialized." & vbTab)
    Else
        WriteMessageText("Failed to initialized proximity device." & vbTab)
    End If
End Sub

Private Sub ProximityDeviceArrived(device As Windows.Networking.Proximity.ProximityDevice)
    WriteMessageText("Proximate device arrived. id = " & device.DeviceId & vbTab)
End Sub

Private Sub ProximityDeviceDeparted(device As Windows.Networking.Proximity.ProximityDevice)
    WriteMessageText("Proximate device departed. id = " & device.DeviceId & vbTab)
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

Properties summary

Gets the transfer rate of a proximity device.

Gets the Id for a proximity device.

Gets the maximum size of a published message that this proximity device supports.

Methods summary

Creates an instance of a ProximityDevice class and activates the specified proximity device interface.

Creates an instance of a ProximityDevice class and activates the default proximity provider.

Returns the class selection string that you can use to enumerate proximity devices.

Publishes a message that contains binary data to subscribers of the specified message type.

Publishes a message that contains binary data to subscribers of the specified message type. The specified handler is called when the message has been transmitted.

Publishes a message to subscribers of the specified message type.

Publishes a message to subscribers of the specified message type. The specified handler is called when the message has been transmitted.

Publishes a Uniform Resource Identifier (URI) to a proximate device.

Publishes a Uniform Resource Identifier (URI) to a proximate device. The specified handler is called when the message has been transmitted.

Stops publishing a message.

Cancels a message subscription.

Creates a subscription for a specified message type.

Events summary

Occurs when a device enters the proximate range.

Occurs when a device leaves the proximate range.

Properties

  • BitsPerSecond
    BitsPerSecond
    BitsPerSecond
    BitsPerSecond

    Gets the transfer rate of a proximity device.

    public ulong BitsPerSecond { get; }public ulong BitsPerSecond { get; }Public ReadOnly Property BitsPerSecond As ulong

    Property Value

    • ulong
      ulong
      ulong
      ulong

      The transfer rate of a proximity device.

  • DeviceId
    DeviceId
    DeviceId
    DeviceId

    Gets the Id for a proximity device.

    public string DeviceId { get; }public string DeviceId { get; }Public ReadOnly Property DeviceId As string

    Property Value

    • string
      string
      string
      string

      The Id for a proximity device.

    Remarks

    If your computer supports Proximity and has an NFC device installed, which is commonly the case, then the GetDefault() method will return the device that supports NFC. You can also determine whether your computer has an NFC device installed by querying the device information for the property "{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2". In the Properties object returned from the query the value for the "{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2" key contains and array of strings that describe the capabilities of the proximity device. If one of the strings is "StandardNfc", then the device supports NFC protocols such as NDEF. For more information on how to query for the properties of a device, see How to retrieve additional properties for a device or PnP object.

    Examples

    private async void QueryDeviceProperties()
    {
        // Include the proximity properties key
        var propertiesToRetrieve = new List<String> {"{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"};
    
        var defaultProximityDevice =
            Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
        if (defaultProximityDevice != null)
        {
            var devInfo = await Windows.Devices.Enumeration.DeviceInformation.CreateFromIdAsync(
                defaultProximityDevice.DeviceId, propertiesToRetrieve);
    
            if (devInfo.Properties.ContainsKey("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"))
            {
                var proximityCapabilities =
                    devInfo.Properties["{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"] as string[];
                if (proximityCapabilities.Contains("StandardNfc"))
                {
                    // This proximity device supports NFC
                }
            }
        }
    }
    
    function queryDeviceProperties() {
        // Include the proximity properties key
        var propertiesToRetrieve = new Array();
        propertiesToRetrieve.push("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2");
    
        var defaultProximityDevice =
            Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (defaultProximityDevice) {
            Windows.Devices.Enumeration.DeviceInformation.createFromIdAsync(
                defaultProximityDevice.deviceId, propertiesToRetrieve).done(
                function (devInfo) {
                    if (devInfo.properties.hasKey("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2")) {
                        var proximityCapabilities = new Array();
                        proximityCapabilities = devInfo.properties["{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"];
                        for (var i = 0; i < proximityCapabilities.length; i++) {
                            if (proximityCapabilities[i] == "StandardNfc") {
                                // This proximity device supports NFC
                            }
                        };
                    }
                });
        }
    }
    
    Private Async Sub QueryDeviceProperties()
        ' Include the proximity properties key
        Dim propertiesToRetrieve = New List(Of String) From {"{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"}
    
        Dim defaultProximityDevice =
            Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If defaultProximityDevice IsNot Nothing Then
            Dim devInfo = Await Windows.Devices.Enumeration.DeviceInformation.CreateFromIdAsync(
                defaultProximityDevice.DeviceId, propertiesToRetrieve)
    
            If devInfo.Properties.ContainsKey("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2") Then
                Dim proximityCapabilities =
                    TryCast(devInfo.Properties("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"), String())
    
                If proximityCapabilities.Contains("StandardNfc") Then
                    ' This proximity device supports NFC
                End If
            End If
        End If
    End Sub
    
  • MaxMessageBytes
    MaxMessageBytes
    MaxMessageBytes
    MaxMessageBytes

    Gets the maximum size of a published message that this proximity device supports.

    public uint MaxMessageBytes { get; }public uint MaxMessageBytes { get; }Public ReadOnly Property MaxMessageBytes As uint

    Property Value

    • uint
      uint
      uint
      uint

      The maximum size of a published message that this proximity device supports.

Methods

  • FromId(System.String)
    FromId(System.String)
    FromId(System.String)
    FromId(System.String)

    Creates an instance of a ProximityDevice class and activates the specified proximity device interface.

    public static ProximityDevice FromId(System.String)public static ProximityDevice FromId(System.String)Public Static Function FromId(System.String) As ProximityDevice

    Parameters

    • deviceId
      System.String
      System.String
      System.String
      System.String

      The Id of a proximity device.

    Returns

    Remarks

    You can enumerate proximity devices by passing the class selection string returned by the GetDeviceSelector() method to the FindAllAsync(System.String) or CreateWatcher() method. You can then use the resulting Id value(s) to create an instance of a ProximityDevice using the FromId(System.String) method.

    Examples

    Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
    private async void InitializeProximity()
    {
        string selectorString = Windows.Networking.Proximity.ProximityDevice.GetDeviceSelector();
    
        var deviceInfoCollection =
            await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selectorString, null);
    
            if (deviceInfoCollection.Count == 0)
            {
                StatusTextBlock.Text = "No proximity devices found.";
            } 
            else 
            {
                StatusTextBlock.Text = "Proximity Device id = " + deviceInfoCollection[0].Id;
                proximityDevice =
                    Windows.Networking.Proximity.ProximityDevice.FromId(deviceInfoCollection[0].Id);
            }
    }
    
    var proximityDevice;
    
    function initializeProximity() {
        var selectorString = Windows.Networking.Proximity.ProximityDevice.getDeviceSelector();
                
        var propertiesToRetrieve = new Array();
        propertiesToRetrieve.push("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2");
    
        Windows.Devices.Enumeration.DeviceInformation.findAllAsync(selectorString, propertiesToRetrieve).done(
            function (deviceInfoCollection) {
                if (deviceInfoCollection.size == 0) {
                    statusDiv.innerHTML = "No proximity devices found.";
                } else {
                    statusDiv.innerHTML = "Proximity Device id = " + deviceInfoCollection[0].id;
                    proximityDevice =
                        Windows.Networking.Proximity.ProximityDevice.fromId(deviceInfoCollection[0].id);
                }
        });
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Async Sub InitializeProximity()
        Dim selectorString = Windows.Networking.Proximity.ProximityDevice.GetDeviceSelector()
    
        Dim deviceInfoCollection =
            Await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selectorString, {"{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"})
    
        If deviceInfoCollection.Count = 0 Then
            StatusTextBlock.Text = "No proximity devices found."
        Else
            StatusTextBlock.Text = "Proximity Device id = " & deviceInfoCollection(0).Id
            proximityDevice =
                Windows.Networking.Proximity.ProximityDevice.FromId(deviceInfoCollection(0).Id)
        End If
    End Sub
    
  • GetDefault()
    GetDefault()
    GetDefault()
    GetDefault()

    Creates an instance of a ProximityDevice class and activates the default proximity provider.

    public static ProximityDevice GetDefault()public static ProximityDevice GetDefault()Public Static Function GetDefault() As ProximityDevice

    Returns

    Remarks

    Examples

    Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
    private void InitializeProximityDevice()
    {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
        if (proximityDevice != null) {
            proximityDevice.DeviceArrived += ProximityDeviceArrived;
            proximityDevice.DeviceDeparted += ProximityDeviceDeparted;
    
            WriteMessageText("Proximity device initialized.\n");
        }
        else
        {
            WriteMessageText("Failed to initialized proximity device.\n");
        }
    }
    
    private void ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device arrived. id = " + device.DeviceId + "\n");
    }
    
    private void ProximityDeviceDeparted(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device departed. id = " + device.DeviceId + "\n");
    }
    
    // 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;
            });
    }
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    var proximityDevice;
    
    function initializeProximityDevice() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            proximityDevice.addEventListener("devicearrived", proximityDeviceArrived);
            proximityDevice.addEventListener("devicedeparted", proximityDeviceDeparted);
    
            id("messageDiv").innerHTML += "Proximity device initialized.<br />";
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
        }
    }
    
    function proximityDeviceArrived(device) {
        id("messageDiv").innerHTML += "Proximate device arrived. id = " + device.deviceId + "<br />";
    }
    
    function proximityDeviceDeparted(device) {
        id("messageDiv").innerHTML += "Proximate device departed. id = " + device.deviceId + "<br />";
    }
    
    Dim proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub InitializeProximityDevice()
    
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler proximityDevice.DeviceArrived, AddressOf ProximityDeviceArrived
            AddHandler proximityDevice.DeviceDeparted, AddressOf ProximityDeviceDeparted
    
            WriteMessageText("Proximity device initialized." & vbTab)
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub ProximityDeviceArrived(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device arrived. id = " & device.DeviceId & vbTab)
    End Sub
    
    Private Sub ProximityDeviceDeparted(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device departed. id = " & device.DeviceId & vbTab)
    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
    
  • GetDeviceSelector()
    GetDeviceSelector()
    GetDeviceSelector()
    GetDeviceSelector()

    Returns the class selection string that you can use to enumerate proximity devices.

    public static string GetDeviceSelector()public static string GetDeviceSelector()Public Static Function GetDeviceSelector() As string

    Returns

    • string
      string
      string
      string

      The class selection string for proximity devices.

    Remarks

    You can enumerate proximity devices by passing the class selection string returned by the GetDeviceSelector() method to the FindAllAsync(System.String) or CreateWatcher() method.

    If your computer supports Proximity and has an NFC device installed, which is commonly the case, then the GetDefault() method will return the device that supports NFC. You can also determine whether your computer has an NFC device installed by querying the device information for the property "{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2". In the Properties object returned from the query the value for the "{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2" key contains and array of strings that describe the capabilities of the proximity device. If one of the strings is "StandardNfc", then the device supports NFC protocols such as NDEF. For more information on how to query for the properties of a device, see How to retrieve additional properties for a device or PnP object.

    Examples

    Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
    private async void InitializeProximity()
    {
        string selectorString = Windows.Networking.Proximity.ProximityDevice.GetDeviceSelector();
    
        var deviceInfoCollection =
            await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selectorString, null);
    
            if (deviceInfoCollection.Count == 0)
            {
                StatusTextBlock.Text = "No proximity devices found.";
            } 
            else 
            {
                StatusTextBlock.Text = "Proximity Device id = " + deviceInfoCollection[0].Id;
                proximityDevice =
                    Windows.Networking.Proximity.ProximityDevice.FromId(deviceInfoCollection[0].Id);
            }
    }
    
    var proximityDevice;
    
    function initializeProximity() {
        var selectorString = Windows.Networking.Proximity.ProximityDevice.getDeviceSelector();
                
        var propertiesToRetrieve = new Array();
        propertiesToRetrieve.push("{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2");
    
        Windows.Devices.Enumeration.DeviceInformation.findAllAsync(selectorString, propertiesToRetrieve).done(
            function (deviceInfoCollection) {
                if (deviceInfoCollection.size == 0) {
                    statusDiv.innerHTML = "No proximity devices found.";
                } else {
                    statusDiv.innerHTML = "Proximity Device id = " + deviceInfoCollection[0].id;
                    proximityDevice =
                        Windows.Networking.Proximity.ProximityDevice.fromId(deviceInfoCollection[0].id);
                }
        });
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Async Sub InitializeProximity()
        Dim selectorString = Windows.Networking.Proximity.ProximityDevice.GetDeviceSelector()
    
        Dim deviceInfoCollection =
            Await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selectorString, {"{FB3842CD-9E2A-4F83-8FCC-4B0761139AE9} 2"})
    
        If deviceInfoCollection.Count = 0 Then
            StatusTextBlock.Text = "No proximity devices found."
        Else
            StatusTextBlock.Text = "Proximity Device id = " & deviceInfoCollection(0).Id
            proximityDevice =
                Windows.Networking.Proximity.ProximityDevice.FromId(deviceInfoCollection(0).Id)
        End If
    End Sub
    
  • PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)

    Publishes a message that contains binary data to subscribers of the specified message type.

    public long PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)public long PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer)Public Function PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) As long

    Parameters

    • messageType
      System.String
      System.String
      System.String
      System.String

      The type of message to deliver to subscribers.

    • message

      The binary message data to deliver to subscribers.

    Returns

    • long
      long
      long
      long

      A unique publication ID for the published message.

    Remarks

    You can publish multiple messages of the same message type and each publication will have a unique ID associated with it.

    You can stop publishing a message by passing the publication ID returned by the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method to the StopPublishingMessage(System.Int64) method.

    Messages continue to be published until the StopPublishingMessage(System.Int64) method is called or the ProximityDevice is released.

    You can subscribe to published messages using the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method.

    You can use the PublishMessage(System.String,System.String) method to publish a text message to a proximate computer. You can use the PublishUriMessage(Windows.Foundation.Uri) method to publish a Uniform Resource Identifier (URI) to a proximate computer.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Message Types

    You use the messageType parameter to supply an identifier that uniquely identifies the published message, and also defines the meaning of the message and the intended subscriber audience.

    Message type values are case-sensitive strings that consist of two parts: the protocol and the subtype. The protocol is first, followed by a dot (.) and then the subtype. The subtype is a string of alphanumeric characters and any of the valid URI characters as defined by RFC 3986: - . _~ : / ? # [ ] @ ! $ & ‘ ( ) * + , ; = %. The subtype cannot exceed a length of 250 characters. The following table shows the supported values for the protocol part of the message type.

    WindowsThe message contains binary data.WindowsUriThe message data contains a UTF-16LE encoded string that is a Uniform Resource Identifier (URI). Windows will always handle "WindowsUri" messages by prompting the user to view a received URI that in the Windows default app that handles a specific URI protocol, for example, http:// URIs open in the default web browser. Windows will open a URI in the default app even if another app is also subscribed to "WindowsUri". Instead of calling the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method with this protocol, use the PublishUriMessage(Windows.Foundation.Uri) method. If you publish a Uri to a computer that is not running Windows, the Uri is automatically formatted based on the proximity technology that your computer supports. For example, if your computer uses NFC hardware for proximity, then the Uri is formatted as an NDEF URI record. If you are subscribing for a "WindowsUri" message and your Windows computer receives a message formatted for the proximity technology that your computer supports, Windows reads the formatted message and returns only the Uri as the message content.WindowsMimeThe message data is of a specific mime type. For example, if the message data is a jpeg image, the message type is "WindowsMime.image/jpeg". Windows will always handle "WindowsMime" messages by prompting the user to view the mime content that was received, even if an app is also subscribed for the mime content. If you publish a "WindowsMime" message to a computer that is not running Windows, the message content is automatically formatted based on the proximity technology that your computer supports. For example, if your computer uses NFC hardware for proximity, then the message content is formatted as an NDEF Mime record. If you are publishing a "WindowsMime" message, you must always include the mime type. If you are subscribing to a "WindowsMime" message, you can use "WindowsMime" without specifying the mime type to subscribe for all mime types. If you subscribe to a specific mime type and your Windows computer receives a message formatted for the proximity technology that your computer supports, Windows reads the formatted message and returns only the mime content as the message content. If you subscribe for all mime types, the first 256 bytes received is the ASCII mime type string, and the remaining bytes are the mime content.Windows:WriteTagThis is the same as the Windows protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. An example of this protocol is "Windows:WriteTag.SampleSubtype".WindowsUri:WriteTagThis is the same as the WindowsUri protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications.WindowsMime:WriteTagThis is the same as the WindowsMime protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. An example of this protocol is "WindowsMime:WriteTag.image/jpeg".LaunchApp:WriteTagWrite a tag that can be used to launch a specific app with optional launch parameters. If you publish a LaunchApp:WriteTag message to a tag the result when that tag is tapped to a computer is the same as calling the Start(System.String) method and passing your launch parameters. The message must be a UTF-16LE encoded string where the values are delimited by tab characters or null values in the following form: text <launch arguments>[tab]<app platform 1>[tab]<app name 1>...[tab]<app platform N>[tab]<app name N> The launch arguments are optional. The message can omit them: text <app platform 1>[tab]<app name 1>...[tab]<app platform N>[tab]<app name N> You must specify at least one app platform and app name. The app platform for a Windows 8 computer is Windows. The format of the proximity app Id is <package family name>!<app Id>. You can get the package family name from the FamilyName property. You must copy the app Id value from the Id attribute of the Application element in the package manifest for your app. An example of this message is "user=default\tWindows\tExample.Proximity.JS_8wekyb3d8bbwe!Proximity.App". You can also support other app platforms. For more information, see @Windows.Networking.Proximity.PeerFinder.AlternateIdentities.</termdef><termdef><name>WriteableTag</name>When subscribing for this message protocol, if a writeable tag is brought in to proximity, a proximity message is received that contains an int32 (little endian) indicating the maximum writeable size of the tag. This protocol is only valid for subscriptions.Pairing:BluetoothWindows subscribes to this message type to complete a Bluetooth pairing using proximity. This protocol is not intended to be uses in apps.NDEFThe message contents are properly formatted NDEF records. The underlying type of the content for a publication using NDEF as the message type is contained in the NDEF records. A subscription for the NDEF type subscribes to all NDEF formatted messages.NDEF:extThe message data is application defined NDEF records (TNF field value of 0x04). This protocol will launch a properly configured application to handle these events if there is no running application already subscribing to these events. To designate an app to handle a particular protocol using NDEF:ext, you must add a Protocol tag to the app manifest to specify the URI that will launch the app. The appropriate manifest syntax is demonstrated in the following example. xml <Extensions> <Extension Category="windows.protocol"> <Protocol Name="contoso.com+testapp" /> </Extension> </Extensions> > [!NOTE] > The URI format used in the app manifest is slightly different from the URI format used on the NFC tag, in that the manifest URI uses a '+ ' character rather than a ': ' character. The URI on the NFC tag that activates the app with the manifest sample above is contoso.com:testapp.NDEF:MIMEThe message data is a properly formatted NDEF mime message (TNF field value of 0x02). For example, "NDEF:MIME.image/jpeg". This protocol only applies to subscriptions, when publishing NDEF content, use NDEF.NDEF:URIThe message data is a properly formatted NDEF message of a type defined by a URI namespace (TNF field value of 0x03).This protocol only applies to subscriptions, when publishing NDEF content, use NDEF. This means that the data format is identified by the specified URI. An example of this protocol is "NDEF:URI.http://contoso.com/sometype".NDEF:wktThe message data is a properly formatted NDEF message of a type defined by the NFC forum (TNF field value of 0x01).An example of this type is "NDEF:wkt.U" for the well known type of URI. This protocol only applies to subscriptions, when publishing NDEF content, use NDEF.NDEF:WriteTagThe message data should be written to an NFC forum standard static tag. The message data must be in a proper NDEF format. This protocol is only valid for publications.NDEF:UnknownThe message data is an untyped NDEF message (TNF field value of 0x05).This protocol only applies to subscriptions, when publishing NDEF content, use NDEF.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
       private void PublishLaunchApp()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice != null)
           {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               string launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;
    
               string launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
               dataWriter.WriteString(launchAppMessage);
               var launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                   "LaunchApp:WriteTag", dataWriter.DetachBuffer());
           }
       }
    
           var proximityDevice;
    
       function publishLaunchApp() {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice) {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               var launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               var praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               var appName = Windows.ApplicationModel.Package.current.id.familyName + "!" + praid;
    
               var launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
               dataWriter.writeString(launchAppMessage);
               var launchAppPubId =
                    proximityDevice.publishBinaryMessage(
                        "LaunchApp:WriteTag", 
                        dataWriter.detachBuffer());
           }
       }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub PublishLaunchApp()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
    If proximityDevice IsNot Nothing Then
            ' The format of the app launch string is: "<args>" & vbTab & "Windows" vbTab & "<AppName>".
            ' The string is tab or null delimited.
    
            ' The <args> string must have at least one character.
            Dim launchArgs = "user=default"
    
            ' The format of the AppName is: PackageFamilyName!PRAID.
            Dim praid = "MyAppId" ' The Application Id value from your package.appxmanifest.
    
            Dim appName = Windows.ApplicationModel.Package.Current.Id.FamilyName & "!" & praid
    
            Dim launchAppMessage = launchArgs & vbTab & "Windows" & vbTab & appName
    
            Dim dataWriter = New Windows.Storage.Streams.DataWriter()
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE
            dataWriter.WriteString(launchAppMessage)
            Dim launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                  "LaunchApp:WriteTag", dataWriter.DetachBuffer())
        End If
    End Sub
    
       Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
       private void PublishLaunchApp()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice != null)
           {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               string launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;
    
               string launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
               dataWriter.WriteString(launchAppMessage);
               var launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                   "LaunchApp:WriteTag", dataWriter.DetachBuffer());
           }
       }
    
           var proximityDevice;
    
       function publishLaunchApp() {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice) {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               var launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               var praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               var appName = Windows.ApplicationModel.Package.current.id.familyName + "!" + praid;
    
               var launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
               dataWriter.writeString(launchAppMessage);
               var launchAppPubId =
                    proximityDevice.publishBinaryMessage(
                        "LaunchApp:WriteTag", 
                        dataWriter.detachBuffer());
           }
       }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub PublishLaunchApp()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
    If proximityDevice IsNot Nothing Then
            ' The format of the app launch string is: "<args>" & vbTab & "Windows" vbTab & "<AppName>".
            ' The string is tab or null delimited.
    
            ' The <args> string must have at least one character.
            Dim launchArgs = "user=default"
    
            ' The format of the AppName is: PackageFamilyName!PRAID.
            Dim praid = "MyAppId" ' The Application Id value from your package.appxmanifest.
    
            Dim appName = Windows.ApplicationModel.Package.Current.Id.FamilyName & "!" & praid
    
            Dim launchAppMessage = launchArgs & vbTab & "Windows" & vbTab & appName
    
            Dim dataWriter = New Windows.Storage.Streams.DataWriter()
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE
            dataWriter.WriteString(launchAppMessage)
            Dim launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                  "LaunchApp:WriteTag", dataWriter.DetachBuffer())
        End If
    End Sub
    
  • PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)

    Publishes a message that contains binary data to subscribers of the specified message type. The specified handler is called when the message has been transmitted.

    public long PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)public long PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler)Public Function PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler) As long

    Parameters

    Returns

    • long
      long
      long
      long

      A unique publication ID for the published message.

    Remarks

    You can publish multiple messages of the same message type and each publication will have a unique ID associated with it.

    You can stop publishing a message by passing the publication ID returned by the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method to the StopPublishingMessage(System.Int64) method.

    Messages continue to be published until the StopPublishingMessage(System.Int64) method is called or the ProximityDevice is released.

    You can subscribe to published messages using the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method.

    You can use the PublishMessage(System.String,System.String) method to publish a text message to a proximate computer. You can use the PublishUriMessage(Windows.Foundation.Uri) method to publish a Uniform Resource Identifier (URI) to a proximate computer.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Message Types

    For details on the types of messages that you can publish with the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer,Windows.Networking.Proximity.MessageTransmittedHandler) method, see the remarks in the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) reference topic.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
       private void PublishLaunchApp()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice != null)
           {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               string launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;
    
               string launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
               dataWriter.WriteString(launchAppMessage);
               var launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                   "LaunchApp:WriteTag", dataWriter.DetachBuffer(), 
                   proximityWriteTagLaunchAppMessageTransmitCallback);
           }
       }
    
       private void proximityWriteTagLaunchAppMessageTransmitCallback(
           Windows.Networking.Proximity.ProximityDevice sender,
           long messageId)
       {
           // The LaunchApp message has been successfully written to a tag.
       }
    
       var proximityDevice;
    
       function publishLaunchApp() {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
    if (proximityDevice) {
               // The format of the app launch string is: "<args>\tWindows\t<AppName>".
               // The string is tab or null delimited.
    
               // The <args> string must have at least one character.
               var launchArgs = "user=default";
    
               // The format of the AppName is: PackageFamilyName!PRAID.
               var praid = "MyAppId"; // The Application Id value from your package.appxmanifest.
    
               var appName = Windows.ApplicationModel.Package.current.id.familyName + "!" + praid;
    
               var launchAppMessage = launchArgs + "\tWindows\t" + appName;
    
               var dataWriter = new Windows.Storage.Streams.DataWriter();
               dataWriter.unicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
               dataWriter.writeString(launchAppMessage);
               var launchAppPubId =
                    proximityDevice.publishBinaryMessage(
                        "LaunchApp:WriteTag", 
                        dataWriter.detachBuffer(), 
                        proximityWriteTagLaunchAppMessageTransmitCallback);
            }
       }
    
       function proximityWriteTagLaunchAppMessageTransmitCallback() {
           // The LaunchApp message has been successfully written to a tag.
       }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub PublishLaunchApp()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
    If proximityDevice IsNot Nothing Then
            ' The format of the app launch string is: "<args>" & vbTab & "Windows" vbTab & "<AppName>".
            ' The string is tab or null delimited.
    
            ' The <args> string must have at least one character.
            Dim launchArgs = "user=default"
    
            ' The format of the AppName is: PackageFamilyName!PRAID.
            Dim praid = "MyAppId" ' The Application Id value from your package.appxmanifest.
    
            Dim appName = Windows.ApplicationModel.Package.Current.Id.FamilyName & "!" & praid
    
            Dim launchAppMessage = launchArgs & vbTab & "Windows" & vbTab & appName
    
            Dim dataWriter = New Windows.Storage.Streams.DataWriter()
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE
            dataWriter.WriteString(launchAppMessage)
            Dim launchAppPubId =
               proximityDevice.PublishBinaryMessage(
                  "LaunchApp:WriteTag", dataWriter.DetachBuffer(),
                  AddressOf proximityWriteTagLaunchAppMessageTransmitCallback)
        End If
    End Sub
    
    Private Sub proximityWriteTagLaunchAppMessageTransmitCallback(
        sender As Windows.Networking.Proximity.ProximityDevice,
        messageId As Long)
        ' The LaunchApp message has been successfully written to a tag.
    End Sub
    
  • PublishMessage(System.String,System.String)
    PublishMessage(System.String,System.String)
    PublishMessage(System.String,System.String)
    PublishMessage(System.String,System.String)

    Publishes a message to subscribers of the specified message type.

    public long PublishMessage(System.String,System.String)public long PublishMessage(System.String,System.String)Public Function PublishMessage(System.String,System.String) As long

    Parameters

    • messageType
      System.String
      System.String
      System.String
      System.String

      The type of message to deliver to subscribers.

    • message
      System.String
      System.String
      System.String
      System.String

      The message to deliver to subscribers.

    Returns

    Remarks

    You can subscribe to published messages by using the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method.

    Messages continue to be published until the StopPublishingMessage(System.Int64) method is called or the ProximityDevice object is released.

    Messages are delivered to all applications that have subscribed to the message type (as indicated by the messageType parameter). Message type values are case-sensitive strings that consist of two parts: the protocol and the subtype. The protocol is first, followed by a dot (.) and then the subtype. For the PublishMessage(System.String,System.String) method, the protocol must always be "Windows.". The subtype is a string of alphanumeric characters and the following additional characters: . ( ) + , - : = @ ; $ _ ! * ’. The subtype cannot exceed a length of 250 characters.

    To publish messages by using another message type, like “WindowsMime.” or “NDEF:WriteTag”, you must use the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method.

    You can use the PublishUriMessage(Windows.Foundation.Uri) method to publish a Uniform Resource Identifier (URI) to a proximate computer.

    Messages are converted to UTF-8 characters before they're transmitted.

    For Windows Store app, publications and subscriptions are active only if the calling app is in the foreground.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
       long publishedMessageId = -1;
       long subscribedMessageId = -1;
    
       private void initializeProximityDevice()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
           if (proximityDevice != null)
           {
               PublishMessageButton.Click += PublishMessage;
               SubscribeForMessageButton.Click += SubscribeForMessage;
         StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
         StopPublishingMessageButton.Click += StopPublishingMessage;
           }
           else
           {
               WriteMessageText("Failed to initialized proximity device.\n");
           }
       }
    
       private void PublishMessage(object sender, RoutedEventArgs e)
       {
           // Stop publishing the current message.
           if (publishedMessageId != -1)
           {
               proximityDevice.StopPublishingMessage(publishedMessageId);
           }
    
           publishedMessageId = 
         proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text);
       }
    
       private void SubscribeForMessage(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)
       {
           MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
       }
    
    private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);
           subscribedMessageId = -1;
    }
    
    private void StopPublishingMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopPublishingMessage(publishedMessageId);
           publishedMessageId = -1;
    }
    
       // 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;
               });
       }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value);
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    Private publishedMessageId As Long = -1
    Private subscribedMessageId As Long = -1
    
    Private Sub initializeProximityDevice()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler PublishMessageButton.Click, AddressOf PublishMessage
            AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
            AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
            AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text)
    End Sub
    
    Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
        ' 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)
    
        MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
    End Sub
    
    Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
        subscribedMessageId = -1
    End Sub
    
    Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopPublishingMessage(publishedMessageId)
        publishedMessageId = -1
    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
    
       Windows.Networking.Proximity.ProximityDevice proximityDevice;
       long publishedMessageId = -1;
       long subscribedMessageId = -1;
    
       private void initializeProximityDevice()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
           if (proximityDevice != null)
           {
               PublishMessageButton.Click += PublishMessage;
               SubscribeForMessageButton.Click += SubscribeForMessage;
         StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
         StopPublishingMessageButton.Click += StopPublishingMessage;
           }
           else
           {
               WriteMessageText("Failed to initialized proximity device.\n");
           }
       }
    
       private void PublishMessage(object sender, RoutedEventArgs e)
       {
           // Stop publishing the current message.
           if (publishedMessageId != -1)
           {
               proximityDevice.StopPublishingMessage(publishedMessageId);
           }
    
           publishedMessageId = 
         proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text);
       }
    
       private void SubscribeForMessage(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)
       {
           MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
       }
    
    private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);
           subscribedMessageId = -1;
    }
    
    private void StopPublishingMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopPublishingMessage(publishedMessageId);
           publishedMessageId = -1;
    }
    
       // 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;
               });
       }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value);
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    Private publishedMessageId As Long = -1
    Private subscribedMessageId As Long = -1
    
    Private Sub initializeProximityDevice()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler PublishMessageButton.Click, AddressOf PublishMessage
            AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
            AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
            AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text)
    End Sub
    
    Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
        ' 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)
    
        MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
    End Sub
    
    Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
        subscribedMessageId = -1
    End Sub
    
    Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopPublishingMessage(publishedMessageId)
        publishedMessageId = -1
    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
    
  • PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)

    Publishes a message to subscribers of the specified message type. The specified handler is called when the message has been transmitted.

    public long PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)public long PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler)Public Function PublishMessage(System.String,System.String,Windows.Networking.Proximity.MessageTransmittedHandler) As long

    Parameters

    Returns

    • long
      long
      long
      long

      A unique publication ID for the published message.

    Remarks

    You can subscribe to published messages by using the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method.

    Messages continue to be published until the StopPublishingMessage(System.Int64) method is called or the ProximityDevice object is released.

    Messages are delivered to all applications that have subscribed to the message type (as indicated by the messageType parameter). Message type values are case-sensitive strings that consist of two parts: the protocol and the subtype. The protocol is first, followed by a dot (.) and then the subtype. For the PublishMessage(System.String,System.String) method, the protocol must always be "Windows.". The subtype is a string of alphanumeric characters and the following additional characters: . ( ) + , - : = @ ; $ _ ! * ’. The subtype cannot exceed a length of 250 characters.

    To publish messages by using another message type, like “WindowsMime.” or “NDEF:WriteTag”, you must use the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method.

    You can use the PublishUriMessage(Windows.Foundation.Uri) method to publish a Uniform Resource Identifier (URI) to a proximate computer.

    Messages are converted to UTF-8 characters before they're transmitted.

    For Windows Store app, publications and subscriptions are active only if the calling app is in the foreground.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Examples

           Windows.Networking.Proximity.ProximityDevice proximityDevice;
           long publishedMessageId = -1;
           long subscribedMessageId = -1;
    
           private void initializeProximityDevice()
           {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
               if (proximityDevice != null)
               {
                   PublishMessageButton.Click += PublishMessage;
                   SubscribeForMessageButton.Click += SubscribeForMessage;
    	        StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
    	        StopPublishingMessageButton.Click += StopPublishingMessage;
               }
               else
               {
                   WriteMessageText("Failed to initialized proximity device.\n");
               }
           }
    
           private void PublishMessage(object sender, RoutedEventArgs e)
           {
               // Stop publishing the current message.
               if (publishedMessageId != -1)
               {
                   proximityDevice.StopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	        proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text,
                                                          MessagePublished);
           }
    
    private void MessagePublished(
        Windows.Networking.Proximity.ProximityDevice sender,
               long messageId)
           {
        // The message has been successfully published.
           }
    
           private void SubscribeForMessage(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)
           {
               MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
           }
    
        private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
           {
            proximityDevice.StopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
        }
    
        private void StopPublishingMessage(object sender, RoutedEventArgs e)
           {
            proximityDevice.StopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
        }
    
           // 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;
                   });
           }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value,
                                                  messagePublished);
           }
    
    function messagePublished(sender, messageId) {
        // The message has been successfully published.
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
       Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
       Private publishedMessageId As Long = -1
       Private subscribedMessageId As Long = -1
    
       Private Sub initializeProximityDevice()
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
           If proximityDevice IsNot Nothing Then
               AddHandler PublishMessageButton.Click, AddressOf PublishMessage
               AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
               AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
               AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
           Else
               WriteMessageText("Failed to initialized proximity device." & vbTab)
           End If
       End Sub
    
       Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
           ' Stop publishing the current message.
           If publishedMessageId <> -1 Then
               proximityDevice.StopPublishingMessage(publishedMessageId)
           End If
    
           publishedMessageId =
               proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text,
                                              AddressOf MessagePublished)
       End Sub
    
       Private Sub MessagePublished(
    sender As Windows.Networking.Proximity.ProximityDevice,
           messageId As Long)
    
    ' The message has been successfully published.
       End Sub
    
       Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
           ' 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)
    
           MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
       End Sub
    
       Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
           proximityDevice.StopSubscribingForMessage(subscribedMessageId)
           subscribedMessageId = -1
       End Sub
    
       Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
           proximityDevice.StopPublishingMessage(publishedMessageId)
           publishedMessageId = -1
       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
    
  • PublishUriMessage(Windows.Foundation.Uri)
    PublishUriMessage(Windows.Foundation.Uri)
    PublishUriMessage(Windows.Foundation.Uri)
    PublishUriMessage(Windows.Foundation.Uri)

    Publishes a Uniform Resource Identifier (URI) to a proximate device.

    public long PublishUriMessage(Windows.Foundation.Uri)public long PublishUriMessage(Windows.Foundation.Uri)Public Function PublishUriMessage(Windows.Foundation.Uri) As long

    Parameters

    Returns

    • long
      long
      long
      long

      The publication ID of the message.

    Remarks

    Only one URI can be published at a time for each proximity device.

    You can stop publishing a URI by passing the publication ID returned by the PublishUriMessage(Windows.Foundation.Uri) method to the StopPublishingMessage(System.Int64) method.

    Unlike the other publish methods for a proximity device, URI publishing is handled by the default protocol handler for the URI. A subscription to a URI message publication is not required. You can receive URI messages by registering a default handler for a URI protocol such as the HTTP protocol.

    The PackageFamilyName value of the sending application is automatically sent along with the URI. If no handler is registered for the protocol of a URI, the PackageFamilyName value of the sending application is used to direct the receiving application to the application store.

    You can use the PublishMessage(System.String,System.String) method to publish a text message to a proximate computer. You can use the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method to publish non-text messages or messages that conform to the NDEF messaging standard.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Examples

    private Windows.Networking.Proximity.ProximityDevice proximityDevice;
        
    public MainPage()
    {
        this.InitializeComponent();
    
        initializeProximitySample();
    }
    
    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.");
    }
    
    // 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;
            });
    }
    
    var proximityDevice;
    
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            initializeProximitySample();
    
            args.setPromise(WinJS.UI.processAll());
        }
    };
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    function initializeProximitySample() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            id("publishUriButton").addEventListener("click", publishUri);
            id("stopPublishingUriButton").addEventListener("click",
      stopPublishingUri);
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialize proximity device." +
                 "Your device may not have proximity hardware.<br />";
        }
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Public Sub New()
        Me.InitializeComponent()
    
        initializeProximitySample()
    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
    
    ' 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 Windows.Networking.Proximity.ProximityDevice proximityDevice;
        
    public MainPage()
    {
        this.InitializeComponent();
    
        initializeProximitySample();
    }
    
    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.");
    }
    
    // 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;
            });
    }
    
    var proximityDevice;
    
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            initializeProximitySample();
    
            args.setPromise(WinJS.UI.processAll());
        }
    };
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    function initializeProximitySample() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            id("publishUriButton").addEventListener("click", publishUri);
            id("stopPublishingUriButton").addEventListener("click",
      stopPublishingUri);
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialize proximity device." +
                 "Your device may not have proximity hardware.<br />";
        }
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Public Sub New()
        Me.InitializeComponent()
    
        initializeProximitySample()
    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
    
    ' 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
    
    long publishedUriId = -1;
    
    private void PublishUriButton_Click(object sender, RoutedEventArgs e)
    {
        // Stop publishing the current message.
        if (publishedUriId != -1)
            proximityDevice.StopPublishingMessage(publishedUriId);
    
        publishedUriId =
            proximityDevice.PublishUriMessage(new Uri("http://www.microsoft.com"));
    }
    
    private void StopPublishingUriButton_Click(object sender, RoutedEventArgs e)
    {
        proximityDevice.StopPublishingMessage(publishedUriId);
    }
    
    var publishedUriId = -1;
    
    function publishUri() {
        // Stop publishing the current Uri.
        if (publishedUriId != -1) {
            proximityDevice.stopPublishingUri(publishedUriId);
        }
    
        publishedUriId =
     proximityDevice.publishUri(new Windows.Foundation.Uri("http://www.microsoft.com"));
    }
    
    function stopPublishingUri() {
        proximityDevice.stopPublishingMessage(publishedUriId);
    }
    
    Private publishedUriId As Long = -1
    
    Private Sub PublishUriButton_Click(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedUriId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedUriId)
        End If
    
        publishedUriId =
            proximityDevice.PublishUriMessage(New Uri("http:'www.microsoft.com"))
    End Sub
    
    Private Sub StopPublishingUriButton_Click()
        proximityDevice.StopPublishingMessage(publishedUriId)
    End Sub
    
    long publishedUriId = -1;
    
    private void PublishUriButton_Click(object sender, RoutedEventArgs e)
    {
        // Stop publishing the current message.
        if (publishedUriId != -1)
            proximityDevice.StopPublishingMessage(publishedUriId);
    
        publishedUriId =
            proximityDevice.PublishUriMessage(new Uri("http://www.microsoft.com"));
    }
    
    private void StopPublishingUriButton_Click(object sender, RoutedEventArgs e)
    {
        proximityDevice.StopPublishingMessage(publishedUriId);
    }
    
    var publishedUriId = -1;
    
    function publishUri() {
        // Stop publishing the current Uri.
        if (publishedUriId != -1) {
            proximityDevice.stopPublishingUri(publishedUriId);
        }
    
        publishedUriId =
     proximityDevice.publishUri(new Windows.Foundation.Uri("http://www.microsoft.com"));
    }
    
    function stopPublishingUri() {
        proximityDevice.stopPublishingMessage(publishedUriId);
    }
    
    Private publishedUriId As Long = -1
    
    Private Sub PublishUriButton_Click(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedUriId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedUriId)
        End If
    
        publishedUriId =
            proximityDevice.PublishUriMessage(New Uri("http:'www.microsoft.com"))
    End Sub
    
    Private Sub StopPublishingUriButton_Click()
        proximityDevice.StopPublishingMessage(publishedUriId)
    End Sub
    
  • PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)
    PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)

    Publishes a Uniform Resource Identifier (URI) to a proximate device. The specified handler is called when the message has been transmitted.

    public long PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)public long PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler)Public Function PublishUriMessage(Windows.Foundation.Uri,Windows.Networking.Proximity.MessageTransmittedHandler) As long

    Parameters

    Returns

    • long
      long
      long
      long

      The publication ID of the message.

    Remarks

    Only one URI can be published at a time for each proximity device.

    You can stop publishing a URI by passing the publication ID returned by the PublishUriMessage(Windows.Foundation.Uri) method to the StopPublishingMessage(System.Int64) method.

    Unlike the other publish methods for a proximity device, URI publishing is handled by the default protocol handler for the URI. A subscription to a URI message publication is not required. You can receive URI messages by registering a default handler for a URI protocol such as the HTTP protocol.

    The PackageFamilyName value of the sending application is automatically sent along with the URI. If no handler is registered for the protocol of a URI, the PackageFamilyName value of the sending application is used to direct the receiving application to the application store.

    You can use the PublishMessage(System.String,System.String) method to publish a text message to a proximate computer. You can use the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) method to publish non-text messages or messages that conform to the NDEF messaging standard.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Examples

    private Windows.Networking.Proximity.ProximityDevice proximityDevice;
        
    public MainPage()
    {
        this.InitializeComponent();
    
        initializeProximitySample();
    }
    
    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.");
    }
    
    // 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;
            });
    }
    
    var proximityDevice;
    
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            initializeProximitySample();
    
            args.setPromise(WinJS.UI.processAll());
        }
    };
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    function initializeProximitySample() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            id("publishUriButton").addEventListener("click", publishUri);
            id("stopPublishingUriButton").addEventListener("click",
      stopPublishingUri);
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialize proximity device." +
                 "Your device may not have proximity hardware.<br />";
        }
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Public Sub New()
        Me.InitializeComponent()
    
        initializeProximitySample()
    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
    
    ' 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 Windows.Networking.Proximity.ProximityDevice proximityDevice;
        
    public MainPage()
    {
        this.InitializeComponent();
    
        initializeProximitySample();
    }
    
    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.");
    }
    
    // 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;
            });
    }
    
    var proximityDevice;
    
    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            initializeProximitySample();
    
            args.setPromise(WinJS.UI.processAll());
        }
    };
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    function initializeProximitySample() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            id("publishUriButton").addEventListener("click", publishUri);
            id("stopPublishingUriButton").addEventListener("click",
      stopPublishingUri);
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialize proximity device." +
                 "Your device may not have proximity hardware.<br />";
        }
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Public Sub New()
        Me.InitializeComponent()
    
        initializeProximitySample()
    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
    
    ' 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
    
           long publishedUriId = -1;
    
           private void PublishUriButton_Click(object sender, RoutedEventArgs e)
           {
               // Stop publishing the current message.
               if (publishedUriId != -1)
                   proximityDevice.StopPublishingMessage(publishedUriId);
    
               publishedUriId =
                   proximityDevice.PublishUriMessage(new Uri("http://www.microsoft.com"),
                                                     UriTransmitted);
           }
    
    private void UriTransmitted(
        Windows.Networking.Proximity.ProximityDevice sender,
               long messageId)
           {
        // The Uri has been successfully transmitted.
           }
    
           private void StopPublishingUriButton_Click(object sender, RoutedEventArgs e)
           {
               proximityDevice.StopPublishingMessage(publishedUriId);
           }
    
       var publishedUriId = -1;
       var subscribedUriId = -1;
    
       function publishUri() {
           // Stop publishing the current Uri.
           if (publishedUriId != -1) {
               proximityDevice.stopPublishingUri(publishedUriId);
           }
    
           publishedUriId =
        proximityDevice.publishUri(new Windows.Foundation.Uri("http://www.microsoft.com"),
                                          uriTransmitted);
       }
    
       function uriTransmitted(sender, messageId) {
    // The Uri has been successfully transmitted.
       }
    
       function stopPublishingUri() {
           proximityDevice.stopPublishingMessage(publishedUriId);
       }
    
       Private publishedUriId As Long = -1
    
       Private Sub PublishUriButton_Click(sender As Object, e As RoutedEventArgs)
           ' Stop publishing the current message.
           If publishedUriId <> -1 Then
               proximityDevice.StopPublishingMessage(publishedUriId)
           End If
    
           publishedUriId =
               proximityDevice.PublishUriMessage(New Uri("http:'www.microsoft.com"),
                                                 AddressOf UriTransmitted)
       End Sub
    
       Private Sub UriTransmitted(
    sender As Windows.Networking.Proximity.ProximityDevice,
           messageId As Long)
    
    ' The Uri has been successfully transmitted
       End Sub
    
       Private Sub StopPublishingUriButton_Click()
           proximityDevice.StopPublishingMessage(publishedUriId)
       End Sub
    
  • StopPublishingMessage(System.Int64)
    StopPublishingMessage(System.Int64)
    StopPublishingMessage(System.Int64)
    StopPublishingMessage(System.Int64)

    Stops publishing a message.

    public void StopPublishingMessage(System.Int64)public void StopPublishingMessage(System.Int64)Public Function StopPublishingMessage(System.Int64) As void

    Parameters

    • messageId
      System.Int64
      System.Int64
      System.Int64
      System.Int64

      The publication ID for the message.

    Remarks

    The publication ID for a message is returned from the PublishMessage(System.String,System.String), PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer), and PublishUriMessage(Windows.Foundation.Uri) methods.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
       long publishedMessageId = -1;
       long subscribedMessageId = -1;
    
       private void initializeProximityDevice()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
           if (proximityDevice != null)
           {
               PublishMessageButton.Click += PublishMessage;
               SubscribeForMessageButton.Click += SubscribeForMessage;
         StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
         StopPublishingMessageButton.Click += StopPublishingMessage;
           }
           else
           {
               WriteMessageText("Failed to initialized proximity device.\n");
           }
       }
    
       private void PublishMessage(object sender, RoutedEventArgs e)
       {
           // Stop publishing the current message.
           if (publishedMessageId != -1)
           {
               proximityDevice.StopPublishingMessage(publishedMessageId);
           }
    
           publishedMessageId = 
         proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text);
       }
    
       private void SubscribeForMessage(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)
       {
           MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
       }
    
    private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);
           subscribedMessageId = -1;
    }
    
    private void StopPublishingMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopPublishingMessage(publishedMessageId);
           publishedMessageId = -1;
    }
    
       // 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;
               });
       }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value);
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    Private publishedMessageId As Long = -1
    Private subscribedMessageId As Long = -1
    
    Private Sub initializeProximityDevice()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler PublishMessageButton.Click, AddressOf PublishMessage
            AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
            AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
            AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text)
    End Sub
    
    Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
        ' 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)
    
        MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
    End Sub
    
    Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
        subscribedMessageId = -1
    End Sub
    
    Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopPublishingMessage(publishedMessageId)
        publishedMessageId = -1
    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
    
  • StopSubscribingForMessage(System.Int64)
    StopSubscribingForMessage(System.Int64)
    StopSubscribingForMessage(System.Int64)
    StopSubscribingForMessage(System.Int64)

    Cancels a message subscription.

    public void StopSubscribingForMessage(System.Int64)public void StopSubscribingForMessage(System.Int64)Public Function StopSubscribingForMessage(System.Int64) As void

    Parameters

    • subscriptionId
      System.Int64
      System.Int64
      System.Int64
      System.Int64

      The subscription ID for the message.

    Remarks

    The subscription ID for a message subscription is returned from the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
       long publishedMessageId = -1;
       long subscribedMessageId = -1;
    
       private void initializeProximityDevice()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
           if (proximityDevice != null)
           {
               PublishMessageButton.Click += PublishMessage;
               SubscribeForMessageButton.Click += SubscribeForMessage;
         StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
         StopPublishingMessageButton.Click += StopPublishingMessage;
           }
           else
           {
               WriteMessageText("Failed to initialized proximity device.\n");
           }
       }
    
       private void PublishMessage(object sender, RoutedEventArgs e)
       {
           // Stop publishing the current message.
           if (publishedMessageId != -1)
           {
               proximityDevice.StopPublishingMessage(publishedMessageId);
           }
    
           publishedMessageId = 
         proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text);
       }
    
       private void SubscribeForMessage(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)
       {
           MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
       }
    
    private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);
           subscribedMessageId = -1;
    }
    
    private void StopPublishingMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopPublishingMessage(publishedMessageId);
           publishedMessageId = -1;
    }
    
       // 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;
               });
       }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value);
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    Private publishedMessageId As Long = -1
    Private subscribedMessageId As Long = -1
    
    Private Sub initializeProximityDevice()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler PublishMessageButton.Click, AddressOf PublishMessage
            AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
            AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
            AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text)
    End Sub
    
    Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
        ' 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)
    
        MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
    End Sub
    
    Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
        subscribedMessageId = -1
    End Sub
    
    Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopPublishingMessage(publishedMessageId)
        publishedMessageId = -1
    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
    
  • SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)
    SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)
    SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)
    SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)

    Creates a subscription for a specified message type.

    public long SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)public long SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler)Public Function SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) As long

    Parameters

    Returns

    • long
      long
      long
      long

      A unique ID for the subscription.

    Remarks

    After your app calls the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method, it will receive messages that are published with the same message type (as indicated by the messageType parameter) from any proximate devices. For details on the different message types, see the remarks in the PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer) reference topic.

    You can cancel a subscription by passing the subscription ID that's returned by the SubscribeForMessage(System.String,Windows.Networking.Proximity.MessageReceivedHandler) method to the StopSubscribingForMessage(System.Int64) method.

    You can publish a message to a subscriber by using the PublishMessage(System.String,System.String), PublishBinaryMessage(System.String,Windows.Storage.Streams.IBuffer), or PublishUriMessage(Windows.Foundation.Uri) method.

    Important

    The proximity APIs do not provide authentication, encryption, or message integrity. Do not use proximity to exchange user sensitive information such as passwords, financial data, text messages, email, photographs, or government id numbers.

    Examples

       Windows.Networking.Proximity.ProximityDevice proximityDevice;
       long publishedMessageId = -1;
       long subscribedMessageId = -1;
    
       private void initializeProximityDevice()
       {
           proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
           if (proximityDevice != null)
           {
               PublishMessageButton.Click += PublishMessage;
               SubscribeForMessageButton.Click += SubscribeForMessage;
         StopSubscribingForMessageButton.Click += StopSubscribingForMessage;
         StopPublishingMessageButton.Click += StopPublishingMessage;
           }
           else
           {
               WriteMessageText("Failed to initialized proximity device.\n");
           }
       }
    
       private void PublishMessage(object sender, RoutedEventArgs e)
       {
           // Stop publishing the current message.
           if (publishedMessageId != -1)
           {
               proximityDevice.StopPublishingMessage(publishedMessageId);
           }
    
           publishedMessageId = 
         proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text);
       }
    
       private void SubscribeForMessage(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)
       {
           MessageBlock.Text += "Message received: " + message.DataAsString + "\n";
       }
    
    private void StopSubscribingForMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopSubscribingForMessage(subscribedMessageId);
           subscribedMessageId = -1;
    }
    
    private void StopPublishingMessage(object sender, RoutedEventArgs e)
       {
        proximityDevice.StopPublishingMessage(publishedMessageId);
           publishedMessageId = -1;
    }
    
       // 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;
               });
       }
    
           function id(elementId) {
               return document.getElementById(elementId);
           }
    
           var proximityDevice;
           var publishedMessageId = -1;
           var subscribedMessageId = -1;
    
           function initializeProximityDevice() {
               proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
               if (proximityDevice) {
                   id("publishMessageButton").addEventListener("click", publishMessage);
                   id("subscribeForMessageButton").addEventListener("click", subscribeForMessage);
    	id("stopSubscribingForMessageButton").addEventListener("click", 
    	    stopSubScribingForMessage);
    	id("stopPublishingMessageButton").addEventListener("click", 
    	    stopPublishingMessage);
               }
               else {
                   id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
               }
           }
    
           function publishMessage() {
               // Stop publishing the current message.
               if (publishedMessageId != -1) {
                   proximityDevice.stopPublishingMessage(publishedMessageId);
               }
    
               publishedMessageId = 
    	proximityDevice.publishMessage("Windows.SampleMessage", id("messageText").value);
           }
    
           function subscribeForMessage() {
               // Only subscribe for the message one time.
               if (subscribedMessageId === -1) {
                   subscribedMessageId = 
    	    proximityDevice.subscribeForMessage("Windows.SampleMessage", messageReceived);
               }
           }
    
           function messageReceived(device, message) {
               id("messageDiv").innerHTML += "Message received: " + message.dataAsString + "<br />";
           }
    
    function stopSubscribingForMessage() {
        proximityDevice.stopSubscribingForMessage(subscribedMessageId);
               subscribedMessageId = -1;
    }
    
    function stopPublishingMessage() {
        proximityDevice.stopPublishingMessage(publishedMessageId);
               publishedMessageId = -1;
    }
    
    Private proximityDevice As Windows.Networking.Proximity.ProximityDevice
    Private publishedMessageId As Long = -1
    Private subscribedMessageId As Long = -1
    
    Private Sub initializeProximityDevice()
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler PublishMessageButton.Click, AddressOf PublishMessage
            AddHandler SubscribeForMessageButton.Click, AddressOf SubscribeForMessage
            AddHandler StopSubscribingForMessageButton.Click, AddressOf StopSubscribingForMessage
            AddHandler StopPublishingMessageButton.Click, AddressOf StopPublishingMessage
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub PublishMessage(sender As Object, e As RoutedEventArgs)
        ' Stop publishing the current message.
        If publishedMessageId <> -1 Then
            proximityDevice.StopPublishingMessage(publishedMessageId)
        End If
    
        publishedMessageId =
            proximityDevice.PublishMessage("Windows.SampleMessage", MessageTextBlock.Text)
    End Sub
    
    Private Sub SubscribeForMessage(sender As Object, e As RoutedEventArgs)
        ' 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)
    
        MessageBlock.Text &= "Message received: " & message.DataAsString & vbTab
    End Sub
    
    Private Sub StopSubscribingForMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopSubscribingForMessage(subscribedMessageId)
        subscribedMessageId = -1
    End Sub
    
    Private Sub StopPublishingMessage(sender As Object, e As RoutedEventArgs)
        proximityDevice.StopPublishingMessage(publishedMessageId)
        publishedMessageId = -1
    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
    

Events

  • DeviceArrived
    DeviceArrived
    DeviceArrived
    DeviceArrived

    Occurs when a device enters the proximate range.

    public event DeviceArrivedEventHandler DeviceArrivedpublic event DeviceArrivedEventHandler DeviceArrivedPublic Event DeviceArrived

    Remarks

    Examples

    Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
    private void InitializeProximityDevice()
    {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
        if (proximityDevice != null) {
            proximityDevice.DeviceArrived += ProximityDeviceArrived;
            proximityDevice.DeviceDeparted += ProximityDeviceDeparted;
    
            WriteMessageText("Proximity device initialized.\n");
        }
        else
        {
            WriteMessageText("Failed to initialized proximity device.\n");
        }
    }
    
    private void ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device arrived. id = " + device.DeviceId + "\n");
    }
    
    private void ProximityDeviceDeparted(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device departed. id = " + device.DeviceId + "\n");
    }
    
    // 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;
            });
    }
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    var proximityDevice;
    
    function initializeProximityDevice() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            proximityDevice.addEventListener("devicearrived", proximityDeviceArrived);
            proximityDevice.addEventListener("devicedeparted", proximityDeviceDeparted);
    
            id("messageDiv").innerHTML += "Proximity device initialized.<br />";
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
        }
    }
    
    function proximityDeviceArrived(device) {
        id("messageDiv").innerHTML += "Proximate device arrived. id = " + device.deviceId + "<br />";
    }
    
    function proximityDeviceDeparted(device) {
        id("messageDiv").innerHTML += "Proximate device departed. id = " + device.deviceId + "<br />";
    }
    
    Dim proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub InitializeProximityDevice()
    
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler proximityDevice.DeviceArrived, AddressOf ProximityDeviceArrived
            AddHandler proximityDevice.DeviceDeparted, AddressOf ProximityDeviceDeparted
    
            WriteMessageText("Proximity device initialized." & vbTab)
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub ProximityDeviceArrived(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device arrived. id = " & device.DeviceId & vbTab)
    End Sub
    
    Private Sub ProximityDeviceDeparted(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device departed. id = " & device.DeviceId & vbTab)
    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
    
  • DeviceDeparted
    DeviceDeparted
    DeviceDeparted
    DeviceDeparted

    Occurs when a device leaves the proximate range.

    public event DeviceDepartedEventHandler DeviceDepartedpublic event DeviceDepartedEventHandler DeviceDepartedPublic Event DeviceDeparted

    Remarks

    Examples

    Windows.Networking.Proximity.ProximityDevice proximityDevice;
    
    private void InitializeProximityDevice()
    {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();
    
        if (proximityDevice != null) {
            proximityDevice.DeviceArrived += ProximityDeviceArrived;
            proximityDevice.DeviceDeparted += ProximityDeviceDeparted;
    
            WriteMessageText("Proximity device initialized.\n");
        }
        else
        {
            WriteMessageText("Failed to initialized proximity device.\n");
        }
    }
    
    private void ProximityDeviceArrived(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device arrived. id = " + device.DeviceId + "\n");
    }
    
    private void ProximityDeviceDeparted(Windows.Networking.Proximity.ProximityDevice device)
    {
        WriteMessageText("Proximate device departed. id = " + device.DeviceId + "\n");
    }
    
    // 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;
            });
    }
    
    function id(elementId) {
        return document.getElementById(elementId);
    }
    
    var proximityDevice;
    
    function initializeProximityDevice() {
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();
    
        if (proximityDevice) {
            proximityDevice.addEventListener("devicearrived", proximityDeviceArrived);
            proximityDevice.addEventListener("devicedeparted", proximityDeviceDeparted);
    
            id("messageDiv").innerHTML += "Proximity device initialized.<br />";
        }
        else {
            id("messageDiv").innerHTML += "Failed to initialized proximity device.<br />";
        }
    }
    
    function proximityDeviceArrived(device) {
        id("messageDiv").innerHTML += "Proximate device arrived. id = " + device.deviceId + "<br />";
    }
    
    function proximityDeviceDeparted(device) {
        id("messageDiv").innerHTML += "Proximate device departed. id = " + device.deviceId + "<br />";
    }
    
    Dim proximityDevice As Windows.Networking.Proximity.ProximityDevice
    
    Private Sub InitializeProximityDevice()
    
        proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault()
    
        If proximityDevice IsNot Nothing Then
            AddHandler proximityDevice.DeviceArrived, AddressOf ProximityDeviceArrived
            AddHandler proximityDevice.DeviceDeparted, AddressOf ProximityDeviceDeparted
    
            WriteMessageText("Proximity device initialized." & vbTab)
        Else
            WriteMessageText("Failed to initialized proximity device." & vbTab)
        End If
    End Sub
    
    Private Sub ProximityDeviceArrived(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device arrived. id = " & device.DeviceId & vbTab)
    End Sub
    
    Private Sub ProximityDeviceDeparted(device As Windows.Networking.Proximity.ProximityDevice)
        WriteMessageText("Proximate device departed. id = " & device.DeviceId & vbTab)
    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
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Capabilities

proximity
ID_CAP_PROXIMITY [Windows Phone]

Attributes

Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.DualApiPartitionAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ThreadingAttribute

Details

Assembly

Windows.Networking.Proximity.dll