How to disconnect a bluetooth device from C# .Net in Win7

懵懂的女人 提交于 2019-12-04 15:54:02

Finally, I have got it working by myself !

I searched a bit more in the InTheHand.Net code and finally understood how to make it !

Here is some working code (you will need InTheHand.Net if you want to use it):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using System.Runtime.InteropServices;

namespace BTDisco2
{
    class Program
    {
        const int IOCTL_BTH_DISCONNECT_DEVICE = 0x41000c;
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern bool DeviceIoControl(
        IntPtr hDevice,
        uint dwIoControlCode,
        ref long InBuffer,
        int nInBufferSize,
        IntPtr OutBuffer,
        int nOutBufferSize,
        out int pBytesReturned,
        IntPtr lpOverlapped);

        static void Main(string[] args)
        {
            var r = BluetoothRadio.PrimaryRadio;
            var h = r.Handle;
            long btAddr = BluetoothAddress.Parse("00:1b:3d:0d:ac:31").ToInt64();
            int bytesReturned = 0;
            var success = DeviceIoControl(h,
            IOCTL_BTH_DISCONNECT_DEVICE,
            ref btAddr, 8,
            IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

            if (!success)
            {
                int gle = Marshal.GetLastWin32Error();
                Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "failure: {0} = 0x{0:X}.", gle));
            }
            else
            {
                Console.WriteLine("Success !");
            }
            while (!Console.KeyAvailable) System.Threading.Thread.Sleep(200);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!