@@ -22,6 +22,8 @@ UCHAR CMessageLoopHook::m_LastScanCode = NULL;
2222BYTE* CMessageLoopHook::m_LastKeyboardState = new BYTE[256 ];
2323bool ms_bIgnoreNextEscapeCharacter = false ;
2424
25+ #define WM_CUSTOMFOCUS_FIX WM_APP + 1
26+
2527CMessageLoopHook::CMessageLoopHook ()
2628{
2729 WriteDebugEvent (" CMessageLoopHook::CMessageLoopHook" );
@@ -132,6 +134,17 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w
132134 if (pModManager && pModManager->IsLoaded ())
133135 {
134136 bool bFocus = (wState == WA_CLICKACTIVE) || (wState == WA_ACTIVE);
137+
138+ // Fix for the Windows behavior that removes focus from a window if it was minimized during startup
139+ // (you have to double-click the icon or alt+tab to regain focus despite the window being visible).
140+ // GitHub issue #4233
141+ static bool fixFirstTimeFocus = false ;
142+ if (!fixFirstTimeFocus && !bFocus && GetForegroundWindow () != hwnd && GetFocus () == hwnd && !IsIconic (hwnd))
143+ {
144+ fixFirstTimeFocus = true ;
145+ PostMessage (hwnd, WM_CUSTOMFOCUS_FIX, 0 , 0 );
146+ }
147+
135148 pModManager->GetClient ()->OnWindowFocusChange (bFocus);
136149 }
137150
@@ -150,6 +163,30 @@ LRESULT CALLBACK CMessageLoopHook::ProcessMessage(HWND hwnd, UINT uMsg, WPARAM w
150163 }
151164 }
152165
166+ // When updating m_bFocused in CClientGame from CPacketHandler (to fix another bug — see the note there),
167+ // the window might not actually have focus at that moment (even though Windows reports it as focused).
168+ // In this case, isMTAWindowFocused returns false even though the window has focus.
169+ // Therefore, we need to intercept the window return operation and manually set the focus in CClientGame.
170+ if (uMsg == WM_WINDOWPOSCHANGING)
171+ {
172+ WINDOWPOS* wp = reinterpret_cast <WINDOWPOS*>(lParam);
173+ if (wp->flags & SWP_NOMOVE && wp->flags & SWP_NOSIZE && !(wp->flags & SWP_NOZORDER))
174+ {
175+ if (GetForegroundWindow () == hwnd && !IsIconic (hwnd))
176+ {
177+ CModManager* pModManager = CModManager::GetSingletonPtr ();
178+ if (pModManager && pModManager->IsLoaded ())
179+ pModManager->GetClient ()->OnWindowFocusChange (true );
180+ }
181+ }
182+ }
183+
184+ if (uMsg == WM_CUSTOMFOCUS_FIX)
185+ {
186+ AllowSetForegroundWindow (ASFW_ANY);
187+ SetForegroundWindow (hwnd);
188+ }
189+
153190 if (uMsg == WM_PAINT)
154191 {
155192 GetVideoModeManager ()->OnPaint ();
0 commit comments