SDL: Fixed trying to grab the mouse when losing keyboard focus (4fc54)

From 4fc5405f16295c55067293fa3aff13104c55d39e Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 28 Oct 2025 07:15:43 -0700
Subject: [PATCH] Fixed trying to grab the mouse when losing keyboard focus

Fixes https://github.com/libsdl-org/SDL/issues/14350

(cherry picked from commit 2d14a237dc6659006a15747d8c87e72430574bba)
---
 src/events/SDL_keyboard.c     | 24 ++++++++++++------------
 src/events/SDL_windowevents.c |  7 ++++---
 2 files changed, 16 insertions(+), 15 deletions(-)

diff --git a/src/events/SDL_keyboard.c b/src/events/SDL_keyboard.c
index 7f1ac7aaa11a8..05e3f6edd3fb3 100644
--- a/src/events/SDL_keyboard.c
+++ b/src/events/SDL_keyboard.c
@@ -333,6 +333,18 @@ bool SDL_SetKeyboardFocus(SDL_Window *window)
         }
     }
 
+    // See if the current window has lost focus
+    if (keyboard->focus && keyboard->focus != window) {
+        SDL_SendWindowEvent(keyboard->focus, SDL_EVENT_WINDOW_FOCUS_LOST, 0, 0);
+
+        // Ensures IME compositions are committed
+        if (SDL_TextInputActive(keyboard->focus)) {
+            if (video && video->StopTextInput) {
+                video->StopTextInput(video, keyboard->focus);
+            }
+        }
+    }
+
     if (keyboard->focus && !window) {
         // We won't get anymore keyboard messages, so reset keyboard state
         SDL_ResetKeyboard();
@@ -351,18 +363,6 @@ bool SDL_SetKeyboardFocus(SDL_Window *window)
         }
     }
 
-    // See if the current window has lost focus
-    if (keyboard->focus && keyboard->focus != window) {
-        SDL_SendWindowEvent(keyboard->focus, SDL_EVENT_WINDOW_FOCUS_LOST, 0, 0);
-
-        // Ensures IME compositions are committed
-        if (SDL_TextInputActive(keyboard->focus)) {
-            if (video && video->StopTextInput) {
-                video->StopTextInput(video, keyboard->focus);
-            }
-        }
-    }
-
     keyboard->focus = window;
 
     if (keyboard->focus) {
diff --git a/src/events/SDL_windowevents.c b/src/events/SDL_windowevents.c
index e20cd3ab0da7a..ab847ed67fb6a 100644
--- a/src/events/SDL_windowevents.c
+++ b/src/events/SDL_windowevents.c
@@ -77,9 +77,6 @@ bool SDL_SendWindowEvent(SDL_Window *window, SDL_EventType windowevent, int data
     }
     SDL_assert(SDL_ObjectValid(window, SDL_OBJECT_TYPE_WINDOW));
 
-    if (window->is_destroying && windowevent != SDL_EVENT_WINDOW_DESTROYED) {
-        return false;
-    }
     switch (windowevent) {
     case SDL_EVENT_WINDOW_SHOWN:
         if (!(window->flags & SDL_WINDOW_HIDDEN)) {
@@ -212,6 +209,10 @@ bool SDL_SendWindowEvent(SDL_Window *window, SDL_EventType windowevent, int data
         break;
     }
 
+    if (window->is_destroying && windowevent != SDL_EVENT_WINDOW_DESTROYED) {
+        return false;
+    }
+
     // Post the event, if desired
     SDL_Event event;
     event.type = windowevent;