C#のWinFormsプロジェクトで、Windows.Devices.Radios アセンブリを利用してBluetoothのレシーバーをオンオフを制御したい場合の方法を備忘録的に投稿します。
Windows.Devices.Radiosで取得
BluetoothなどのWindowsで利用している無線デバイスは[Windows.Devices.Radios]アセンブリで状態や設定ができます。
[Windows.Devices.Radios]は、非同期メソッドで取得するので専用クラスを追加しました。
using System;
using System.Collections.Generic;
using System.Text;
using Windows.Devices.Radios;
using static System.Windows.Forms.AxHost;
namespace Sample
{
internal class BluetoothRadio
{
private IReadOnlyList<Radio>? _radios;
public async Task InitializeAsync()
{
_radios = await Radio.GetRadiosAsync();
}
public async Task SetBluetoothStateAsync(RadioState state, string radioName)
{
if (_radios == null)
await InitializeAsync();
foreach (var radio in _radios!)
{
if (radio.Kind == RadioKind.Bluetooth && radio.Name == radioName)
{
await radio.SetStateAsync(state);
}
}
}
public async Task<List<string>> GetBluttoothDeviceList()
{
if (_radios == null)
await InitializeAsync();
List<string> list = new List<string>();
foreach (var radio in _radios!)
{
if (radio.Kind == RadioKind.Bluetooth)
{
list.Add(radio.Name);
}
}
return list;
}
public async Task<RadioState> GetBluetoothStateAsync(string radioName)
{
if (_radios == null)
await InitializeAsync();
foreach (var radio in _radios!)
{
if (radio.Kind == RadioKind.Bluetooth && radio.Name == radioName)
{
return radio.State;
}
}
return RadioState.Unknown;
}
public Task ConnectAsync(string radioName) => SetBluetoothStateAsync(RadioState.On, radioName);
public Task DisconnectAsync(string radioName) => SetBluetoothStateAsync(RadioState.Off, radioName);
public async Task ResetAsync(string radioName)
{
await DisconnectAsync(radioName);
await Task.Delay(500);
await ConnectAsync(radioName);
}
}
}
利用する方法は、こんな感じでクラスをインスタンス化して非同期で呼び出します。
デバイスの名前を取得するためのNameプロパティがあったので、一覧を取得して名前を指定して制御するデバイスを決めていますがプロパティで戻ってくる文字列は”Bluetooth”でした。大抵の場合はBluetoothレシーバーは1台なので、あまり意味がないかもしれません。
private async void ResetBluetooth()
{
BluetoothRadio bluetoothRadio = new BluetoothRadio();
if (bluetoothRadio != null)
{
List<string> devices = await bluetoothRadio.GetBluttoothDeviceList();
foreach(string device in devices)
{
Debug.WriteLine(device);
await bluetoothRadio.ResetAsync(device);
}
}
}
まとめ
今回は短い記事ですが、Windows.Devices.Radios アセンブリを利用してBluetoothのレシーバーをオンオフを制御したい場合の方法をについて書きました。
“Windows.Devices.Radios” アセンブリを利用すると、接続された無線機器などの状態を簡単に取得や設定が可能です。
WinFormsプロジェクトでBluetooth機器を操作したい人の参考になれば幸いです。
スポンサーリンク
最後までご覧いただき、ありがとうございます。
