Omi Kor
Omi Kor

Reputation: 35

Desktop Elements with Winapi

I'm trying to get the elements in the desktop (icon shortcuts) using winapi, but for some reason I'm getting nothing. Am I doing it wrong? (I'm very new to this)

BOOL CALLBACK EnumChildWindows(HWND hwnd,LPARAM lParam) {
    char str[256];
    GetWindowTextA(hwnd, str, 200);
    OutputDebugStringA(str);
    return true;
}

Inside wWinMain:

HWND hDesktop = GetDesktopWindow();
EnumChildWindows(hDesktop, 0);

Upvotes: 1

Views: 299

Answers (1)

Zeus
Zeus

Reputation: 3890

You used the EnumChildWindows function by mistake:

BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {
    char str[256]{};
    GetWindowTextA(hwnd, str, 200);
    OutputDebugStringA(str);
    return true;
}
int main(int argc, const char* argv[])
{
    HWND hDesktop = GetDesktopWindow();
    EnumChildWindows(hDesktop, EnumChildProc, 0);
    return 0;
}

You need to set a callback function and call it with EnumChildWindows.

Of course, this cannot get the name of the "desktop shortcut", what you get is the name of all child windows.

If you want to get the name and location of the desktop shortcut, you need to use COM related, here is an example:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <ShlObj.h>
#include <atlbase.h>

int main(int argc, char** argv)
{
    CComPtr<IShellWindows> spShellWindows;
    CComPtr<IShellBrowser> spBrowser;
    CComPtr<IDispatch> spDispatch;
    CComPtr<IShellView> spShellView;
    CComPtr<IFolderView>  spView;
    CComPtr<IShellFolder> spFolder;
    CComPtr<IEnumIDList>  spEnum;
    CComHeapPtr<ITEMID_CHILD> spidl;
    CComVariant vtLoc(CLSID_ShellWindows);
    CComVariant vtEmpty;
    STRRET str;

    int count = 0;
    HRESULT hr;
    long lhWnd;

    // INITIALIZE COM
    CoInitialize(NULL);

    // GET ShellWindows INTERFACE
    hr = spShellWindows.CoCreateInstance(CLSID_ShellWindows);

    // FIND WINDOW
    hr = spShellWindows->FindWindowSW(
        &vtLoc, &vtEmpty, SWC_DESKTOP, &lhWnd, SWFO_NEEDDISPATCH, &spDispatch);

    // GET DISPATCH INTERFACE
    CComQIPtr<IServiceProvider>(spDispatch)->
        QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&spBrowser));

    spBrowser->QueryActiveShellView(&spShellView);
    spShellView->QueryInterface(IID_PPV_ARGS(&spView));

    hr = spView->GetFolder(IID_PPV_ARGS(&spFolder));

    // GET ENUMERATOR
    spView->Items(SVGIO_ALLVIEW, IID_PPV_ARGS(&spEnum));    // get enumerator

    // ENUMERATE ALL DESKTOP ITEMS
    for (; spEnum->Next(1, &spidl, nullptr) == S_OK; spidl.Free()) {
        // GET/PRINT ICON NAME AND POSITION
        char* name;
        POINT pt;
        spFolder->GetDisplayNameOf(spidl, SHGDN_NORMAL, &str);
        StrRetToStrA(&str, spidl, &name);
        spView->GetItemPosition(spidl, &pt);
        printf("%5d %5d \"%s\"\n", pt.x, pt.y, name);
    }
    CoUninitialize();           // release COM
    exit(0);
}

Upvotes: 2

Related Questions