WM蓝牙开发--搜索周围的设备

来源:互联网 发布:网络经纪模式案例分析 编辑:程序博客网 时间:2024/04/30 14:53

开发环境: vs2008+wm6.0 sdk

                HTC3238+手机两台

                1号手机把蓝牙打开,并设为可见模式,2号手机把蓝牙打开

代码如下:

WORD wVersionRequested=0;
WSADATA wsaData;
INT     iResult = 0;
LPWSAQUERYSET pwsaResults;
DWORD    dwSize = 0;
WSAQUERYSET   wsaq;
HCURSOR    hCurs;
HANDLE    hLookup = 0;

// Initialize Winsock
wVersionRequested = MAKEWORD( 2, 2 );

//初始化
if (WSAStartup( wVersionRequested, &wsaData ) != 0)
{
   MessageBox(_T("Could not initialize winsock!"), _T("Fatal Error"), MB_OK);
}

memset (&wsaq, 0, sizeof(wsaq));
wsaq.dwSize      = sizeof(wsaq);
wsaq.dwNameSpace = NS_BTH;
wsaq.lpcsaBuffer = NULL;

// initialize searching procedure
iResult = WSALookupServiceBegin(&wsaq,
   LUP_CONTAINERS,
   &hLookup);

if (iResult != 0)
{
   TCHAR tszErr[32];
   iResult = WSAGetLastError();  
   StringCchPrintf(tszErr, 32, _T("Socket Error: %d"), iResult);
   MessageBox(tszErr, _T("Error"), MB_OK);

}

union {
   CHAR buf[5000];     // returned struct can be quite large
   SOCKADDR_BTH __unused; // properly align buffer to BT_ADDR requirements
};

// save the current cursor
hCurs = GetCursor();

for (; ;)
{
   // set the wait cursor while searching
   SetCursor(LoadCursor(NULL, IDC_WAIT));
   pwsaResults = (LPWSAQUERYSET) buf;

   dwSize = sizeof(buf);

   memset(pwsaResults,0,sizeof(WSAQUERYSET));
   pwsaResults->dwSize      = sizeof(WSAQUERYSET);
   // namespace MUST be NS_BTH for bluetooth queries
   pwsaResults->dwNameSpace = NS_BTH;
   pwsaResults->lpBlob      = NULL;

   // iterate through all found devices, returning name and address
   // (this sample only uses the name, but address could be used for
   // further queries)
   iResult = WSALookupServiceNext (hLookup,
    LUP_RETURN_NAME | LUP_RETURN_ADDR,
    &dwSize,
    pwsaResults);


   if (iResult != 0)
   {
    iResult = WSAGetLastError();
    if (iResult != WSA_E_NO_MORE)
    {
     TCHAR tszErr[32];
     iResult = WSAGetLastError();
     StringCchPrintf(tszErr, 32, _T("Socket Error: %d"), iResult);
     MessageBox(tszErr, _T("Error"), MB_OK);

    }
    // we're finished

    break;
   }

   // add the name to the listbox
   if (pwsaResults->lpszServiceInstanceName)
   {
    m_ctrlDevList.AddString(pwsaResults->lpszServiceInstanceName);
   

   }

}

WSALookupServiceEnd(hLookup);

// restore cursor
SetCursor(hCurs);

 

注意: 要

#include <winsock2.h>
#include <bt_api.h>

不然说NS_BTH没定义

经过测试,在2号手机上运行后可以发现1号手机

 

原创粉丝点击