Primeiro limparemos todos os controles da aula anterior e criaremos uma janela vazia mínima sem nenhum componente.
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma execution_character_set("utf-8")
#include <GLFW/glfw3.h>
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include <cstdio>
#include <string>
#include <fstream>
#include <windows.h>
#include <io.h>
#include <commdlg.h> // Cabeçalho obrigatório para caixas de diálogo de arquivo
#include <iostream>
using namespace std;
// Configurar fonte para corrigir caracteres ilegíveis "??" ao digitar texto
// Insira o caminho da fonte compatível com seu ambiente ou use a fonte padrão do sistema
void SetupFont(ImGuiIO& io)
{
// Caminho comum de fonte chinesa no Windows
const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // Microsoft YaHei
float font_size = 18.0f;
// Carregar intervalo de caracteres chineses simplificados comuns
ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
builder.BuildRanges(&ranges);
// Carregar fonte personalizada
io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);
// Se precisar de suporte multilíngue pode adicionar os blocos abaixo:
// io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesJapanese());
// io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesKorean());
}
int main()
{
if (!glfwInit())
{
printf("Falha na inicialização do GLFW\n");
return -1;
}
const char* glsl_version = "#version 330";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "Título", nullptr, nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGui::StyleColorsLight();
SetupFont(io); // Carregar fonte para resolver caracteres quebrados
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(io.DisplaySize);
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoSavedSettings;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::Begin("Título", nullptr, window_flags);
// Área de desenho dos controles da interface início
// Fim da área de controles
ImGui::End();
ImGui::PopStyleVar(2);
ImGui::Render();
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(0.12f, 0.12f, 0.12f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}Code language: C++ (cpp)

Agora vamos criar cada controle do ImGui um por um.
Caixa de texto
ImGui::Text("Olá, mundo %d", 123);Code language: PHP (php)

Ele renderiza texto da esquerda para a direita começando no canto superior esquerdo.
Botão
// Exibir botão, o código interno executa ao clicar
if (ImGui::Button("Salvar"))
{
// Código aqui roda após o clique
}Code language: PHP (php)
Há muitos controles disponíveis, vamos ver o exemplo completo abaixo que renderiza todos os componentes comuns de uma vez.
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#pragma execution_character_set("utf-8")
#include <GLFW/glfw3.h>
#include "imgui.h"
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include <cstdio>
#include <string>
#include <cstring>
#include <windows.h>
#include <io.h>
#include <iostream>
using namespace std;
// Configurar fonte para corrigir caracteres ilegíveis "??" ao digitar texto
// Insira o caminho da fonte compatível com seu ambiente ou use a fonte padrão do sistema
void SetupFont(ImGuiIO& io)
{
// Caminho comum de fonte chinesa no Windows
const char* font_path = "C:/Windows/Fonts/msyh.ttc"; // Microsoft YaHei
float font_size = 18.0f;
// Carregar intervalo de caracteres chineses simplificados comuns
ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddRanges(io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
builder.BuildRanges(&ranges);
// Carregar fonte personalizada
io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, ranges.Data);
// Se precisar de suporte multilíngue pode adicionar os blocos abaixo:
// io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesJapanese());
// io.Fonts->AddFontFromFileTTF(font_path, font_size, nullptr, io.Fonts->GetGlyphRangesKorean());
}
// ===================== Variáveis globais vinculadas aos controles =====================
char buf[256] = "Texto de teste de entrada de linha única";
char bufMulti[1024] = "Caixa de texto multilinha\nSegunda linha\nTerceira linha teste em chinês";
float fVal = 0.5f;
int iVal = 50;
bool checkBox1 = false;
bool checkBox2 = true;
int radioIdx = 0;
int comboSel = 0;
ImVec4 color = ImVec4(0.2f, 0.7f, 0.9f, 1.0f);
bool showPopupWin = false;
bool showModal = false;
int tabIndex = 0;
float progress = 0.35f;
int main()
{
SetConsoleOutputCP(65001);
if (!glfwInit())
{
printf("Falha na inicialização do GLFW\n");
return -1;
}
const char* glsl_version = "#version 330";
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(1000, 700, "Exemplo de todos os controles comuns do ImGui", nullptr, nullptr);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
ImGui::StyleColorsLight();
SetupFont(io);
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init(glsl_version);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(io.DisplaySize);
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoSavedSettings;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::Begin("Janela Principal", nullptr, window_flags);
// ========== 1. Barra de menu superior ==========
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Arquivo"))
{
if (ImGui::MenuItem("Novo", "Ctrl+N")) {}
if (ImGui::MenuItem("Salvar", "Ctrl+S")) {}
ImGui::Separator();
if (ImGui::MenuItem("Sair"))
glfwSetWindowShouldClose(window, true);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Ferramentas"))
{
if (ImGui::MenuItem("Abrir exemplo de popup"))
showPopupWin = true;
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Spacing();
// ========== 2. Controles básicos de texto ==========
ImGui::Text("===== Controles de Texto =====");
ImGui::Text("Texto normal Olá mundo %d", 123);
ImGui::TextColored(ImVec4(1, 0, 0, 1), "Texto colorido vermelho");
ImGui::TextDisabled("Texto desabilitado cinza");
ImGui::BulletText("Texto com marcador 1");
ImGui::BulletText("Texto com marcador 2");
ImGui::Spacing();
// ========== 3. Família de botões ==========
ImGui::Text("===== Botões =====");
if (ImGui::Button("Botão normal"))
cout << "Botão normal clicado" << endl;
ImGui::SameLine();
if (ImGui::SmallButton("Botão pequeno"))
cout << "Botão pequeno clicado" << endl;
ImGui::SameLine();
if (ImGui::Button("Botão largo", ImVec2(120, 0)))
cout << "Botão de largura customizada clicado" << endl;
ImGui::Spacing();
// ========== 4. Caixas de entrada ==========
ImGui::Text("===== Controles de Entrada =====");
ImGui::InputText("Entrada de linha única", buf, IM_ARRAYSIZE(buf));
ImGui::InputTextWithHint("Entrada com dica", "Digite o conteúdo aqui...", buf, IM_ARRAYSIZE(buf));
ImGui::InputFloat("Entrada de número decimal", &fVal);
ImGui::InputInt("Entrada de número inteiro", &iVal);
ImGui::Spacing();
ImGui::Text("Caixa de texto multilinha:");
ImVec2 multiSize = ImVec2(500, 80);
ImGui::InputTextMultiline("##multi", bufMulti, IM_ARRAYSIZE(bufMulti), multiSize);
ImGui::Spacing();
// ========== 5. Sliders e barras de arrasto ==========
ImGui::Text("===== Sliders / Controles de Arrasto =====");
ImGui::SliderFloat("Slider decimal", &fVal, 0.0f, 1.0f);
ImGui::SliderInt("Slider inteiro", &iVal, 0, 100);
ImGui::DragFloat("Arrasto float", &fVal, 0.01f);
ImGui::DragInt("Arrasto int", &iVal, 1.0f);
ImGui::Spacing();
// ========== 6. Caixas de seleção e botões de rádio ==========
ImGui::Text("===== Caixas de Seleção & Botões de Rádio =====");
ImGui::Checkbox("Caixa A", &checkBox1);
ImGui::Checkbox("Caixa B", &checkBox2);
ImGui::Text("Grupo de rádio:");
ImGui::RadioButton("Opção 1", &radioIdx, 0); ImGui::SameLine();
ImGui::RadioButton("Opção 2", &radioIdx, 1); ImGui::SameLine();
ImGui::RadioButton("Opção 3", &radioIdx, 2);
ImGui::Spacing();
// ========== 7. Combo suspenso ==========
ImGui::Text("===== Combo Suspenso =====");
const char* items[] = { "Opção A", "Opção B", "Opção C", "Opção D" };
ImGui::Combo("Seleção suspensa", &comboSel, items, IM_ARRAYSIZE(items));
ImGui::Spacing();
// ========== 8. Seletor de cor ==========
ImGui::Text("===== Editor de Cor =====");
ImGui::ColorEdit4("Cor RGBA", (float*)&color);
ImGui::ColorButton("Amostra de cor", color);
ImGui::Spacing();
// ========== 9. Barra de progresso e separadores ==========
ImGui::Text("===== Barra de Progresso / Separadores =====");
ImGui::ProgressBar(progress, ImVec2(300, 0));
ImGui::Text("Valor do progresso: %.2f", progress);
ImGui::Separator(); // Linha separadora horizontal
ImGui::Spacing();
// ========== 10. Nós de árvore recolhíveis ==========
ImGui::Text("===== Painéis de Árvore Recolhíveis =====");
if (ImGui::CollapsingHeader("Painel recolhível – clique para expandir"))
{
ImGui::Text("Conteúdo interno do painel");
ImGui::Button("Botão dentro do painel");
}
if (ImGui::TreeNode("Nó de árvore"))
{
ImGui::BulletText("Subitem 1");
ImGui::BulletText("Subitem 2");
ImGui::TreePop();
}
ImGui::Spacing();
// ========== 11. Abas TabBar ==========
ImGui::Text("===== Abas / TabBar =====");
ImGui::BeginTabBar("TabBar");
if (ImGui::BeginTabItem("Aba 1"))
{
ImGui::Text("Conteúdo da aba 1");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Aba 2"))
{
ImGui::Text("Conteúdo da aba 2");
ImGui::EndTabItem();
}
ImGui::EndTabBar();
ImGui::Spacing();
// ========== 12. Controle de Tabela ==========
ImGui::Text("===== Controle de Tabela =====");
if (ImGui::BeginTable("table1", 3, ImGuiTableFlags_Borders))
{
ImGui::TableSetupColumn("ID");
ImGui::TableSetupColumn("Nome");
ImGui::TableSetupColumn("Valor");
ImGui::TableHeadersRow();
// Linha 1
ImGui::TableNextRow();
ImGui::TableNextColumn(); ImGui::Text("1");
ImGui::TableNextColumn(); ImGui::Text("Teste A");
ImGui::TableNextColumn(); ImGui::Text("%.2f", fVal);
// Linha 2
ImGui::TableNextRow();
ImGui::TableNextColumn(); ImGui::Text("2");
ImGui::TableNextColumn(); ImGui::Text("Teste B");
ImGui::TableNextColumn(); ImGui::Text("%d", iVal);
ImGui::EndTable();
}
ImGui::Spacing();
// ========== 13. Menu de clique direito ==========
ImGui::Text("===== Menu de Clique Direito (clique com botão direito neste texto) =====");
if (ImGui::IsItemClicked(ImGuiMouseButton_Right))
ImGui::OpenPopup("RightMenu");
if (ImGui::BeginPopup("RightMenu"))
{
ImGui::MenuItem("Item do menu direito 1");
ImGui::MenuItem("Item do menu direito 2");
ImGui::Separator();
ImGui::MenuItem("Fechar menu");
ImGui::EndPopup();
}
ImGui::Spacing();
// ========== 14. Janela popup não modal ==========
if (showPopupWin)
{
ImGui::OpenPopup("PopupWindow");
showPopupWin = false;
}
if (ImGui::BeginPopup("PopupWindow"))
{
ImGui::Text("Popup normal, ainda é possível interagir com a janela principal");
if (ImGui::Button("Fechar popup"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
// ========== 15. Diálogo modal ==========
if (ImGui::Button("Abrir diálogo modal"))
showModal = true;
if (showModal)
{
ImGui::OpenPopup("ModalDialog");
showModal = false;
}
if (ImGui::BeginPopupModal("Diálogo Modal", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("O modal bloqueia a janela principal, você deve fechar ele primeiro");
if (ImGui::Button("OK", ImVec2(120, 0)))
{
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
ImGui::End();
ImGui::PopStyleVar(2);
ImGui::Render();
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(0.12f, 0.12f, 0.12f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}Code language: C++ (cpp)
Você pode ir testando aos poucos e aprender o funcionamento de cada controle.


A biblioteca de controles é muito ampla e satisfaz completamente o desenvolvimento de softwares utilitários simples. Conta com árvores recolhíveis, abas, todos os controles de formulário: caixas de texto mono/multilinha, botões de rádio, caixas de seleção, combos suspensos, barras de progresso, painéis recolhíveis, tabelas, menus de clique direito, editores de cor e muito mais. Sinta-se à vontade para testar por conta própria.