[Windows API] Programmatically invoking Map Network Drive dialog.

This how the map network drive dialog look like. So how do we show this dialog programmatically?

Map Network Drive

The windows API’s for showing this dialog is: WNetConnectionDialog and WNetConnectionDialog1. I’ve demonstrated both WNetConnectionDialog and WNetConnectionDialog1 in this code snippet. WNetConnectionDialog is a simple API which takes a window handle and a DWORD. While WNetConnectionDialog1 is an API which provides few more parameters along with the flexibility to set up different options. Here’s the code…

#pragma comment(lib, "Mpr.lib")
void PrvMapNetworkDrive(LPTSTR lptszNetworkPath)
{
    CONNECTDLGSTRUCT condlg = { 0 };
    condlg.cbStructure = sizeof(condlg);
    condlg.hwndOwner = GetConsoleWindow();
    condlg.dwFlags =  CONNDLG_USE_MRU;

    NETRESOURCE nr = { 0 };
    nr.dwScope = RESOURCE_GLOBALNET;
    nr.dwType = RESOURCETYPE_DISK;
    nr.lpRemoteName = lptszNetworkPath;
    nr.dwDisplayType = RESOURCEDISPLAYTYPE_DOMAIN;

    condlg.lpConnRes = &nr;

    const int RetVal = WNetConnectionDialog1(&condlg);
    //const int RetVal = WNetConnectionDialog(GetConsoleWindow(), RESOURCETYPE_DISK);

    switch(RetVal)
    {
    case ERROR_INVALID_PARAMETER:
        cerr << "Error: invalid parameter";
        break;
    case ERROR_BAD_DEV_TYPE:
        cerr << "Error: Bad device type";
        break;
    case ERROR_BUSY:
        cerr << "Error: Busy";
        break;
    case ERROR_NO_NETWORK:
        cerr << "Error: No network";
        break;
    case ERROR_NOT_ENOUGH_MEMORY:
        cerr << "Error: Not enough memory";
        break;
    case ERROR_EXTENDED_ERROR:
        {
            DWORD Err = 0;
            TCHAR ErrBuf[MAX_PATH] = {0};
            TCHAR NameBuf[MAX_PATH] = {0};
            WNetGetLastError(&Err, ErrBuf, MAX_PATH, NameBuf, MAX_PATH);
            cerr << "Error: " << ErrBuf;
        }
        break;
    case NO_ERROR:
        cout << "No error";
        break;
    default:
        break;
    };// End switch
}// End PrvMapNetworkDrive

I’ve added basic error checks, you’ll have to test this out properly before production usage.

Appreciate your comments...