现在的位置: 首页 > 综合 > 正文

无线承载(一)

2018年02月08日 ⁄ 综合 ⁄ 共 21320字 ⁄ 字号 评论关闭
// WifiAssistDlg.h : 头文件
//

#include <shellapi.h>
#include <Wlanapi.h>
#include <NetCon.h>
#include <ObjBase.h>

#pragma comment(lib,"wlanapi.lib")
#pragma comment(lib,"Ole32.lib")
#pragma once

// CWifiAssistDlg 对话框
class CWifiAssistDlg : public CDialogEx
{
// 构造
public:
	CWifiAssistDlg(CWnd* pParent = NULL);	// 标准构造函数

// 对话框数据
	enum { IDD = IDD_WIFIASSIST_DIALOG };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV 支持


// 实现
protected:
	HICON m_hIcon;			//托盘也采用此图标

	// 生成的消息映射函数
	virtual BOOL OnInitDialog();
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()

protected:
	HANDLE m_hClientHandle;
	CString m_strSSID;
	CString m_strPasswd;
	
	bool m_bIsOpen;

	NOTIFYICONDATA m_NotifData;
	
protected:
	DWORD OpenHostedConnection(HANDLE &hClientHandle);
	DWORD QueryHostedStatus(HANDLE &hClientHandle,CString &strSSID);
	DWORD QueryPasswd(HANDLE &hClientHandle,CString &strPasswd);

	BOOL InitRASConnection();

	DWORD InitWlanHostedConfig(HANDLE &hClientHandle);
	DWORD SetSSID(HANDLE &hClientHandle,CString strSSID);
	DWORD EnableWlanHostedNetwork(HANDLE &hClientHandle);
	DWORD ForceStopWlanHostedNetwork(HANDLE &hClientHandle);
	DWORD SetWlanAPPasswd(HANDLE &hClientHandle,CString strPasswd);
	DWORD StartWlanHostednetwordUsing(HANDLE &hClientHandle);

	BOOL ClearICS();
	DWORD ClearWlanHostedNetWord(HANDLE &hClientHandle);

	DWORD PreInitWlanReg();
	BOOL SaveWlanReg();
	
	//Tray 
	void InitTrayWindow(NOTIFYICONDATA &tNotifData);
	LRESULT OnNotifyIcon(WPARAM wParam, LPARAM lParam);
	afx_msg void OnReset();
	afx_msg void OnExit();
	afx_msg void OnClose();

public:
	BOOL PreInitWlan();
	HRESULT LoadConnection(INetSharingManager * pNSM);		//加载 可共享的网络
	DWORD StartWlanHostedNetwork();							//启动无线承载网络
	HRESULT StopICS(INetSharingManager * pNSM,const CString& selConnectionStr);//停止 可共享的网络


public:
	afx_msg void OnBnClickedButton1();
	afx_msg void OnBnClickedButton2();
	afx_msg void OnBnClickedButton3();
	virtual BOOL PreTranslateMessage(MSG* pMsg);
	afx_msg void OnSize(UINT nType, int cx, int cy);
};


// WifiAssistDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "WifiAssist.h"
#include "WifiAssistDlg.h"
#include "afxdialogex.h"

#include "RegWlanStruct\WlanData.h"
#include "MyTrace\MyTrace.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define WM_NOTIFYICON (WM_USER +101)

WlanDataA g_tWlanDataA;
HKEY g_hKey;

#ifdef OPEN_MYTRACE
MyTrace g_tMyTrace;
#endif

// CWifiAssistDlg 对话框
void GetErrorMsg(CString &msg,DWORD code, const CString errorFunName);
char *WideCharToMultiByte(const CString &str);
BOOL  IsProcessRunAsAdmin();	//检测程序是否以管理员权限运行


CWifiAssistDlg::CWifiAssistDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CWifiAssistDlg::IDD, pParent)
	, m_strSSID(_T(""))
	, m_strPasswd(_T(""))
	, m_hClientHandle(NULL)
	, m_bIsOpen(false)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CWifiAssistDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_strSSID);
	DDX_Text(pDX, IDC_EDIT2, m_strPasswd);
}

