ocornut / imgui

Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
MIT License
59.33k stars 10.11k forks source link

Add custom button in window title bar #3882

Open s-pravin opened 3 years ago

s-pravin commented 3 years ago

Version/Branch of Dear ImGui:

Version: 1.81 Branch: docking

Back-end/Renderer/Compiler/OS

Back-ends: imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp Operating System: Windows 10

My Issue/Question:

I am trying to customize ImGui window title bar by adding a custom button over it. Though, button content gets rendered as per expectation, button click isn't captured. I have set cursor position to the button location before invoking ItemSize, but am not confident if that's the correct way to achieve this.

Standalone, minimal, complete and verifiable example:

        ImGui::SetNextWindowSize(ImVec2(200, 200));
        ImGui::Begin("Demo Window");
        ImGuiWindow* curWindow = ImGui::GetCurrentWindow();
        ImDrawList* drawList = ImGui::GetForegroundDrawList(curWindow);
        ImRect titlePos = curWindow->TitleBarRect();

        ImGuiContext& g = *GImGui;
        const ImGuiID id = curWindow->GetID("#snap");

        const ImRect bb(ImVec2(titlePos.Max.x - 30, titlePos.Max.y - 15), ImVec2(titlePos.Max.x - 10, titlePos.Max.y - 7));
        ImGui::SetCursorScreenPos(bb.Min);
        ImGui::SetCursorPos(bb.Min);
        ImGui::ItemSize(bb);
        ImGui::ItemAdd(bb, id);

        bool hovered, held;
        bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);

        // Render
        const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
        ImGui::RenderNavHighlight(bb, id);
        ImGui::RenderFrame(bb.Min, bb.Max, col, true);
        drawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f)));
        drawList->AddTriangleFilled(ImVec2(titlePos.Max.x - 30, titlePos.Max.y - 7), ImVec2(titlePos.Max.x - 10, titlePos.Max.y - 7), ImVec2(titlePos.Max.x - 20, titlePos.Max.y - 15), ImGui::GetColorU32(ImVec4(1.0f, 0.0f, 0.0f, 1.0f)));

        ImGui::SetCursorScreenPos(curWindow->ContentRegionRect.Min);
        ImGui::Text("Test Content");
        if (pressed)
            ImGui::Text("Button pressed");
        ImGui::End();
ocornut commented 3 years ago

There are two things at play here: