示例#1
0
HRESULT HrGetBindingPathEnum (IN INetCfgComponent *pncc,
                              IN DWORD dwBindingType,
                              OUT IEnumNetCfgBindingPath **ppencbp)
{
    INetCfgComponentBindings *pnccb = NULL;
    HRESULT                  hr;

    *ppencbp = NULL;

    //
    // Get component's binding.
    //

    hr = pncc->QueryInterface( IID_INetCfgComponentBindings,
                               (PVOID *)&pnccb );

    if ( hr == S_OK ) {

        //
        // Get binding path enumerator reference.
        //

        hr = pnccb->EnumBindingPaths( dwBindingType,
                                      ppencbp );

        ReleaseRef( pnccb );
    }

    return hr;
}
bool ChangeNicBindingOrder()
{
	HRESULT hr = S_OK;

	INetCfg *pNetCfg = NULL; 
	INetCfgBindingPath *pNetCfgPath; 
	INetCfgComponent *pNetCfgComponent = NULL;
	INetCfgComponentBindings *pNetCfgBinding = NULL;
	INetCfgLock *pNetCfgLock = NULL;

	IEnumNetCfgBindingPath *pEnumNetCfgBindingPath = NULL;

	PWSTR szLockedBy;

	if (!SUCCEEDED(CoInitialize(NULL)))
	{
		return false;
	}

	if (S_OK != CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER, IID_INetCfg, (void**)&pNetCfg))
	{
		return false;
	}

	if (!SUCCEEDED(pNetCfg->QueryInterface(IID_INetCfgLock, (LPVOID *)&pNetCfgLock)))
	{
		return false;
	}

	static const ULONG c_cmsTimeout = 5000;
	static const WCHAR c_szSampleNetcfgApp[] = L"TapRebinder (TapRebinder.exe)";

	if (!SUCCEEDED(pNetCfgLock->AcquireWriteLock(c_cmsTimeout, c_szSampleNetcfgApp, &szLockedBy)))
	{
		wprintf(L"Could not lock INetcfg, it is already locked by '%s'", szLockedBy);

		return false;
	}

	if (!SUCCEEDED(pNetCfg->Initialize(NULL)))
	{
		if (pNetCfgLock)
		{
			pNetCfgLock->ReleaseWriteLock();
		}

		ReleaseObj(pNetCfgLock);

		return false;
	}

	ReleaseObj(pNetCfgLock);

	if (S_OK != pNetCfg->FindComponent(L"ms_tcpip", &pNetCfgComponent))
	{
		return false;
	}

	if (S_OK != pNetCfgComponent->QueryInterface(IID_INetCfgComponentBindings, (LPVOID *)&pNetCfgBinding))
	{
		return false;
	}

	if (S_OK != pNetCfgBinding->EnumBindingPaths(EBP_BELOW, &pEnumNetCfgBindingPath))
	{
		return false;
	}

	while (S_OK == hr)
	{
		hr = pEnumNetCfgBindingPath->Next(1, &pNetCfgPath, NULL);

		LPWSTR pszwPathToken;

		pNetCfgPath->GetPathToken(&pszwPathToken);

		if (wcscmp(pszwPathToken, wDeviceInstanceId) == 0)
		{
			wprintf(L"   Moving adapter to the first position: %s.\n", pszwPathToken);

			pNetCfgBinding->MoveBefore(pNetCfgPath, NULL);
			pNetCfg->Apply();

			CoTaskMemFree(pszwPathToken);

			ReleaseObj(pNetCfgPath);

			break;
		}

		CoTaskMemFree(pszwPathToken);

		ReleaseObj(pNetCfgPath);
	}

	ReleaseObj(pEnumNetCfgBindingPath);

	ReleaseObj(pNetCfgBinding);
	ReleaseObj(pNetCfgComponent);

	ReleaseINetCfg(TRUE, pNetCfg);

	return true;
}