BEGIN_MESSAGE_MAP(CWifiAssistDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_CLOSE()
	ON_WM_SIZE()
	ON_WM_QUERYDRAGICON()
	ON_COMMAND(ID_M_RESUM, &CWifiAssistDlg::OnReset)
	ON_COMMAND(ID_M_EXIT, &CWifiAssistDlg::OnExit)
	ON_MESSAGE (WM_NOTIFYICON ,&OnNotifyIcon)
	ON_BN_CLICKED(IDC_BUTTON1, &CWifiAssistDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CWifiAssistDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CWifiAssistDlg::OnBnClickedButton3)
END_MESSAGE_MAP()


// CWifiAssistDlg 消息处理程序

BOOL CWifiAssistDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标
	
#ifdef OPEN_MYTRACE
	g_tMyTrace.CleanLog();
#endif
	if(!IsProcessRunAsAdmin())
	{
		MessageBox(TEXT("非管理员权限运行程序可能导致获取网络连接状态失败"));
	}

	PreInitWlan();
	InitTrayWindow(m_NotifData);
	PreInitWlanReg();

	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

// 如果向对话框添加最小化按钮,则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
//  这将由框架自动完成。

void CWifiAssistDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

/***************
* Func:屏蔽 回车键 ESC键盘的默认相应
****************/
BOOL CWifiAssistDlg::PreTranslateMessage(MSG* pMsg)
{
	if (pMsg->message == WM_KEYDOWN)
	{
		switch (pMsg->wParam)
		{
		case VK_RETURN:			
		case VK_ESCAPE:
			return TRUE;break;
		default:
			break;
		}
	}
	return CDialogEx::PreTranslateMessage(pMsg);
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CWifiAssistDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void GetErrorMsg(CString &strMSG,DWORD dwCode, const CString strErrorFunName)
{
	switch (dwCode)
	{
	case ERROR_INVALID_HANDLE:
		strMSG.Format(_T("%s:\n句柄handle违法!"),strErrorFunName);
		break;
	case ERROR_INVALID_PARAMETER:
		strMSG.Format(_T("%s:\n错误或违法的参数!"),strErrorFunName);
		break;
	case ERROR_INVALID_STATE:
		strMSG.Format(_T("%s:\n错误或违法的状态"),strErrorFunName);
		break;
	case ERROR_SERVICE_NOT_ACTIVE:
		strMSG.Format(_T("%s:\n管理员权限运行程序!"),strErrorFunName);
		break;
	default://other
		strMSG.Format(_T("%s:\n其他错误!"),strErrorFunName);
		break;
	};
}

//CString To char*
char *WideCharToMultiByte(const CString &strData)
{
	int nSize;
	char* pszMultiByte;
	nSize = WideCharToMultiByte(CP_ACP, 0, strData, -1, NULL, 0, NULL, NULL);
	pszMultiByte = (char*)malloc((nSize+1));
	WideCharToMultiByte(CP_ACP, 0, strData, -1, pszMultiByte, nSize, NULL, NULL);
	return pszMultiByte;
}

//检测程序是否以管理员权限运行
BOOL  IsProcessRunAsAdmin()
{
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup;

    BOOL  bRet = AllocateAndInitializeSid( &NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup);

    if (bRet)
    {
        CheckTokenMembership(NULL, AdministratorsGroup, &bRet);
        FreeSid(AdministratorsGroup);
    }

    return  bRet;
 }

//打开一个服务器连接
DWORD CWifiAssistDlg::OpenHostedConnection(HANDLE &hClientHandle)
{
	DWORD dwClientVersion = 2;
	DWORD dwNegotiatedVersion = 0;	
	DWORD dwWlan = WlanOpenHandle(dwClientVersion, NULL, &dwNegotiatedVersion, &hClientHandle);
	if(dwWlan != ERROR_SUCCESS )
	{
		CString strMsg;
		GetErrorMsg(strMsg, dwWlan, _T("OpenHostedConnection"));
		AfxMessageBox(strMsg);
	}

#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwWlan);
	g_tMyTrace.PrintImportantLineFuncLog(strData,__LINE__,__FUNCTION__);
#endif
	return dwWlan;
}

//确定无线承载网络的状态,查询SSID,KEY
DWORD CWifiAssistDlg::QueryHostedStatus(HANDLE &hClientHandle,CString &strSSID)
{
	void *pvData = NULL;
	DWORD dwDataSize;
	WLAN_OPCODE_VALUE_TYPE WlanOpcodeValueType;
	DWORD dwRet = WlanHostedNetworkQueryProperty(hClientHandle,wlan_hosted_network_opcode_connection_settings, &dwDataSize,&pvData,&WlanOpcodeValueType,NULL);
	if (dwRet == ERROR_SUCCESS)
	{	
		char szSSID[32]="\0";
		WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS *p = (WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS*)pvData;
		memcpy(szSSID, p->hostedNetworkSSID.ucSSID, p->hostedNetworkSSID.uSSIDLength);
		strSSID = szSSID;
	}
	
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwRet);
	g_tMyTrace.PrintImportantLineFuncLog(strData,__LINE__,__FUNCTION__);
#endif
	return dwRet;
}


//查询 KEY
DWORD CWifiAssistDlg::QueryPasswd(HANDLE &hClientHandle,CString &strPasswd)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD dwKeyLength = 0;//key长度
	unsigned char *pucKeyData = NULL;
	BOOL bIsPassPhrase,bPersistent;
	DWORD dwRet = WlanHostedNetworkQuerySecondaryKey(hClientHandle,&dwKeyLength,&pucKeyData, &bIsPassPhrase,&bPersistent,&failReason,NULL);
	if (dwRet == ERROR_SUCCESS)
	{
		strPasswd = pucKeyData;
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwRet);
	g_tMyTrace.PrintImportantLineFuncLog(strData,__LINE__,__FUNCTION__);
#endif
	return dwRet;
}


