You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows 10中使用C# WinForm实现蓝牙的开启与关闭?

WinForm中实现Windows 10蓝牙的开启与关闭

完全可以通过Windows API实现蓝牙的按需开启与关闭,以下是两种适用于Windows 10的可行方案:

方案一:使用Win32 API(BluetoothEnableRadio)

通过P/Invoke调用系统原生的BluetoothEnableRadio函数,这是传统桌面程序的实现方式:

代码示例

using System;
using System.Runtime.InteropServices;

public class BluetoothHelper
{
    [DllImport("irprops.cpl", SetLastError = true)]
    private static extern int BluetoothEnableRadio(IntPtr hRadio, bool fEnable);

    [DllImport("irprops.cpl", SetLastError = true)]
    private static extern int BluetoothFindFirstRadio(ref BLUETOOTH_FIND_RADIO_PARAMS pbtfrp, out IntPtr phRadio);

    [StructLayout(LayoutKind.Sequential)]
    private struct BLUETOOTH_FIND_RADIO_PARAMS
    {
        public int dwSize;
    }

    public static bool ToggleBluetooth(bool enable)
    {
        var paramsStruct = new BLUETOOTH_FIND_RADIO_PARAMS();
        paramsStruct.dwSize = Marshal.SizeOf(typeof(BLUETOOTH_FIND_RADIO_PARAMS));
        
        if (BluetoothFindFirstRadio(ref paramsStruct, out IntPtr radioHandle) != 0)
        {
            int result = BluetoothEnableRadio(radioHandle, enable);
            return result == 0;
        }
        return false;
    }
}

使用时直接调用BluetoothHelper.ToggleBluetooth(true)开启蓝牙,ToggleBluetooth(false)关闭蓝牙。

方案二:使用Windows 10 UWP API(Windows.Devices.Radios)

对于Windows 10及以上系统,推荐使用更现代的UWP Radio API,兼容性更好且无需复杂的P/Invoke:

实现步骤

  1. 在WinForm项目中添加对Windows.Devices的引用(右键项目 -> 添加 -> 引用 -> 浏览 -> 找到C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd)
  2. 编写控制代码:
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Radios;

public class BluetoothRadioHelper
{
    public static async Task<bool> SetBluetoothState(bool enable)
    {
        var radios = await Radio.GetRadiosAsync();
        var bluetoothRadio = radios.FirstOrDefault(r => r.Kind == RadioKind.Bluetooth);
        
        if (bluetoothRadio != null)
        {
            var result = await bluetoothRadio.SetStateAsync(enable ? RadioState.On : RadioState.Off);
            return result == RadioAccessStatus.Allowed;
        }
        return false;
    }
}

调用示例:

// 开启蓝牙
await BluetoothRadioHelper.SetBluetoothState(true);
// 关闭蓝牙
await BluetoothRadioHelper.SetBluetoothState(false);

注意:使用UWP API时,需要确保项目目标平台为Windows 10 1709及以上版本,且程序需以管理员权限运行(或在应用清单中声明相关权限)。

内容的提问来源于stack exchange,提问作者wxit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:27:20