• Forum
  • Jobs
  • Program crash What is wrong with this co

 
Program crash What is wrong with this code

You need to call CoInitializeEx() first.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms695279(v=vs.85).aspx

You also need to release the resources properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <windows.h>
#include <netlistmgr.h>
#pragma comment(lib, "ole32.lib")

int main()
{
    CoInitializeEx( nullptr, COINIT_MULTITHREADED ) ;

    INetworkListManager* pNetworkListManager = nullptr;
    HRESULT hr = CoCreateInstance( CLSID_NetworkListManager,
                                   nullptr,
                                   CLSCTX_ALL,
                                   IID_INetworkListManager,
                                   (LPVOID*)&pNetworkListManager );
    if( SUCCEEDED(hr) )
    {
        VARIANT_BOOL bIsConnectedInternet ;
        hr = pNetworkListManager->get_IsConnectedToInternet( &bIsConnectedInternet );

        if( SUCCEEDED(hr)  ) MessageBoxA( nullptr, "", bIsConnectedInternet ? "connected" : "not connected", MB_OK );
        else  MessageBoxA( nullptr, "", "not connected", MB_OK );

        pNetworkListManager->Release() ;
    }

    CoUninitialize() ;
}



Using a smart pointer makes life easier:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <windows.h>
#include <netlistmgr.h>
#include <comdef.h>
#pragma comment(lib, "ole32.lib")

_COM_SMARTPTR_TYPEDEF( INetworkListManager, IID_INetworkListManager ) ;

int main()
{
    CoInitializeEx( nullptr, COINIT_MULTITHREADED ) ;

    {
        INetworkListManagerPtr pNetworkListManager ;
        HRESULT hr = pNetworkListManager.CreateInstance(CLSID_NetworkListManager);
        if( SUCCEEDED(hr) )
        {
            VARIANT_BOOL bIsConnectedInternet ;
            hr = pNetworkListManager->get_IsConnectedToInternet( &bIsConnectedInternet );

            if( SUCCEEDED(hr) ) MessageBoxA( NULL, "", bIsConnectedInternet ? "connected" : "not connected", MB_OK );
            else  MessageBoxA( NULL, "", "not connected", MB_OK );
        }
    } // the com object is released by the smart pointer 

    CoUninitialize() ;
}
@bobsadino
Nothing. You've just edited your start post twice. Once there was the code c++c++c++c++ and so on, and at that time it already has been edited.
There's no reason to report @JLBorges post although I don't know what your question was about before.

Apart from that, it's very stupid to edit your start topic to "How to send an email using c++" although your topic title is about a code that doesn't/didn't work.

I'll report your topic.
Could anyone please remove that topic completely?
Thanks.
Topic archived. No new replies allowed.