// init security to enum RAS connections
BOOL CWifiAssistDlg::InitRASConnection()
{
//初始化com  用于查看是否已开启WIFI外接
	 CoInitialize (NULL);
	 
// init security to enum RAS connections
	 INetSharingManager * pNSM = NULL;

	 //CoInitializeSecurity (NULL, -1, NULL, NULL,RPC_C_AUTHN_LEVEL_NONE,RPC_C_IMP_LEVEL_IDENTIFY,NULL, EOAC_NONE, NULL);
	 CoInitializeSecurity (NULL, -1, NULL, NULL,RPC_C_AUTHN_LEVEL_PKT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL, EOAC_NONE, NULL);
	 HRESULT hr = ::CoCreateInstance (__uuidof(NetSharingManager),NULL,CLSCTX_ALL,__uuidof(INetSharingManager),(void**)&pNSM);
	 if ( !pNSM )
	 {
		 MessageBox(_T("Error:failed to create NetSharingManager object!"),_T("Sorry..."),MB_OK);
		 EndDialog(IDOK);

#ifdef OPEN_MYTRACE
		 g_tMyTrace.PrintImportantLineFuncLog("Fail",__LINE__,__FUNCTION__);
#endif
		 return NULL;
	}
#ifdef OPEN_MYTRACE
	 g_tMyTrace.PrintImportantLineFuncLog("Success",__LINE__,__FUNCTION__);
#endif
	 
	 if( NULL == pNSM )
		 return FALSE;

//加载 可共享的网络连接
	LoadConnection(pNSM);
	pNSM->Release();

	return TRUE;
}

//初始化配置无线承载网络
DWORD CWifiAssistDlg::InitWlanHostedConfig(HANDLE &hClientHandle)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD dwInit = WlanHostedNetworkInitSettings(hClientHandle, &failReason, NULL);	
	if( dwInit != ERROR_SUCCESS )
	{
		CString strMsg;
		GetErrorMsg(strMsg, dwInit, _T("InitWlanHostedConfig"));
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:出错了!"));
		AfxMessageBox(strMsg);
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwInit);
	g_tMyTrace.PrintImportantLineFuncLog(strData,__LINE__,__FUNCTION__);
#endif
	return dwInit;
}

BOOL CWifiAssistDlg::PreInitWlan()
{
//打开一个服务器连接
	if( ERROR_SUCCESS != OpenHostedConnection(m_hClientHandle))
		return FALSE;

//确定无线承载网络的状态,查询SSID,KEY
	if( ERROR_SUCCESS != QueryHostedStatus(m_hClientHandle,m_strSSID))
		return FALSE;

//查询 KEY
	if( ERROR_SUCCESS != QueryPasswd(m_hClientHandle,m_strPasswd))
		return FALSE;

// init security to enum RAS connections
	 if( !InitRASConnection() )
		 return FALSE;
	
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog("",__LINE__,__FUNCTION__);
#endif
	return TRUE;
}

//设置SSID名称
DWORD CWifiAssistDlg::SetSSID(HANDLE &hClientHandle,CString strSSID)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS WHNCS;
	char * pszSSID = WideCharToMultiByte(strSSID);
	memset(WHNCS.hostedNetworkSSID.ucSSID,0,32);
	
	memcpy(WHNCS.hostedNetworkSSID.ucSSID,pszSSID,strlen(pszSSID));		//设置SSID
	WHNCS.hostedNetworkSSID.uSSIDLength = strlen(pszSSID);				//SSID的长度
	WHNCS.dwMaxNumberOfPeers = 10;										//默认值100
	DWORD dwSet = WlanHostedNetworkSetProperty(hClientHandle,wlan_hosted_network_opcode_connection_settings, sizeof(WHNCS),&WHNCS,&failReason,NULL);
	delete []pszSSID;
	pszSSID = NULL;
	
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog("",__LINE__,__FUNCTION__);
#endif
	return dwSet;
}

//启用网络承载
DWORD  CWifiAssistDlg::EnableWlanHostedNetwork(HANDLE &hClientHandle)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	BOOL bEnableHosted = TRUE;
	DWORD dwSet = WlanHostedNetworkSetProperty(hClientHandle,wlan_hosted_network_opcode_enable, sizeof(BOOL),&bEnableHosted,&failReason,NULL);
	if (dwSet != ERROR_SUCCESS)
	{
		CString strMsg,strFailReason;
		GetErrorMsg(strMsg, dwSet, _T("EnableWlanHostedNetwork"));
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:出错了!"));
		strFailReason.Format(_T(":%d"),failReason);
		AfxMessageBox(strMsg+strFailReason);
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwSet);
	g_tMyTrace.PrintImportantLineFuncLog( strData, __LINE__, __FUNCTION__);
#endif
	return dwSet;
}

//先强制关闭 无线承载网络
DWORD CWifiAssistDlg::ForceStopWlanHostedNetwork(HANDLE &hClientHandle)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD dwStop = WlanHostedNetworkForceStop(hClientHandle, &failReason, NULL );
	if (dwStop != ERROR_SUCCESS)
	{
		CString strMsg,strFailReason;
		GetErrorMsg(strMsg, dwStop, _T("ForceStopWlanHostedNetwork"));
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:出错了!"));
		strFailReason.Format(_T(":%d"),failReason);
		AfxMessageBox(strMsg+strFailReason);
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwStop);
	g_tMyTrace.PrintImportantLineFuncLog( strData, __LINE__, __FUNCTION__);
#endif
	return dwStop;
}

//设置无线AP的密码
DWORD CWifiAssistDlg::SetWlanAPPasswd(HANDLE &hClientHandle,CString strPasswd)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	char * pszPasswd = WideCharToMultiByte(strPasswd);
	DWORD dwSet = WlanHostedNetworkSetSecondaryKey(hClientHandle,strlen(pszPasswd)+1, (PUCHAR)pszPasswd,TRUE,TRUE,&failReason,NULL);
	delete []pszPasswd;
	pszPasswd = NULL;
	
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwSet);
	g_tMyTrace.PrintImportantLineFuncLog( strData, __LINE__, __FUNCTION__);
#endif
	return dwSet;
}


//开启 无线承载网络
DWORD CWifiAssistDlg::StartWlanHostednetwordUsing(HANDLE &hClientHandle)
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD dwStart = WlanHostedNetworkStartUsing(hClientHandle, &failReason, NULL );
	if( dwStart != ERROR_SUCCESS )
	{
		CString strMSG,strFailReason;
		GetErrorMsg(strMSG, dwStart, _T("WlanHostedNetworkStartUsing"));
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:出错了!"));
		strFailReason.Format(_T(":%d"), failReason);
		AfxMessageBox( strMSG + strFailReason );
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwStart);
	g_tMyTrace.PrintImportantLineFuncLog( strData, __LINE__, __FUNCTION__);
#endif
	return dwStart;
}



BOOL CWifiAssistDlg::ClearICS()
{
	CString strConnection;
	GetDlgItem(IDC_COMBO1)->GetWindowText(strConnection);
	INetSharingManager * pNSM = NULL; 
    HRESULT hr = ::CoCreateInstance (__uuidof(NetSharingManager),NULL,CLSCTX_ALL,__uuidof(INetSharingManager),(void**)&pNSM);
	if (S_OK != StopICS(pNSM,strConnection))
	{
		pNSM->Release();
		AfxMessageBox(_T("ICS开启失败"));
#ifdef OPEN_MYTRACE
		g_tMyTrace.PrintImportantLineFuncLog("ICS开启失败", __LINE__, __FUNCTION__);
#endif
		return FALSE;
	}
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog( "", __LINE__, __FUNCTION__);
#endif
	return TRUE;
}


DWORD CWifiAssistDlg::ClearWlanHostedNetWord(HANDLE &hClientHandle)
{
	BOOL bStopWlan = FALSE;
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD dwStop = WlanHostedNetworkSetProperty(m_hClientHandle,wlan_hosted_network_opcode_enable, sizeof(BOOL),&bStopWlan,&failReason,NULL);
	if (dwStop == ERROR_SUCCESS)
	{
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:清除成功!"));
		AfxMessageBox(_T("提示:清除成功!"));
	}
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwStop);
	g_tMyTrace.PrintImportantLineFuncLog(strData, __LINE__, __FUNCTION__);
#endif
	return dwStop;
}


DWORD CWifiAssistDlg::PreInitWlanReg()
{
	char sLog[100] = {0};
	CString strSSID,strPasswd;
	DWORD dwRet = 0;
	if(!InitWlanDataRegA(g_hKey,g_tWlanDataA,sLog))
	{
		CStringA sResultA;
		DefaultWlanDataA(g_tWlanDataA);
		sResultA.Format("%s,采用默认配置",sLog);
		MessageBoxA(NULL,sResultA,"提示",1);
		dwRet = 1;
	}
	strSSID = g_tWlanDataA.strSSID;
	strPasswd = g_tWlanDataA.strPasswd;

	SetDlgItemText(IDC_EDIT1,strSSID);
	SetDlgItemText(IDC_EDIT2,strPasswd);
	
#ifdef OPEN_MYTRACE
	CStringA strData;
	strData.Format(("Result:%lu"),dwRet);
	g_tMyTrace.PrintImportantLineFuncLog(strData, __LINE__, __FUNCTION__);
#endif
	return dwRet;
}

BOOL CWifiAssistDlg::SaveWlanReg()
{
	char sLog[100] = {0};
	CString strSSID,strPasswd;

	GetDlgItemText(IDC_EDIT1,strSSID);
	GetDlgItemText(IDC_EDIT2,strPasswd);

	g_tWlanDataA.strSSID = strSSID;
	g_tWlanDataA.strPasswd = strPasswd;
	SaveWlanDataRegA(g_hKey,g_tWlanDataA,sLog);
	
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog( "", __LINE__, __FUNCTION__);
#endif
	return TRUE;
}

//Tray 
void  CWifiAssistDlg::InitTrayWindow(NOTIFYICONDATA &tNotifData)
{
	tNotifData.cbSize = sizeof(NOTIFYICONDATA);
    tNotifData.hWnd = GetSafeHwnd();
    tNotifData.uID = 0;    
    tNotifData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO | NIF_SHOWTIP;
    tNotifData.uCallbackMessage = WM_NOTIFYICON;		// 自己定义消息
	//m_NotifData.hIcon = m_hIcon;
	tNotifData.hIcon = LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME));  

    _tcscpy_s(tNotifData.szTip, _T("Win7无线助手"));
    _tcscpy_s(tNotifData.szInfo,_T("最小化运行ing..."));
    _tcscpy_s(tNotifData.szInfoTitle, _T("Win7无线助手"));
	tNotifData.uVersion = NOTIFYICON_VERSION_4;			//打开高版本
    tNotifData.dwInfoFlags = NIIF_USER|NIIF_LARGE_ICON;	//打开自定义及大图标提示  
	tNotifData.hBalloonIcon = LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME));   
	Shell_NotifyIcon(NIM_SETVERSION,&tNotifData);		//设置vista效果的balloon tips 
    tNotifData.uTimeout = 1000;							//提示时间
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog( "", __LINE__, __FUNCTION__);
#endif
}

LRESULT  CWifiAssistDlg::OnNotifyIcon(WPARAM wParam, LPARAM lParam)
{
    switch(lParam)//根据lParam判断相对应的事件
    {
    case WM_LBUTTONDBLCLK:		//如果左键双击托盘图标,则显示窗体
		{
			Shell_NotifyIcon(NIM_DELETE, &m_NotifData);
			ShowWindow(SW_SHOWNORMAL);
			SetForegroundWindow();
		}break;
	case WM_RBUTTONUP:			//如果右键菜单弹起,则弹出菜单
		{
			CMenu * pTaskMenu, taskMenu;
			taskMenu.LoadMenuW(IDR_MENU1);
			pTaskMenu = taskMenu.GetSubMenu(0);

			CPoint pMousePosition;
			GetCursorPos(&pMousePosition);
			SetForegroundWindow();	//加这句是为了鼠标点击其他地方时,弹出的菜单能够消
			pTaskMenu->TrackPopupMenu( TPM_RIGHTBUTTON,pMousePosition.x,pMousePosition.y,this);
		}break;
    }
    return 0;
}

void  CWifiAssistDlg::OnReset()
{
	Shell_NotifyIcon(NIM_DELETE, &m_NotifData);
	ShowWindow(SW_SHOWNORMAL);
	SetForegroundWindow();
}

void  CWifiAssistDlg::OnExit()
{
	::Shell_NotifyIcon (NIM_DELETE ,&m_NotifData);
	CDialog::OnOK();
}
void  CWifiAssistDlg::OnClose()
{
	if ( m_bIsOpen )
	{
		int ret = MessageBox(_T("退出会关闭Wifi,建议最小化工具!\n继续退出点\"确定\""),_T("提示"),MB_OKCANCEL);
		if (ret != IDOK)
		{
			return;
		}
	}
	::Shell_NotifyIcon (NIM_DELETE ,&m_NotifData);
	OnBnClickedButton2();
	WlanCloseHandle(m_hClientHandle, NULL);
	CoUninitialize();
	CDialogEx::OnClose();
}



HRESULT CWifiAssistDlg::LoadConnection(INetSharingManager * pNSM)	//加载 可共享的网络
{
	//enum connections until we get one that we can convert into an INetSharingConfiguration
	INetConnection * pNetConnect = NULL;			// fill this out for part 2 below	
    INetSharingEveryConnectionCollection * pNSECC = NULL;
	CComboBox *comboBox = (CComboBox*)GetDlgItem(IDC_COMBO1);

	//获取所有可用无线连接
    HRESULT hResult = pNSM->get_EnumEveryConnection (&pNSECC);
#ifdef OPEN_MYTRACE
	CStringA strBuf;
	strBuf.Format("%ld",hResult);
	g_tMyTrace.PrintImportantLineFuncLog(strBuf,__LINE__,__FUNCTION__);
#endif
    if (!pNSECC)
    {
		CString strResult;
		strResult.Format(L"Error:%ld,请确保电脑的无线网卡可用或者已开启无线服务:failed to get EveryConnectionCollection!",hResult);
		AfxMessageBox(strResult);
		return S_FALSE;
	}
    else 
	{
        // enumerate connections
        IEnumVARIANT * pEV = NULL;
        IUnknown * pUnk = NULL;
        hResult = pNSECC->get__NewEnum (&pUnk);
        if (pUnk) 
		{
            hResult = pUnk->QueryInterface (__uuidof(IEnumVARIANT),(void**)&pEV);
            pUnk->Release();
        }
		if (pEV)
		{
			VARIANT variant;
			VariantInit (&variant);
			INetSharingConfiguration * pNSC = NULL;
			while (S_OK == pEV->Next (1, &variant, NULL)) 
			{
				if (V_VT (&variant) == VT_UNKNOWN) 
				{
					V_UNKNOWN (&variant)->QueryInterface (__uuidof(INetConnection),(void**)&pNetConnect);
					if (pNetConnect)
					{  
						INetConnectionProps * pNCP = NULL;
                        pNSM->get_NetConnectionProps (pNetConnect, &pNCP);

						NETCON_STATUS Status;
						pNCP->get_Status(&Status);

						if(NCS_CONNECTED == Status)
						{
							BSTR bstrName;
							pNCP->get_Name(&bstrName);
							comboBox->InsertString(0, bstrName);
							::SysFreeString(bstrName);
						}
						pNCP->Release();
						pNetConnect->Release();
						pNetConnect = NULL;  
					}
				}
				VariantClear (&variant);
			}//end while
			pEV->Release();
		}//end if
		pNSECC->Release();
	}
	comboBox->SetCurSel(0);
	return hResult;
}

HRESULT CWifiAssistDlg::StopICS(INetSharingManager * pNSM,const CString& strConnection)
{
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog( "", __LINE__, __FUNCTION__);
#endif
	INetConnection * pNC = NULL;
    INetSharingEveryConnectionCollection * pNSECC = NULL;
    HRESULT hr = pNSM->get_EnumEveryConnection (&pNSECC);
    if (!pNSECC)
	{
		AfxMessageBox(L"请确保电脑的无线网卡可用或者已开启无线服务:failed to get EveryConnectionCollection!");
		return S_FALSE;
	}
    else 
	{
        // enumerate connections
        IEnumVARIANT * pEV = NULL;
        IUnknown * pUnk = NULL;
        hr = pNSECC->get__NewEnum (&pUnk);
        if (pUnk) 
		{
            hr = pUnk->QueryInterface (__uuidof(IEnumVARIANT), (void**)&pEV);
            pUnk->Release();
        }
		if (pEV)
		{
			VARIANT variant;
			VariantInit (&variant);
			INetSharingConfiguration * pNSC = NULL;
			while (S_OK == pEV->Next (1, &variant, NULL)) 
			{
				if (V_VT (&variant) == VT_UNKNOWN) 
				{
					V_UNKNOWN (&variant)->QueryInterface (__uuidof(INetConnection),(void**)&pNC);
					if (pNC)
					{  
						INetConnectionProps * pNCP = NULL;
                        pNSM->get_NetConnectionProps (pNC, &pNCP);
						BSTR bstrConnectName;
						pNCP->get_Name(&bstrConnectName);

						BSTR bstrDeviceName;
						pNCP->get_Name(&bstrDeviceName);
						if(!_tcscmp(bstrConnectName, strConnection))
						{
							NETCON_STATUS Status;
							pNCP->get_Status(&Status);
							if(Status == NCS_CONNECTED)
							{
								hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC);
								hr = pNSC->DisableSharing();
								pNSC->Release();
							}
						}
						else if(!_tcsstr(bstrDeviceName, _T("Microsoft Virtual WiFi Mini Port Adapter")))
						{
							NETCON_STATUS Status;
							pNCP->get_Status(&Status);
							if(Status == NCS_CONNECTED)
							{
								hr = pNSM->get_INetSharingConfigurationForINetConnection(pNC, &pNSC);
								hr = pNSC->DisableSharing();
								pNSC->Release();
							}
						}
						SysFreeString(bstrConnectName);
						SysFreeString(bstrDeviceName);
						pNC->Release();
						pNC = NULL;  
					}
				}
				VariantClear (&variant);
			}//while
			pEV->Release();
		}//if
		pNSECC->Release();
	}
	return S_OK;
}

DWORD CWifiAssistDlg::StartWlanHostedNetwork()
{
	//初始化配置无线承载网络
	DWORD dwRet = InitWlanHostedConfig(m_hClientHandle);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;

	//设置SSID名称
	dwRet = SetSSID(m_hClientHandle,m_strSSID);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;


	//启用网络承载
	dwRet = EnableWlanHostedNetwork(m_hClientHandle);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;


	//设置无线AP的密码
	dwRet = SetWlanAPPasswd(m_hClientHandle,m_strPasswd);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;

	
	//先强制关闭 无线承载网络
	dwRet = ForceStopWlanHostedNetwork(m_hClientHandle);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;

	
	//开启 无线承载网络
	dwRet = StartWlanHostednetwordUsing(m_hClientHandle);
	if( ERROR_SUCCESS != dwRet)
		return dwRet;
	
#ifdef OPEN_MYTRACE
	g_tMyTrace.PrintImportantLineFuncLog( "", __LINE__, __FUNCTION__);
#endif
	return ERROR_SUCCESS;
}



/***************
* Func:开启热点
****************/
void CWifiAssistDlg::OnBnClickedButton1()
{
	UpdateData();
	
	//检查 ssid key
	if ( 0 == m_strSSID.GetLength()  || m_strPasswd.GetLength() < 8 )
	{
		AfxMessageBox(_T("错误:SSID为空或密钥长度小于8!"));
		return;
	}

	CString strSelConnect;
	GetDlgItem(IDC_COMBO1)->GetWindowText(strSelConnect);

	if(strSelConnect.IsEmpty())
	{
		PreInitWlan();
	}
	
	if (strSelConnect.IsEmpty())
	{
		AfxMessageBox(_T("请选择可以上网的网络连接!"));
		GetDlgItem(IDC_COMBO1)->SetFocus();
		return;
	}

	DWORD hInit = StartWlanHostedNetwork();
	if ( StartWlanHostedNetwork() != ERROR_SUCCESS)
	{
		AfxMessageBox(_T("开启失败..."));
		return;
	}
	GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:wifi启动成功!"));
}


/***************
* Func:关闭热点
****************/
void CWifiAssistDlg::OnBnClickedButton2()
{
	WLAN_HOSTED_NETWORK_REASON failReason;
	DWORD hStop = WlanHostedNetworkForceStop(m_hClientHandle, &failReason, NULL );
	if (hStop == ERROR_SUCCESS)
	{
		GetDlgItem(IDC_STATIC1)->SetWindowText(_T("提示:关闭成功!"));
	}
	m_bIsOpen = false;
	SaveWlanReg();
}


/***************
* Func:清除热点
****************/
void CWifiAssistDlg::OnBnClickedButton3()
{
	//清除ICS
	if( !ClearICS() )
		return;

	//清除无线承载网络
	ClearWlanHostedNetWord(m_hClientHandle);
		
	m_bIsOpen = false;
}



/***************
* Func:最小化运行
****************/
void CWifiAssistDlg::OnSize(UINT nType, int cx, int cy)
{
	CDialogEx::OnSize(nType, cx, cy);
	if(nType == SIZE_MINIMIZED)
	{ 
		Shell_NotifyIcon (NIM_ADD,&m_NotifData);//将图标显示到系统托盘
		ShowWindow(SW_HIDE); // 当最小化时,隐藏主窗口 
	}
}

抱歉!评论已关闭.