C++ Win32 菜单栏被绘制在所有者绘制的菜单项上

C++ Win32 Menubar being drawn over owner-drawn menu items

我有2个自绘菜单项,当我启动程序时我只看到一个自绘菜单项;第一个。它正在被绘制,除了菜单栏被绘制在所有其他没有绘制在第一个位置的菜单项上,如果我将鼠标悬停在第二个所有者绘制的菜单项上或以它绘制的任何其他方式更新它,如果我然后与main window (i.g Resizing) 实际上是在更新菜单栏,它继续绘制未在第一个位置绘制的任何其他所有者绘制的项目。

问题:如何让菜单栏不覆盖菜单项,

// 测量项目:

VOID MeasureMenuItem(LPMEASUREITEMSTRUCT ItemStruct)
{
    ItemStruct->itemWidth = 50;
    ItemStruct->itemHeight = 10;
    return;
}

// 抽奖项目:

VOID DrawMenuItem(LPDRAWITEMSTRUCT ItemStruct)
{
    HDC hDC = ItemStruct->hDC;

    SelectObject(hDC, GetStockObject(DC_PEN));
    SelectObject(hDC, GetStockObject(DC_BRUSH));
    SetBkMode(hDC, TRANSPARENT);
    if (ItemStruct->itemState & ODS_HOTLIGHT)
    {
        SetDCPenColor(hDC, RGB(20, 20, 20));
        SetDCBrushColor(hDC, RGB(20, 20, 20));
        SetTextColor(hDC, RGB(255, 255, 255));
    }
    else
    {
        SetDCPenColor(hDC, RGB(70, 70, 70));
        SetDCBrushColor(hDC, RGB(70, 70, 70));
        SetTextColor(hDC, RGB(255, 255, 255));
    }
    Rectangle(hDC, ItemStruct->rcItem.left, ItemStruct->rcItem.top, ItemStruct->rcItem.right, ItemStruct->rcItem.bottom);

    DrawText(hDC, (LPCWSTR)ItemStruct->itemData, -1, &ItemStruct->rcItem, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
    ReleaseDC(MainWindow, hDC);
    return;
}

// 菜单

    HMENU Bar = CreateMenu();
    HMENU File = CreateMenu();
    HMENU Edit = CreateMenu();
    AppendMenu(Bar, MF_OWNERDRAW, (UINT_PTR)File, L"File");
    AppendMenu(Bar, MF_OWNERDRAW, (UINT_PTR)Edit, L"Edit");
    MENUINFO Info;
    Info.cbSize = sizeof(Info);
    Info.fMask = MIM_BACKGROUND;
    Info.hbrBack = (HBRUSH)CreateSolidBrush(RGB(100, 100, 100));
    SetMenuInfo(Bar, &Info);
    SetMenu(MainWindow, Bar);

为什么 DrawMenuItem() 调用 ReleaseDC(MainWindow, hDC);?那不属于那里,摆脱它。您没有从 Get(Window)DC() 获得 HDC,因此您不拥有它,也不应该尝试释放它。

此外,您并没有取消选择您在 HDC 中选择的对象。您需要恢复您替换的原始对象。

试试这个:

VOID DrawMenuItem(LPDRAWITEMSTRUCT ItemStruct)
{
    HDC hDC = ItemStruct->hDC;

    HPEN oldPen = (HPEN) SelectObject(hDC, GetStockObject(DC_PEN));
    HBRUSH oldBrush = (HBRUSH) SelectObject(hDC, GetStockObject(DC_BRUSH));
    SetBkMode(hDC, TRANSPARENT);

    if (ItemStruct->itemState & ODS_HOTLIGHT)
    {
        SetDCPenColor(hDC, RGB(20, 20, 20));
        SetDCBrushColor(hDC, RGB(20, 20, 20));
        SetTextColor(hDC, RGB(255, 255, 255));
    }
    else
    {
        SetDCPenColor(hDC, RGB(70, 70, 70));
        SetDCBrushColor(hDC, RGB(70, 70, 70));
        SetTextColor(hDC, RGB(255, 255, 255));
    }

    Rectangle(hDC, ItemStruct->rcItem.left, ItemStruct->rcItem.top, ItemStruct->rcItem.right, ItemStruct->rcItem.bottom);

    DrawText(hDC, (LPCWSTR)ItemStruct->itemData, -1, &ItemStruct->rcItem, DT_SINGLELINE | DT_CENTER | DT_VCENTER);

    SelectObject(hDC, oldPen);
    SelectObject(hDC, oldBrush); 
}