开发者

Does TrackPopupMenu "harm" my HMENU?

Heya. Fina开发者_JS百科lly, after a lot of fiddling, I got a .rc-loaded context menu for my tray notify icon working. (Dialog based Windows API application, no MFC). However, in the various examples and usage demonstrations I always saw that the HMENU is being created (CreateMenu(), LoadMenu()) and destroyed (DestroyMenu()) right before/right after the call to TrackPopupMenu(). Popup menus for notify icons are, like, not at all documented on MSDN (at least I haven't found more than a single paragraph about them).

Intuitively, I put the LoadMenu() in the message handling for WM_INITDIALOG and store the HMENU, so I don't have to create and destroy the menu every time. As I said, I haven't found any examples where this is done similarly, which I find a bit intriguing. Is it possible that my HMENU would ever get "corrupted" while using the menu or the application? Or is it safe to go for the (well, marginal) extra performance as I do?

INT_PTR CALLBACK MainDlg(HWND ..., UINT, WPARAM, LPARAM)
{
    switch (message)
    {
    case WM_INITDIALOG:
        ...
        HMENU hMenuBar = LoadMenu(hInst, MAKEINTRESOURCE(IDR_NOTIFYMENU));
        hNotifyMenu = GetSubMenu(hMenuBar, 0);
        ...
        break;

    ...

    case WM_NOTIFYICON:
        switch (lParam)
        {
        case WM_RBUTTONUP:        // there is no WM_CONTEXTMENU for 
            {                     // nid.uVersion != NOTIFYICON_VERSION_4
            POINT CursorPos;
            GetCursorPos(&CursorPos);

            // this is where I saw LoadMenu and stuff in examples

            SetForegroundWindow(hDlg); // otherwise menu won't disappear
            TrackPopupMenu(hNotifyMenu, TPM_LEFTALIGN, CursorPos.x,
                           CursorPos.y, 0, hDlg, NULL);

            PostMessage(hDlg, WM_NULL, 0, 0); // otherwise menu locks hDlg

            // this is where I saw DestroyMenu in examples
            }

            return (INT_PTR)TRUE;
        }
        ...
    }
    ...
}


It's not that it gets corrupted, it's more that you don't want to hold GDI resources longer than absolutely necessary. You can easily run out of them, just look at Chrome that struggled with GDI resource limits for months before finally finding a work around.

Besides loading a menu a dozen times and destroying it is nothing for a modern day processor. Don't prematurely optimize programs, especially not for so little gain.

As to why you haven't found any MSDN pages dealing specifically with notification icons' menus, that's because they're two separate things. A menu is a menu, whether it's on top of a dialog, popping up when you right click a textbox or when you right click a notification icon. You don't need special advice or code for either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