LoadImage() returns NULL and GetLastError() return

2020-02-15 02:05发布

I've been searching around the net in different forums for an answer, but there seems to be no match to my case...

I am working on Windows 7, VS2010.

I have an application that uses a timer to call a taskbar refreshing function. Within that taskbar function lies a call to LoadImage() that gets an icon image from the resource files and eventually to the taskber (with shell_notifyicon). When running the application this seems to work fine for the first couple of hours, but then all of the sudden the LoadImage() starts failing (it is always the same .ico file it tries to load) and returns NULL. I've inserted a GetLastError call straight after but it always returns 0 (indicating success). The image itself is still good and valid, and I have no way of explaining that.

Any clue? Any help is much much appreciated!

Here's a code snippet:

if (ghInst && hwnd)
{
    DWORD err;
// Update Tray Icon Here
    small_icon=LoadImage(ghInst, MAKEINTRESOURCE(IconId), IMAGE_ICON,
        GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
    err = GetLastError();
    if (!small_icon)
    {
        LPVOID lpMsgBuf;
        //DWORD err = GetLastError();
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS,
                      NULL,
                      err,
                      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                      (LPTSTR) &lpMsgBuf,
                      0, NULL );

        printf("LoadImage FAILED error message: %d %s\n" ,err ,lpMsgBuf);
    }

    nid.uFlags=NIF_MESSAGE | NIF_ICON | NIF_TIP;
    nid.uCallbackMessage=UWM_SYSTRAY;
    nid.hIcon=small_icon;   /* 16x16 icon */

    if (bIconExist)
        Shell_NotifyIcon(NIM_MODIFY, &nid);
    else
        Shell_NotifyIcon(NIM_ADD, &nid);
}

标签: c windows
1条回答
我想做一个坏孩纸
2楼-- · 2020-02-15 02:42

I think the problem almost certainly is that you are leaking GDI objects and are running out of GDI object handles. The standard Windows Task Manager can show you the GDI object count for your process.

You aren't calling LoadImage with LR_SHARED, so you must free the icon with DestroyIcon afterward. See the "Remarks" section for the LoadImage documentation:

http://msdn.microsoft.com/en-us/library/ms648045%28v=VS.85%29.aspx

(Incidentally, you also should free the string allocated by FormatMessage.)

查看更多
登录 后发表回答