.Net(Mobile) BlutoothのON/OFFを行うには

BlutoothのON/OFFを行うにはBthSetModeというAPIを使用します。

Imports System.Runtime.InteropServices

Public Class Form1
    Public Enum RadioMode
        RadioOff = 0            'Bluetooth OFF
        Connectable = 1         'Bluetooth ON(他のデバイスから検索不可)
        Discoverable = 2        'Bluetooth ON(他のデバイスから検索可)
    End Enum
    
     _
    Public Shared Function BthGetMode(ByRef dwMode As RadioMode) As Integer
    End Function
    
     _
    Public Shared Function BthSetMode(ByVal dwMode As RadioMode) As Integer
    End Function

    'Bluetooth ON
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SetBluetooth(True)
    End Sub
    
    'Bluetooth OFF
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        SetBluetooth(False)
    End Sub

    Private Sub SetBluetooth(ByVal isEnabled As Boolean)
        If (isEnabled) Then
            Dim mode As RadioMode = RadioMode.RadioOff
            Dim ret As Integer = BthGetMode(mode)
            If mode = RadioMode.RadioOff Then
                ret = BthSetMode(RadioMode.Discoverable)
                If ret = 0 Then
                    Do
                        System.Threading.Thread.Sleep(100)
                        ret = BthGetMode(mode)
                        If ret <> 0 OrElse mode <> RadioMode.RadioOff Then
                            Exit Do
                        End If
                    Loop
                End If
            End If
        Else
            Dim mode As RadioMode = RadioMode.Connectable
            Dim ret As Integer = BthGetMode(mode)
            If mode = RadioMode.Connectable Or mode = RadioMode.Discoverable Then
                ret = BthSetMode(RadioMode.RadioOff)
            End If
        End If
    End Sub
End Class

0 件のコメント: