⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testconnmgr.cpp

📁 使用WM6系统上的连接管理器和RAS进行网络建立和断开的操作.
💻 CPP
字号:
// TestConnMgr.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "TestConnMgr.h"
#include <windows.h>
#include <commctrl.h>
#include "Connmgr_status.h"
#include "Connmgr.h"      
#include <ras.h>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE			g_hInst;			// current instance
HWND				g_hWndMenuBar;		// menu bar handle

// Forward declarations of functions included in this code module:
ATOM			MyRegisterClass(HINSTANCE, LPTSTR);
BOOL			InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

#define LOGF 1
void ShowConnStatusInfo(CONNMGR_CONNECTION_DETAILED_STATUS* pstatusBuffer, int& tp1)
{
	/*RETAILMSG(LOGF, (TEXT("[ConnMgrTest]================enter ShowConnStatusInfo==================")));
	RETAILMSG(LOGF, (TEXT("[ConnMgrTest]type=%d, subtype=%d, Secure=%d, SignalQuality=%d, ConnectionStatus=%d, Flags=%d, Ver=%d\r\n"), pstatusBuffer->dwType, pstatusBuffer->dwSubtype, pstatusBuffer->dwSecure, pstatusBuffer->dwSignalQuality, pstatusBuffer->dwConnectionStatus, pstatusBuffer->dwFlags, pstatusBuffer->dwVer));
	RETAILMSG(LOGF, (TEXT("[ConnMgrTest]ApaterName=%s, Description=%s\r\n"), pstatusBuffer->szAdapterName, pstatusBuffer->szDescription));
	RETAILMSG(LOGF, (TEXT("DestGUID:")));
	ShowGUID(pstatusBuffer->guidDestNet);
	RETAILMSG(LOGF, (TEXT("\r\nSourceGUID:")));
	ShowGUID(pstatusBuffer->guidSourceNet);
	RETAILMSG(LOGF, (TEXT("\r\nLastConnectTime:")));
	ShowSysTime(pstatusBuffer->LastConnectTime);
	RETAILMSG(LOGF, (TEXT("\r\nIPAddr:")));
	ShowIPAddr(pstatusBuffer->pIPAddr);
	RETAILMSG(LOGF, (TEXT("\r\n[ConnMgrTest]================exit ShowConnStatusInfo==================")));
	*/
	TCHAR szOutPutStr[256] = {0};
	TCHAR szTmp1[256] = {0};
	TCHAR szTmp2[256] = {0};
	TCHAR szTmp3[256] = {0};
	if((pstatusBuffer == NULL) || (CM_CONNTYPE_CELLULAR != pstatusBuffer->dwType) || (CONNMGR_STATUS_DISCONNECTED == pstatusBuffer->dwConnectionStatus))
	{
		return;
	}
	tp1++;
	wcscpy(szOutPutStr, TEXT("================enter ShowConnStatusInfo   ===============\r"));
	//wcscat(szOutPutStr, TEXT(""));
	swprintf(szTmp1, TEXT("Description=[%s]\r"), pstatusBuffer->szDescription);
	swprintf(szTmp2, TEXT("subType=[%d]\r"), pstatusBuffer->dwSubtype);
	swprintf(szTmp3, TEXT("ConnectionStatus=[%d]\r"), pstatusBuffer->dwConnectionStatus);
	wcscat(szOutPutStr, szTmp1);
	wcscat(szOutPutStr, szTmp2);
	wcscat(szOutPutStr, szTmp3);
	MessageBox(NULL, szOutPutStr, TEXT("ConnInfo"), MB_OK);
}
//
//query current conncetion information
//
HRESULT
QueryCurrentConnectionInfo(void)
{
	HRESULT hRet = E_FAIL;
	CONNMGR_CONNECTION_DETAILED_STATUS* pstatusBuffer = NULL;
	DWORD dwSize = sizeof(CONNMGR_CONNECTION_DETAILED_STATUS);
	pstatusBuffer = (CONNMGR_CONNECTION_DETAILED_STATUS*)LocalAlloc(LPTR, dwSize);
	memset(pstatusBuffer, 0, dwSize);
	RETAILMSG(LOGF, (TEXT("[ConnMgrTest]enter QueryCurrentConnectionInfo\r\n")));
	hRet = ConnMgrQueryDetailedStatus(pstatusBuffer, &dwSize);
	RETAILMSG(LOGF, (TEXT("[ConnMgrTest]Query result is [%d]\r\n"), hRet));
	switch(hRet)
	{
		case S_OK:
			{
				CONNMGR_CONNECTION_DETAILED_STATUS* pTmpStatus = pstatusBuffer;
				int t1 = 0;
				RETAILMSG(LOGF, (TEXT("[ConnMgrTest]QueryCurrentConnectionInfo OK!\r\n")));
				do
				{
					ShowConnStatusInfo(pTmpStatus, t1);
					pTmpStatus = pTmpStatus->pNext;
				}
				while(pTmpStatus != NULL);
				if(t1 == 0)
				{
					MessageBox(NULL, TEXT("No Data Conncection!"), TEXT("ConnInfo"), MB_OK);
				}
				break;
			}
		case E_INVALIDARG:
			break;
		case E_ACCESSDENIED:
			break;
		case HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER):
			{
				if(pstatusBuffer)
				{
					LocalFree(pstatusBuffer);
				}
				pstatusBuffer = (CONNMGR_CONNECTION_DETAILED_STATUS*)LocalAlloc(LPTR, dwSize);
				memset(pstatusBuffer, 0, dwSize);
				hRet = ConnMgrQueryDetailedStatus(pstatusBuffer, &dwSize);
				RETAILMSG(LOGF, (TEXT("[ConnMgrTest] Query again OK!\r\n")));
				if(S_OK == hRet)
				{
					CONNMGR_CONNECTION_DETAILED_STATUS* pTmpStatus = pstatusBuffer;
					int t1 = 0;
					RETAILMSG(LOGF, (TEXT("[ConnMgrTest]QueryCurrentConnectionInfo OK!\r\n")));
					do
					{
						ShowConnStatusInfo(pTmpStatus, t1);
						pTmpStatus = pTmpStatus->pNext;
						RETAILMSG(LOGF, (TEXT("[ConnMgrTest] [%d]\r\n"), pTmpStatus));
					}
					while(pTmpStatus != NULL);
					if(t1 == 0)
					{
						MessageBox(NULL, TEXT("No Data Conncection!"), TEXT("ConnInfo"), MB_OK);
					}
				}
				RETAILMSG(LOGF, (TEXT("[ConnMgrTest] End Query OK!\r\n")));
				goto Err;
			}
		default:
			RETAILMSG(LOGF, (TEXT("[ConnMgrTest]QueryCurrentConnectionInfo other error!\r\n")));
	}
Err:
	RETAILMSG(LOGF, (TEXT("[ConnMgrTest] return OK!\r\n")));
	LocalFree(pstatusBuffer);
	return hRet;
}

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPTSTR    lpCmdLine,
                   int       nCmdShow)
{
	MSG msg;

	// Perform application initialization:
	if (!InitInstance(hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	HACCEL hAccelTable;
	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTCONNMGR));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}

#define NM_DEBUG 1
#define RAS_CONN_MAX 10
BOOL DisConnectAll(void)
{
	BOOL fRet = TRUE;
	RASCONN *pRasconn = NULL;
	DWORD lpcb;
	DWORD lpcConnections;
	DWORD nRet,i;

	RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] DoDisConnAll\r\n")));

	// 1.allocate memory for all connections
	pRasconn = (RASCONN*)LocalAlloc(LPTR, RAS_CONN_MAX*sizeof(RASCONN));
	if (NULL == pRasconn)
	{
	       RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] error local memory")));
	       fRet = FALSE;
	       goto ErrExit;
	}

        // 2. enumeration all existed connections
        lpcb = RAS_CONN_MAX*sizeof(RASCONN);
        pRasconn[0].dwSize  = sizeof(RASCONN);
        nRet = RasEnumConnections(pRasconn, &lpcb, &lpcConnections);
        if (nRet)
        {
               RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] error RasEnumConnections")));
               fRet = FALSE;
               goto ErrExit;
        }

        // 3. disconnect all existed connections
       RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] [%d] Active RAS connections..\r\n"), lpcConnections));
       for (i = 0; i < lpcConnections; i++)
       {
                RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] Entry name: %s, handle is 0x%x\n"), pRasconn[i].szEntryName, pRasconn[i].hrasconn));
                if (RasHangUp(pRasconn[i].hrasconn) )
                {
                         RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] error RasHangUp\n")));
                         fRet = FALSE;
                }
                else
                {
                         RETAILMSG(NM_DEBUG, (TEXT("[NetMgr] ok RasHangUp\n")));
                }
       }   

ErrExit:
        // 4. clean up
	if (pRasconn)
	{
	       LocalFree(pRasconn);
	}
	return fRet;
}
//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
	WNDCLASS wc;

	wc.style         = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc   = WndProc;
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = hInstance;
	wc.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TESTCONNMGR));
	wc.hCursor       = 0;
	wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName  = 0;
	wc.lpszClassName = szWindowClass;

	return RegisterClass(&wc);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    HWND hWnd;
    TCHAR szTitle[MAX_LOADSTRING];		// title bar text
    TCHAR szWindowClass[MAX_LOADSTRING];	// main window class name

    g_hInst = hInstance; // Store instance handle in our global variable

    // SHInitExtraControls should be called once during your application's initialization to initialize any
    // of the device specific controls such as CAPEDIT and SIPPREF.
    SHInitExtraControls();

    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); 
    LoadString(hInstance, IDC_TESTCONNMGR, szWindowClass, MAX_LOADSTRING);

    //If it is already running, then focus on the window, and exit
    hWnd = FindWindow(szWindowClass, szTitle);	
    if (hWnd) 
    {
        // set focus to foremost child window
        // The "| 0x00000001" is used to bring any owned windows to the foreground and
        // activate them.
        SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
        return 0;
    } 

    if (!MyRegisterClass(hInstance, szWindowClass))
    {
    	return FALSE;
    }

    hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);

    if (!hWnd)
    {
        return FALSE;
    }

    // When the main window is created using CW_USEDEFAULT the height of the menubar (if one
    // is created is not taken into account). So we resize the window after creating it
    // if a menubar is present
    if (g_hWndMenuBar)
    {
        RECT rc;
        RECT rcMenuBar;

        GetWindowRect(hWnd, &rc);
        GetWindowRect(g_hWndMenuBar, &rcMenuBar);
        rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);
		
        MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);


    return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    static SHACTIVATEINFO s_sai;
	
    switch (message) 
    {
        case WM_COMMAND:
            wmId    = LOWORD(wParam); 
            wmEvent = HIWORD(wParam); 
            // Parse the menu selections:
            switch (wmId)
            {
                case IDM_HELP_ABOUT:
				{
                    //DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, About);
					HRESULT hr = QueryCurrentConnectionInfo();
					if(hr != S_OK)
					{
						MessageBox(NULL, _T("Query Failed!"), _T("ERROR"), MB_OK);
					}
                    break;
				}
                case IDM_OK:
					if(DisConnectAll())
					{
						MessageBox(NULL, TEXT("Discconet All Succeed!"), TEXT("ConnInfo"), MB_OK);
					}
					else
					{
						MessageBox(NULL, TEXT("Discconet All Failed!"), TEXT("ConnInfo"), MB_OK);
					}
                    SendMessage (hWnd, WM_CLOSE, 0, 0);				
                    break;
                default:
                    return DefWindowProc(hWnd, message, wParam, lParam);
            }
            break;
        case WM_CREATE:
            SHMENUBARINFO mbi;

            memset(&mbi, 0, sizeof(SHMENUBARINFO));
            mbi.cbSize     = sizeof(SHMENUBARINFO);
            mbi.hwndParent = hWnd;
            mbi.nToolBarId = IDR_MENU;
            mbi.hInstRes   = g_hInst;

            if (!SHCreateMenuBar(&mbi)) 
            {
                g_hWndMenuBar = NULL;
            }
            else
            {
                g_hWndMenuBar = mbi.hwndMB;
            }

            // Initialize the shell activate info structure
            memset(&s_sai, 0, sizeof (s_sai));
            s_sai.cbSize = sizeof (s_sai);
            break;
        case WM_PAINT:
            hdc = BeginPaint(hWnd, &ps);
            
            // TODO: Add any drawing code here...
            
            EndPaint(hWnd, &ps);
            break;
        case WM_DESTROY:
            CommandBar_Destroy(g_hWndMenuBar);
            PostQuitMessage(0);
            break;

        case WM_ACTIVATE:
            // Notify shell of our activate message
            SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
            break;
        case WM_SETTINGCHANGE:
            SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_INITDIALOG:
            {
                // Create a Done button and size it.  
                SHINITDLGINFO shidi;
                shidi.dwMask = SHIDIM_FLAGS;
                shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU;
                shidi.hDlg = hDlg;
                SHInitDialog(&shidi);
            }
            return (INT_PTR)TRUE;

        case WM_COMMAND:
            if (LOWORD(wParam) == IDOK)
            {
                EndDialog(hDlg, LOWORD(wParam));
                return TRUE;
            }
            break;

        case WM_CLOSE:
            EndDialog(hDlg, message);
            return TRUE;

    }
    return (INT_PTR)FALSE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -