GetLogicalDrives() for loop

后端 未结 2 1213
孤独总比滥情好
孤独总比滥情好 2020-12-22 09:08

I am new to the win32 api and need help trying to understand how the GetLogicalDrives() function works. I am trying to populate a cbs_dropdownlist with all the available dri

相关标签:
2条回答
  • 2020-12-22 09:34

    GetLogicalDrives returns a bitmask and to inspect it you need to use bitwise operators. To see if drive A is in use:

    GetLogicalDrives() & 1 == 1
    

    If drive A is unavailable, GetLogicalDrives() & 1 would yield 0 and the condition would fail.

    To check the next drive you'll need to use the next multiple of 2, GetLogicalDrives() & 2, GetLogicalDrives() & 4 and so on.

    You could use GetLogicalDriveStrings but this returns the inverse of what you want, all the used logical drives.

    I would build a table instead, and index into that:

    const char *drive_names[] = 
    {
        "A:",
        "B:",
        ...
        "Z:"
    };
    

    Then your loop could be:

    DWORD drives_bitmask = GetLogicalDrives();
    
    for (DWORD i < 0; i < 32; i++)
    {
        // Shift 1 to a multiple of 2. 1 << 0 = 1 (0000 0001), 1 << 1 = 2 etc.
        DWORD mask_index = 1 << i;
        if (drives_bitmask & i == 0)
        {
            // Drive unavailable, add it to list.
            const char *name = drive_names[i];
            // ... do GUI work.
        }
    }
    
    0 讨论(0)
  • 2020-12-22 09:41

    The function GetLogicalDrives returns a bitmask of the logical drives available. Here is how you would do it:

     DWORD drives = GetLogicalDrives();
     for (int i=0; i<26; i++)
     {
        if( !( drives & ( 1 << i ) ) )
        {
           TCHAR driveName[] = { TEXT('A') + i, TEXT(':'), TEXT('\\'), TEXT('\0') };
           SendMessage(hWndDropMenu, CB_ADDSTRING, 0, (LPARAM)driveName);
        }
     }
    

    The code checks whether the i-th bit in the bitmask is not set to 1 or true.

    0 讨论(0)
提交回复
热议问题