• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications)
2 // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3 
4 // Implemented features:
5 //  [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
6 //  [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
7 //  [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
8 //  [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9 
10 // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11 // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12 // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
13 // Read online: https://github.com/ocornut/imgui/tree/master/docs
14 
15 #include "imgui.h"
16 #include "imgui_impl_win32.h"
17 #ifndef WIN32_LEAN_AND_MEAN
18 #define WIN32_LEAN_AND_MEAN
19 #endif
20 #include <windows.h>
21 #include <tchar.h>
22 #include <dwmapi.h>
23 
24 // Configuration flags to add in your imconfig.h file:
25 //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD              // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant.
26 
27 // Using XInput for gamepad (will load DLL dynamically)
28 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
29 #include <xinput.h>
30 typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
31 typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*);
32 #endif
33 
34 // CHANGELOG
35 // (minor and older changes stripped away, please see git history for details)
36 //  2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages.
37 //  2021-08-02: Inputs: Fixed keyboard modifiers being reported when host windo doesn't have focus.
38 //  2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events).
39 //  2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
40 //  2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1).
41 //  2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS).
42 //  2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi).
43 //  2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1.
44 //  2021-01-25: Inputs: Dynamically loading XInput DLL.
45 //  2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed.
46 //  2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs)
47 //  2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions.
48 //  2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT.
49 //  2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
50 //  2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter().
51 //  2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent.
52 //  2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages.
53 //  2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
54 //  2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
55 //  2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
56 //  2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
57 //  2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
58 //  2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
59 //  2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
60 //  2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
61 //  2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
62 //  2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
63 //  2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
64 //  2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
65 //  2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
66 //  2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
67 //  2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
68 //  2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set.
69 
70 struct ImGui_ImplWin32_Data
71 {
72     HWND                        hWnd;
73     HWND                        MouseHwnd;
74     bool                        MouseTracked;
75     INT64                       Time;
76     INT64                       TicksPerSecond;
77     ImGuiMouseCursor            LastMouseCursor;
78     bool                        HasGamepad;
79     bool                        WantUpdateHasGamepad;
80 
81 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
82     HMODULE                     XInputDLL;
83     PFN_XInputGetCapabilities   XInputGetCapabilities;
84     PFN_XInputGetState          XInputGetState;
85 #endif
86 
ImGui_ImplWin32_DataImGui_ImplWin32_Data87     ImGui_ImplWin32_Data()      { memset(this, 0, sizeof(*this)); }
88 };
89 
90 // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
91 // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
92 // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
93 // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
ImGui_ImplWin32_GetBackendData()94 static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData()
95 {
96     return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : NULL;
97 }
98 
99 // Functions
ImGui_ImplWin32_Init(void * hwnd)100 bool    ImGui_ImplWin32_Init(void* hwnd)
101 {
102     ImGuiIO& io = ImGui::GetIO();
103     IM_ASSERT(io.BackendPlatformUserData == NULL && "Already initialized a platform backend!");
104 
105     INT64 perf_frequency, perf_counter;
106     if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency))
107         return false;
108     if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter))
109         return false;
110 
111     // Setup backend capabilities flags
112     ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)();
113     io.BackendPlatformUserData = (void*)bd;
114     io.BackendPlatformName = "imgui_impl_win32";
115     io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;         // We can honor GetMouseCursor() values (optional)
116     io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;          // We can honor io.WantSetMousePos requests (optional, rarely used)
117 
118     bd->hWnd = (HWND)hwnd;
119     bd->WantUpdateHasGamepad = true;
120     bd->TicksPerSecond = perf_frequency;
121     bd->Time = perf_counter;
122     bd->LastMouseCursor = ImGuiMouseCursor_COUNT;
123 
124     io.ImeWindowHandle = hwnd;
125 
126     // Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime.
127     io.KeyMap[ImGuiKey_Tab] = VK_TAB;
128     io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
129     io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
130     io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
131     io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
132     io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR;
133     io.KeyMap[ImGuiKey_PageDown] = VK_NEXT;
134     io.KeyMap[ImGuiKey_Home] = VK_HOME;
135     io.KeyMap[ImGuiKey_End] = VK_END;
136     io.KeyMap[ImGuiKey_Insert] = VK_INSERT;
137     io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
138     io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
139     io.KeyMap[ImGuiKey_Space] = VK_SPACE;
140     io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
141     io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
142     io.KeyMap[ImGuiKey_KeyPadEnter] = VK_RETURN;
143     io.KeyMap[ImGuiKey_A] = 'A';
144     io.KeyMap[ImGuiKey_C] = 'C';
145     io.KeyMap[ImGuiKey_V] = 'V';
146     io.KeyMap[ImGuiKey_X] = 'X';
147     io.KeyMap[ImGuiKey_Y] = 'Y';
148     io.KeyMap[ImGuiKey_Z] = 'Z';
149 
150     // Dynamically load XInput library
151 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
152     const char* xinput_dll_names[] =
153     {
154         "xinput1_4.dll",   // Windows 8+
155         "xinput1_3.dll",   // DirectX SDK
156         "xinput9_1_0.dll", // Windows Vista, Windows 7
157         "xinput1_2.dll",   // DirectX SDK
158         "xinput1_1.dll"    // DirectX SDK
159     };
160     for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++)
161         if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n]))
162         {
163             bd->XInputDLL = dll;
164             bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities");
165             bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState");
166             break;
167         }
168 #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
169 
170     return true;
171 }
172 
ImGui_ImplWin32_Shutdown()173 void    ImGui_ImplWin32_Shutdown()
174 {
175     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
176     IM_ASSERT(bd != NULL && "No platform backend to shutdown, or already shutdown?");
177     ImGuiIO& io = ImGui::GetIO();
178 
179     // Unload XInput library
180 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
181     if (bd->XInputDLL)
182         ::FreeLibrary(bd->XInputDLL);
183 #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
184 
185     io.BackendPlatformName = NULL;
186     io.BackendPlatformUserData = NULL;
187     IM_DELETE(bd);
188 }
189 
ImGui_ImplWin32_UpdateMouseCursor()190 static bool ImGui_ImplWin32_UpdateMouseCursor()
191 {
192     ImGuiIO& io = ImGui::GetIO();
193     if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
194         return false;
195 
196     ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
197     if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
198     {
199         // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
200         ::SetCursor(NULL);
201     }
202     else
203     {
204         // Show OS mouse cursor
205         LPTSTR win32_cursor = IDC_ARROW;
206         switch (imgui_cursor)
207         {
208         case ImGuiMouseCursor_Arrow:        win32_cursor = IDC_ARROW; break;
209         case ImGuiMouseCursor_TextInput:    win32_cursor = IDC_IBEAM; break;
210         case ImGuiMouseCursor_ResizeAll:    win32_cursor = IDC_SIZEALL; break;
211         case ImGuiMouseCursor_ResizeEW:     win32_cursor = IDC_SIZEWE; break;
212         case ImGuiMouseCursor_ResizeNS:     win32_cursor = IDC_SIZENS; break;
213         case ImGuiMouseCursor_ResizeNESW:   win32_cursor = IDC_SIZENESW; break;
214         case ImGuiMouseCursor_ResizeNWSE:   win32_cursor = IDC_SIZENWSE; break;
215         case ImGuiMouseCursor_Hand:         win32_cursor = IDC_HAND; break;
216         case ImGuiMouseCursor_NotAllowed:   win32_cursor = IDC_NO; break;
217         }
218         ::SetCursor(::LoadCursor(NULL, win32_cursor));
219     }
220     return true;
221 }
222 
ImGui_ImplWin32_UpdateMousePos()223 static void ImGui_ImplWin32_UpdateMousePos()
224 {
225     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
226     ImGuiIO& io = ImGui::GetIO();
227     IM_ASSERT(bd->hWnd != 0);
228 
229     const ImVec2 mouse_pos_prev = io.MousePos;
230     io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
231 
232     // Obtain focused and hovered window. We forward mouse input when focused or when hovered (and no other window is capturing)
233     HWND focused_window = ::GetForegroundWindow();
234     HWND hovered_window = bd->MouseHwnd;
235     HWND mouse_window = NULL;
236     if (hovered_window && (hovered_window == bd->hWnd || ::IsChild(hovered_window, bd->hWnd)))
237         mouse_window = hovered_window;
238     else if (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd)))
239         mouse_window = focused_window;
240     if (mouse_window == NULL)
241         return;
242 
243     // Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
244     if (io.WantSetMousePos)
245     {
246         POINT pos = { (int)mouse_pos_prev.x, (int)mouse_pos_prev.y };
247         if (::ClientToScreen(bd->hWnd, &pos))
248             ::SetCursorPos(pos.x, pos.y);
249     }
250 
251     // Set Dear ImGui mouse position from OS position
252     POINT pos;
253     if (::GetCursorPos(&pos) && ::ScreenToClient(mouse_window, &pos))
254         io.MousePos = ImVec2((float)pos.x, (float)pos.y);
255 }
256 
257 // Gamepad navigation mapping
ImGui_ImplWin32_UpdateGamepads()258 static void ImGui_ImplWin32_UpdateGamepads()
259 {
260 #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
261     ImGuiIO& io = ImGui::GetIO();
262     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
263     memset(io.NavInputs, 0, sizeof(io.NavInputs));
264     if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
265         return;
266 
267     // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
268     // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
269     if (bd->WantUpdateHasGamepad)
270     {
271         XINPUT_CAPABILITIES caps;
272         bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false;
273         bd->WantUpdateHasGamepad = false;
274     }
275 
276     io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
277     XINPUT_STATE xinput_state;
278     if (bd->HasGamepad && bd->XInputGetState && bd->XInputGetState(0, &xinput_state) == ERROR_SUCCESS)
279     {
280         const XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
281         io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
282 
283         #define MAP_BUTTON(NAV_NO, BUTTON_ENUM)     { io.NavInputs[NAV_NO] = (gamepad.wButtons & BUTTON_ENUM) ? 1.0f : 0.0f; }
284         #define MAP_ANALOG(NAV_NO, VALUE, V0, V1)   { float vn = (float)(VALUE - V0) / (float)(V1 - V0); if (vn > 1.0f) vn = 1.0f; if (vn > 0.0f && io.NavInputs[NAV_NO] < vn) io.NavInputs[NAV_NO] = vn; }
285         MAP_BUTTON(ImGuiNavInput_Activate,      XINPUT_GAMEPAD_A);              // Cross / A
286         MAP_BUTTON(ImGuiNavInput_Cancel,        XINPUT_GAMEPAD_B);              // Circle / B
287         MAP_BUTTON(ImGuiNavInput_Menu,          XINPUT_GAMEPAD_X);              // Square / X
288         MAP_BUTTON(ImGuiNavInput_Input,         XINPUT_GAMEPAD_Y);              // Triangle / Y
289         MAP_BUTTON(ImGuiNavInput_DpadLeft,      XINPUT_GAMEPAD_DPAD_LEFT);      // D-Pad Left
290         MAP_BUTTON(ImGuiNavInput_DpadRight,     XINPUT_GAMEPAD_DPAD_RIGHT);     // D-Pad Right
291         MAP_BUTTON(ImGuiNavInput_DpadUp,        XINPUT_GAMEPAD_DPAD_UP);        // D-Pad Up
292         MAP_BUTTON(ImGuiNavInput_DpadDown,      XINPUT_GAMEPAD_DPAD_DOWN);      // D-Pad Down
293         MAP_BUTTON(ImGuiNavInput_FocusPrev,     XINPUT_GAMEPAD_LEFT_SHOULDER);  // L1 / LB
294         MAP_BUTTON(ImGuiNavInput_FocusNext,     XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
295         MAP_BUTTON(ImGuiNavInput_TweakSlow,     XINPUT_GAMEPAD_LEFT_SHOULDER);  // L1 / LB
296         MAP_BUTTON(ImGuiNavInput_TweakFast,     XINPUT_GAMEPAD_RIGHT_SHOULDER); // R1 / RB
297         MAP_ANALOG(ImGuiNavInput_LStickLeft,    gamepad.sThumbLX,  -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
298         MAP_ANALOG(ImGuiNavInput_LStickRight,   gamepad.sThumbLX,  +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
299         MAP_ANALOG(ImGuiNavInput_LStickUp,      gamepad.sThumbLY,  +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
300         MAP_ANALOG(ImGuiNavInput_LStickDown,    gamepad.sThumbLY,  -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32767);
301         #undef MAP_BUTTON
302         #undef MAP_ANALOG
303     }
304 #endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
305 }
306 
ImGui_ImplWin32_NewFrame()307 void    ImGui_ImplWin32_NewFrame()
308 {
309     ImGuiIO& io = ImGui::GetIO();
310     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
311     IM_ASSERT(bd != NULL && "Did you call ImGui_ImplWin32_Init()?");
312 
313     // Setup display size (every frame to accommodate for window resizing)
314     RECT rect = { 0, 0, 0, 0 };
315     ::GetClientRect(bd->hWnd, &rect);
316     io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
317 
318     // Setup time step
319     INT64 current_time = 0;
320     ::QueryPerformanceCounter((LARGE_INTEGER*)&current_time);
321     io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond;
322     bd->Time = current_time;
323 
324     // Update OS mouse position
325     ImGui_ImplWin32_UpdateMousePos();
326 
327     // Update OS mouse cursor with the cursor requested by imgui
328     ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
329     if (bd->LastMouseCursor != mouse_cursor)
330     {
331         bd->LastMouseCursor = mouse_cursor;
332         ImGui_ImplWin32_UpdateMouseCursor();
333     }
334 
335     // Update game controllers (if enabled and available)
336     ImGui_ImplWin32_UpdateGamepads();
337 }
338 
339 // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
340 #ifndef WM_MOUSEHWHEEL
341 #define WM_MOUSEHWHEEL 0x020E
342 #endif
343 #ifndef DBT_DEVNODES_CHANGED
344 #define DBT_DEVNODES_CHANGED 0x0007
345 #endif
346 
347 // Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
348 // Call from your application's message handler.
349 // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
350 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
351 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
352 // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
353 // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds.
354 // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
355 #if 0
356 // Copy this line into your .cpp file to forward declare the function.
357 extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
358 #endif
ImGui_ImplWin32_WndProcHandler(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)359 IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
360 {
361     if (ImGui::GetCurrentContext() == NULL)
362         return 0;
363 
364     ImGuiIO& io = ImGui::GetIO();
365     ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
366 
367     switch (msg)
368     {
369     case WM_MOUSEMOVE:
370         // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events
371         bd->MouseHwnd = hwnd;
372         if (!bd->MouseTracked)
373         {
374             TRACKMOUSEEVENT tme = { sizeof(tme), TME_LEAVE, hwnd, 0 };
375             ::TrackMouseEvent(&tme);
376             bd->MouseTracked = true;
377         }
378         break;
379     case WM_MOUSELEAVE:
380         if (bd->MouseHwnd == hwnd)
381             bd->MouseHwnd = NULL;
382         bd->MouseTracked = false;
383         break;
384     case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
385     case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
386     case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
387     case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
388     {
389         int button = 0;
390         if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
391         if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
392         if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
393         if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
394         if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL)
395             ::SetCapture(hwnd);
396         io.MouseDown[button] = true;
397         return 0;
398     }
399     case WM_LBUTTONUP:
400     case WM_RBUTTONUP:
401     case WM_MBUTTONUP:
402     case WM_XBUTTONUP:
403     {
404         int button = 0;
405         if (msg == WM_LBUTTONUP) { button = 0; }
406         if (msg == WM_RBUTTONUP) { button = 1; }
407         if (msg == WM_MBUTTONUP) { button = 2; }
408         if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
409         io.MouseDown[button] = false;
410         if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd)
411             ::ReleaseCapture();
412         return 0;
413     }
414     case WM_MOUSEWHEEL:
415         io.MouseWheel += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
416         return 0;
417     case WM_MOUSEHWHEEL:
418         io.MouseWheelH += (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA;
419         return 0;
420     case WM_KEYDOWN:
421     case WM_KEYUP:
422     case WM_SYSKEYDOWN:
423     case WM_SYSKEYUP:
424     {
425         bool down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
426         if (wParam < 256)
427             io.KeysDown[wParam] = down;
428         if (wParam == VK_CONTROL)
429             io.KeyCtrl = down;
430         if (wParam == VK_SHIFT)
431             io.KeyShift = down;
432         if (wParam == VK_MENU)
433             io.KeyAlt = down;
434         return 0;
435     }
436     case WM_SETFOCUS:
437     case WM_KILLFOCUS:
438         io.AddFocusEvent(msg == WM_SETFOCUS);
439         return 0;
440     case WM_CHAR:
441         // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
442         if (wParam > 0 && wParam < 0x10000)
443             io.AddInputCharacterUTF16((unsigned short)wParam);
444         return 0;
445     case WM_SETCURSOR:
446         if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor())
447             return 1;
448         return 0;
449     case WM_DEVICECHANGE:
450         if ((UINT)wParam == DBT_DEVNODES_CHANGED)
451             bd->WantUpdateHasGamepad = true;
452         return 0;
453     }
454     return 0;
455 }
456 
457 
458 //--------------------------------------------------------------------------------------------------------
459 // DPI-related helpers (optional)
460 //--------------------------------------------------------------------------------------------------------
461 // - Use to enable DPI awareness without having to create an application manifest.
462 // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
463 // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
464 //   but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
465 //   neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
466 //---------------------------------------------------------------------------------------------------------
467 // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
468 // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
469 // If you are trying to implement your own backend for your own engine, you may ignore that noise.
470 //---------------------------------------------------------------------------------------------------------
471 
472 // Perform our own check with RtlVerifyVersionInfo() instead of using functions from <VersionHelpers.h> as they
473 // require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200
_IsWindowsVersionOrGreater(WORD major,WORD minor,WORD)474 static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD)
475 {
476     typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG);
477     static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = NULL;
478 	if (RtlVerifyVersionInfoFn == NULL)
479 		if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll"))
480 			RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo");
481     if (RtlVerifyVersionInfoFn == NULL)
482         return FALSE;
483 
484     RTL_OSVERSIONINFOEXW versionInfo = { };
485     ULONGLONG conditionMask = 0;
486     versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
487     versionInfo.dwMajorVersion = major;
488 	versionInfo.dwMinorVersion = minor;
489 	VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
490 	VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
491 	return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE;
492 }
493 
494 #define _IsWindowsVistaOrGreater()   _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA
495 #define _IsWindows8OrGreater()       _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8
496 #define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE
497 #define _IsWindows10OrGreater()      _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10
498 
499 #ifndef DPI_ENUMS_DECLARED
500 typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
501 typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
502 #endif
503 #ifndef _DPI_AWARENESS_CONTEXTS_
504 DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
505 #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE    (DPI_AWARENESS_CONTEXT)-3
506 #endif
507 #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
508 #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
509 #endif
510 typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS);                     // Shcore.lib + dll, Windows 8.1+
511 typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*);        // Shcore.lib + dll, Windows 8.1+
512 typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
513 
514 // Helper function to enable DPI awareness without setting up a manifest
ImGui_ImplWin32_EnableDpiAwareness()515 void ImGui_ImplWin32_EnableDpiAwareness()
516 {
517     if (_IsWindows10OrGreater())
518     {
519         static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
520         if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
521         {
522             SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
523             return;
524         }
525     }
526     if (_IsWindows8Point1OrGreater())
527     {
528         static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
529         if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
530         {
531             SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
532             return;
533         }
534     }
535 #if _WIN32_WINNT >= 0x0600
536     ::SetProcessDPIAware();
537 #endif
538 }
539 
540 #if defined(_MSC_VER) && !defined(NOGDI)
541 #pragma comment(lib, "gdi32")   // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32'
542 #endif
543 
ImGui_ImplWin32_GetDpiScaleForMonitor(void * monitor)544 float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
545 {
546     UINT xdpi = 96, ydpi = 96;
547     if (_IsWindows8Point1OrGreater())
548     {
549 		static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
550 		static PFN_GetDpiForMonitor GetDpiForMonitorFn = NULL;
551 		if (GetDpiForMonitorFn == NULL && shcore_dll != NULL)
552             GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor");
553 		if (GetDpiForMonitorFn != NULL)
554 		{
555 			GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
556             IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
557 			return xdpi / 96.0f;
558 		}
559     }
560 #ifndef NOGDI
561     const HDC dc = ::GetDC(NULL);
562     xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
563     ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
564     IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
565     ::ReleaseDC(NULL, dc);
566 #endif
567     return xdpi / 96.0f;
568 }
569 
ImGui_ImplWin32_GetDpiScaleForHwnd(void * hwnd)570 float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
571 {
572     HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
573     return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
574 }
575 
576 //---------------------------------------------------------------------------------------------------------
577 // Transparency related helpers (optional)
578 //--------------------------------------------------------------------------------------------------------
579 
580 #if defined(_MSC_VER)
581 #pragma comment(lib, "dwmapi")  // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi'
582 #endif
583 
584 // [experimental]
585 // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c
586 // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW)
ImGui_ImplWin32_EnableAlphaCompositing(void * hwnd)587 void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd)
588 {
589     if (!_IsWindowsVistaOrGreater())
590         return;
591 
592     BOOL composition;
593     if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition)
594         return;
595 
596     BOOL opaque;
597     DWORD color;
598     if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque))
599     {
600         HRGN region = ::CreateRectRgn(0, 0, -1, -1);
601         DWM_BLURBEHIND bb = {};
602         bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
603         bb.hRgnBlur = region;
604         bb.fEnable = TRUE;
605         ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
606         ::DeleteObject(region);
607     }
608     else
609     {
610         DWM_BLURBEHIND bb = {};
611         bb.dwFlags = DWM_BB_ENABLE;
612         ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
613     }
614 }
615 
616 //---------------------------------------------------------------------------------------------------------
617