SoFunction
Updated on 2025-03-07

PC Bluetooth communication C# code implementation

This article shares the C# implementation of PC Bluetooth communication code for your reference. The specific content is as follows

Add a reference

First create a Bluetooth class

class LanYa {
public string blueName { get; set; }                  //lBluetooth namepublic BluetoothAddress blueAddress { get; set; }        //The unique identifier of Bluetoothpublic ClassOfDevice blueClassOfDevice { get; set; }      //What type of Bluetooth ispublic bool IsBlueAuth { get; set; }                  //The specified device passes verificationpublic bool IsBlueRemembered { get; set; }            //Remember the devicepublic DateTime blueLastSeen { get; set; }
public DateTime blueLastUsed { get; set; }
}
 

Then search for the device

List<LanYa> lanYaList = new List<LanYa>();        //The searched collection of BluetoothBluetoothClient client = new BluetoothClient();      
BluetoothRadio radio = ; //Get Bluetooth adapter = ;            
BluetoothDeviceInfo[] devices = ();//Search for Bluetooth for 10 secondsforeach (var item in devices) {
(new LanYa { blueName = , blueAddress = , blueClassOfDevice = , IsBlueAuth = , IsBlueRemembered = , blueLastSeen = , blueLastUsed =  });//Add the searched Bluetooth to the collection}
 

Bluetooth pairing

BluetoothClient blueclient = new BluetoothClient();
Guid mGUID1 = ;    //Uuid for Bluetooth service 
(, mGUID)   //Start pairing Bluetooth 4.0 does not require setpin
 

Client

BluetoothClient bl = new BluetoothClient();//
Guid mGUID2 = ("00001101-0000-1000-8000-00805F9B34FB");//Uuid for Bluetooth serial port service
try
{
(s.blue_address, mGUID);
//"Connect successfully";}
catch(Exception x)
{
//abnormal}

var v = ();
byte[] sendData = (“Life is short,I usepython”);
(sendData, 0, );       //send

Server side

bluetoothListener = new BluetoothListener(mGUID2);
();//Start monitoring
bl = ();//take over

while (true)
{
byte[] buffer = new byte[100];
Stream peerStream = ();

(buffer, 0, );

string data= Encoding.(buffer).ToString().Replace("\0", "");//Remove the \0 bytes afterward}

Basically that's it!

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.