212

Are there any solutions to prevent applications stealing focus from the active window?

This is especially annoying when I'm starting an application, switch to do something else and the new application starts receiving half a sentence of text.

Dave
  • 25,297
  • 10
  • 57
  • 69
svandragt
  • 3,243
  • 4
  • 24
  • 28
  • Vista or XP? Since Vista has some known issues with workarounds – Ivo Flipse Aug 05 '09 at 09:14
  • 9
    @Ivo Windows 7 in my case but I think for SuperUser all windows versions would be relevant – svandragt Aug 05 '09 at 09:48
  • XP has a known solution, and a question http://superuser.com/questions/138648/how-to-disable-auto-focus-of-opened-windows-apps so maybe this question should be for Windows 7 only? – endolith Feb 20 '11 at 01:02
  • 3
    The moderator merged this question: http://superuser.com/questions/199821/windows-7-disable-applications-stealing-focus with the current one. This is wrong, the answer to the current question does not apply to windows 7, so it shouldnt be merged. So far I could not find a solution to this problem in Windows 7 – Alex Angelico Oct 13 '11 at 13:38
  • @AlejandroAngelico: Since all the answers here are for Windows-XP, the questions should be split and the question re-tagged – endolith Mar 21 '12 at 19:47
  • @sathya... as a reference [this forum](http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_programs/applications-stealing-focus-reg-key-no-longer/4ee5be7d-31ef-493b-b092-f6f6139f99cd) states that there is no way. However I was unable to locate the blog post mentioned there. – James Mertz Mar 27 '12 at 03:51
  • 21
    This is one of my number one pet peeves with every GUI I have ever used. You're typing and blam, some bleeping dialog box steals focus and half your keystrokes go somewhere else. You'd think that the implementors of windowing systems would have figured out this one out decades ago. If there is activity in a window, delay the exposure of the new window. E.g. don't pop anything up on the GUI until three or four seconds since the last button click or keystroke in the currently focused window. Doh! – Kaz Mar 27 '12 at 22:15
  • 1
    i found when I have my my external hard drive (made by Seagate) or my ipod nano (ahem, apple) connected to my Windows 7 machine, it would appear the "desktop" would steal focus every 30 seconds or so, from what ever i was browsing, be it itunes music, Chrome search results or firefox emails. I turned off the autoplay feature, and that helped for a while, but the problem came back even after autoplay was disabled. I guess i have to keep my external HD and flash drives disconnected for the most part, which sucks cuz thats where all my music is :( Its a really annoying bug that makes me want to S –  Apr 28 '12 at 17:37
  • Also see really lengthy discussion about this issue [here](http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_programs/applications-stealing-focus-reg-key-no-longer/4ee5be7d-31ef-493b-b092-f6f6139f99cd). – Karan Mar 07 '13 at 03:24
  • 32
    `This is especially annoying when I'm starting an application, switch to do something else and the new application starts receiving half a sentence of text.` It’s even more annoying when a dialog pops up and you unintentionally dismiss it without even seeing the message because you happened to press `Space` or `Enter` while typing a sentence. – Synetech Jan 01 '14 at 16:17
  • The Java installer is an example. I can be typing into my IM window whilst the Java installer is running, and suddenly my keyboard focus is whisked away as Java's command-line opens the command prompt box. Other installers do this too, they can't just run in the background (yes, I know, they always say "close all other windows first" - but there's no reason to do that - I believe this requirement is a relic of XP or earlier). – bgmCoder Aug 08 '16 at 15:22
  • 7
    This is actually way more than annoying, I'd say that it's a security risk. There's nothing to stop an application popping up when you're in the middle of typing a password and grabbing your input. – Chris Peacock Nov 25 '16 at 16:55
  • 1
    @Synetech - yes, especially if it's a "Restart Windows now to apply updates" prompt, which then happens without confirmation and with no opportunity to cancel. – Chris Peacock Nov 25 '16 at 16:58
  • 1
    For the record, this stealing-focus nonsense started sometime around Windows 9x for me. I recall that back in Windows 3.x this never happened. A program would "blink" showing that some activity happened in it and requires your attention, but it would never steal the windows focus. – pmdci Jan 17 '19 at 14:36
  • In Windows 7, if you know the name of the offending (focus-stealing) application, does that make it any easier to prevent it from stealing focus? – RockPaperLz- Mask it or Casket Apr 10 '19 at 02:36
  • The worst are file copies - long ones. Nothing worse than being three hours into a long copy operation only to have the dialog steal focus to tell you there's a conflict - just long enough for you to see it disappear as you were typing, doing who knows what (overwriting files you didn't want, making copies you didn't want, or just cancelling and forcing you to start the whole thing over again). If there's a solution **just** for the file copy dialog I'd take it. Give me a notification - I'll deal with it. Don't steal focus!! – J... Apr 22 '21 at 17:58

7 Answers7

55

This is not possible without extensive manipulation of Windows internals and you need to get over it.

There are moments in daily computer use when it is really important that you make one action before the operating system allows you to do another. To do that, it needs to lock your focus on certain windows. In Windows, control over this behavior is largely left to the developers of the individual programs that you use.

Not every developer makes the right decisions when it comes to this topic.

I know that this is very frustrating and annoying, but you can't have your cake and eat it too. There are probably many cases throughout your daily life where you're perfectly fine with the focus being moved to a certain UI element or an application requesting that the focus remains locked on it. But most applications are somewhat equal when it comes to deciding who is the lead right now and the system can never be perfect.

A while ago I did extensive research on solving this issue once and for all (and failed). The result of my research can be found on the annoyance project page.

The project also includes an application that repeatedly tries to grab focus by calling:

switch( message ) {
  case WM_TIMER:
    if( hWnd != NULL ) {
      // Start off easy
      // SetForegroundWindow will not move the window to the foreground,
      // but it will invoke FlashWindow internally and, thus, show the
      // taskbar.
      SetForegroundWindow( hWnd );

      // Our application is awesome! It must have your focus!
      SetActiveWindow( hWnd );

      // Flash that button!
      FlashWindow( hWnd, TRUE );
    }
    break;

As we can see from this snippet, my research was also focused on other aspects of user interface behavior I don't like.

The way I tried to solve this was to load a DLL into every new process and hook the API calls that cause another windows to be activated.
The last part is the easy one, thanks to awesome API hooking libraries out there. I used the very great mhook library:

#include "stdafx.h"
#include "mhook-2.2/mhook-lib/mhook.h"

typedef NTSTATUS( WINAPI* PNT_QUERY_SYSTEM_INFORMATION ) ( 
  __in       SYSTEM_INFORMATION_CLASS SystemInformationClass,     
  __inout    PVOID SystemInformation, 
  __in       ULONG SystemInformationLength, 
  __out_opt  PULONG ReturnLength    
);

// Originals
PNT_QUERY_SYSTEM_INFORMATION OriginalFlashWindow   = 
  (PNT_QUERY_SYSTEM_INFORMATION)::GetProcAddress( 
  ::GetModuleHandle( L"user32" ), "FlashWindow" );

PNT_QUERY_SYSTEM_INFORMATION OriginalFlashWindowEx = 
  (PNT_QUERY_SYSTEM_INFORMATION)::GetProcAddress( 
  ::GetModuleHandle( L"user32" ), "FlashWindowEx" );

PNT_QUERY_SYSTEM_INFORMATION OriginalSetForegroundWindow = 
  (PNT_QUERY_SYSTEM_INFORMATION)::GetProcAddress( 
  ::GetModuleHandle( L"user32" ), "SetForegroundWindow" );

// Hooks
BOOL WINAPI
HookedFlashWindow(
  __in  HWND hWnd,
  __in  BOOL bInvert
  ) {
  return 0;
}

BOOL WINAPI 
HookedFlashWindowEx(
  __in  PFLASHWINFO pfwi
  ) {
  return 0;
}

BOOL WINAPI 
HookedSetForegroundWindow(
  __in  HWND hWnd
  ) {
  // Pretend window was brought to foreground
  return 1;
}


BOOL APIENTRY 
DllMain( 
  HMODULE hModule,
  DWORD   ul_reason_for_call,
  LPVOID  lpReserved
  ) {
  switch( ul_reason_for_call ) {
    case DLL_PROCESS_ATTACH:
      Mhook_SetHook( (PVOID*)&OriginalFlashWindow,         HookedFlashWindow );
      Mhook_SetHook( (PVOID*)&OriginalFlashWindowEx,       HookedFlashWindowEx );
      Mhook_SetHook( (PVOID*)&OriginalSetForegroundWindow, HookedSetForegroundWindow );
      break;

    case DLL_PROCESS_DETACH:
      Mhook_Unhook( (PVOID*)&OriginalFlashWindow );
      Mhook_Unhook( (PVOID*)&OriginalFlashWindowEx );
      Mhook_Unhook( (PVOID*)&OriginalSetForegroundWindow );
      break;
  }
  return TRUE;
}

From my tests back then, this worked great. Except for the part of loading the DLL into every new process. As one might imagine, that's nothing to take too lightly. I used the AppInit_DLLs approach back then (which is simply not sufficient).

Basically, this works great. But I never found the time to write something that properly injects my DLL into new processes. And the time invested in this largely overshadows the annoyance the focus stealing causes me.

In addition to the DLL injection problem, there is also a focus-stealing method which I didn't cover in the implementation on Google Code. A co-worker actually did some additional research and covered that method. The problem was discussed on SO: https://stackoverflow.com/questions/7430864/windows-7-prevent-application-from-losing-focus

Oliver Salzburg
  • 86,445
  • 63
  • 260
  • 306
  • Do you think this solution of yours could be ported to Java? I've been searching and asking questions but found nothing. Maybe I could import the hook library itself in java using `jne`? – Tomáš Zato Mar 04 '15 at 15:04
  • @TomášZato: No idea. I'm not actively using this code myself. – Oliver Salzburg Mar 04 '15 at 15:53
  • I'm trying to compile it as C++ at least (and then inject/remove the compiled DLL from Java). But that doesn't go too well either. I don't want to discuss it here in comments, but if you could actually help me with getting it to work, I'd be very graceful! I created a chat room, if I get that to work I'll post comment how to do so here: http://chat.stackexchange.com/rooms/21637/preventing-applications-from-stealing-focus-using-mhook – Tomáš Zato Mar 04 '15 at 15:56
24

In Windows 7, the ForegroundLockTimeout registry entry is no longer checked, you can verify this with Process Monitor. In fact, in Windows 7 they disallow you from changing the foreground window. Go and read about its details, it has even been there since Windows 2000.

However, the documentation sucks and they chase each other and find ways around that.

So, there is something buggy going on with SetForegroundWindow, or similar API functions...

The only way to really do this properly is to make a small application which periodically calls LockSetForegroundWindow, virtually disabling any calls to our buggy API function.

If that's not enough (another buggy API call?) you can go even further and do some API monitoring to see what's going on, and then you simply hook the API calls on every process after which you can get rid of any calls that mess up the foreground. However, ironically, this is discouraged by Microsoft...

Tamara Wijsman
  • 57,083
  • 27
  • 185
  • 256
  • I'll try to write an application that periodically calls `LockSetForegroundWindow`, this Friday / Weekend. Given that there are already fixes that work for Windows XP and 7, I don't expect anything to work for Windows 7 in a generic way... – Tamara Wijsman Mar 22 '12 at 09:53
  • Hey Tom, maybe this old project of mine will give you a head start :) http://code.google.com/p/annoyance/ – Oliver Salzburg Mar 24 '12 at 09:26
  • @OliverSalzburg: I know of that. Last line in my post... ^^ – Tamara Wijsman Mar 24 '12 at 09:41
  • 3
    **Does anyone have a reproducible use case of this in Windows 7?** Given that people rather experience the opposite (for example, I often find demanding Windows to be hidden behind my current window) and that I am yet to see this happen in Windows 7, it would be pretty annoying to write an application but being unable to test it. Furthermore, as Microsoft states this should no longer happen with Windows 7. At best people discovered that it could only switch the keyboard's focus by accident, this API call would fix that but I don't know how to test whether it actually works... – Tamara Wijsman Mar 24 '12 at 10:47
  • I have a similar issue which annoys the hell out of me. A rather complex installer that calls other programs during installation (e.g. some service initialization). Typing in another program/window during that last part of the installation is impossible. It's reproducible every time, unfortunately I cannot share the offending application. I'd be willing to test your workaround though. – Daniel Beck Mar 26 '12 at 14:20
  • @DanielBeck: Hmm, what kind of windows pop up? It would be very interesting to see whether console windows or the *Windows Installer* itself would offend their own rules. Also, it could be that new applications could work around the rule. But would love to know if its something generic that pops up rather than their own installer, as that would be somewhat easy to reproduce... – Tamara Wijsman Mar 26 '12 at 14:35
  • 1
    The installer (based on InnoSetup) launches other processes and possible other (hidden) setups, but I don't know what setup creator they're based on. – Daniel Beck Mar 26 '12 at 15:00
  • 7
    @TomWijsman: Open regedit, search for some random text that won't be found. Go into another app and start typing. When the search is finished, regedit will steal focus. – endolith Jun 06 '12 at 18:06
  • 1
    @endolith: Not reproducible, using Windows 8 Replase Preview here though. What OS are you using? In my case it just highlights the application at the bottom but doesn't interrupt my browsing at all... – Tamara Wijsman Jun 06 '12 at 19:31
  • Also not producible on Windows 7 ([confirmed by Sathya](http://chat.stackexchange.com/transcript/message/4857861#4857861)). – Tamara Wijsman Jun 06 '12 at 19:46
  • 1
    @endolith I was able to reproduce it on Windows 7 (64-bit). See: http://chat.stackexchange.com/transcript/message/4858025#4858025 – iglvzx Jun 06 '12 at 19:57
  • 1
    @endolith: I think elevated process can (on Windows 7 at least), although Sathya couldn't. It kind of makes sense for administrator stuff to be able to do this... – Tamara Wijsman Jun 06 '12 at 19:59
  • 25
    Yes, Win7 Pro 64-bit. And focus stealing is even worse for elevated processes, since they capture your pressing when they shouldn't, and you tell it to hose your system accidentally. Nothing should *ever* be able to steal focus. – endolith Jun 06 '12 at 20:59
  • 1
    @Tom: It happens to me regularly (even now writing this comment). I have Windows 7 32 bit. In background there is application running which periodically creates child process through calling CreateProcess. This child process goes into foreground and steals keyboard focus. But not always, lets say in 50% of cases. The application mentioned is being developed by me and my colleagues. I have not tried to reproduce focus stealing by writing small demo application but have seen this problem tens maybe hundreds of times. – truthseeker Aug 08 '13 at 12:01
  • Copy something in Windows Explorer (between drives, 1GB, takes 2-3 minutes). When it's done copying, it steals focus. Windows 7 Home Basic 64-bit – LGT Mar 12 '17 at 16:18
  • The problem with this ForegroundLockTimeout registry entry is that if you set it so as to not allow stealing windows focus it causes you problems in switching naturally between applications. It's hard to reproduce the bug but basically sometime between your work when you switch to an application that had been waiting for your attention for a long time then you're not allowed to switch back to the original application via taskbar. One of your apps can get permanently locked into the taskbar. I would actually buy a Windows 11 if it had just this 1 feature. – Mugen Dec 03 '20 at 04:57
18

There is an option in TweakUI which does this. It prevents most of the usual tricks dubious software developers employ to force focus on their app.

It's an ongoing arms war though, so I don't know if it works for everything.

Update: According to EndangeredMassa, TweakUI does not work on Windows 7.

Simon P Stevens
  • 5,183
  • 1
  • 28
  • 36
16

I believe that some confusion may exist, as there are two ways of "stealing focus" : (1) a window coming to the foreground, and (2) the window receiving keystrokes.

The problem referred to here is probably the second one, where a windows claims the focus by bringing itself to the foreground - without the user's request or permission.

The discussion must split here between XP and 7.

Windows XP

In XP there is a registry hack that makes XP work the same as Windows 7 in preventing applications from stealing focus :

  1. Use regedit to go to: HKEY_CURRENT_USER\Control Panel\Desktop.
  2. Double-click on ForegroundLockTimeout and set its value in hexadecimal to 30d40.
  3. Press OK and exit regedit.
  4. Reboot your PC for the changes to take effect.

Windows 7

(The discussion below mostly applies to XP as well.)

Please understand that there is no way in which Windows can totally block applications from stealing the focus and remain functional. For example, if during a file-copy your anti-virus detected a possible threat and would like to pop-up a window asking you for the action to take, if this window is blocked then you would never understand why the copy never terminates.

In Windows 7 there is only one modification possible to the behavior of Windows itself, which is to use the MS-Windows focus-follows-mouse Registry hacks, where the focus and/or activation goes always to the windows under the cursor. A delay can be added to avoid applications popping up all over the desktop.
See this article : Windows 7 - Mouse Hover Makes Window Active - Enable.

Otherwise, one must detect and neutralize the guilty program : If this is always the same application that is getting the focus, then this application is programmed to take the focus and preventing this may be done by either disabling it from starting with the computer, or use some setting supplied by that application to avoid this behavior.

You could use the VBS script included in VB Code which identifies who's stealing focus, which the author used to identify the culprit as a "call home" updater for a printer software.

A desperate measure when all else fails, and if you have identified this badly-programmed application, is to minimize it and hope that will not then bring itself to the front. A stronger form of minimization is to the tray by using one of the free products listed in Best Free Application Minimizer.

Last idea in the order of desperation is to fracture your desktop virtually by using a product such as Desktops or Dexpot, and do your work in another desktop than the default.

[EDIT]

As Microsoft has retired the Archive Gallery, here is the above VB code reproduced :

Declare Auto Function GetForegroundWindow Lib "user32.dll" () As Integer
Declare Auto Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As Integer, ByRef procid As Integer) As UInteger
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.RichTextBox1.AppendText("Starting up at " & Now & vbCrLf)
    End Sub
 
    Private Sub GoingAway(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Deactivate, Me.LostFocus
 
        Dim hwnd As Integer = GetForegroundWindow()
        ' Note that process_id will be used as a ByRef argument
        ' and will be changed by GetWindowThreadProcessId
        Dim process_id As Integer = 1
        GetWindowThreadProcessId(hwnd, process_id)
 
        If (process_id <> 1) Then
            Dim appExePath As String = Process.GetProcessById(process_id).MainModule.FileName() 
            Me.RichTextBox1.AppendText("Lost focus at " & Now & " due to " & appExePath & vbCrLf)
        Else
            Me.RichTextBox1.AppendText("Lost focus due to unknown cause.")
        End If
 
    End Sub
harrymc
  • 455,459
  • 31
  • 526
  • 924
  • 53
    "if this window is blocked then you would never understand why the copy never terminates" That's not true. The correct behavior is to notify the user with a blinking task bar icon (or maybe a balloon pop-up or toaster notification or something). Interrupting the user with a window that intercepts their keystrokes means that they tell the antivirus software to take one action or another at random. Definitely not a good way to do things. – endolith Jun 09 '12 at 12:10
  • Unfortunately, Windows doesn't do that methodically in all cases. So one has to resort to workarounds or third-party products. – harrymc Jun 09 '12 at 12:12
  • 1
    *"if this window is blocked then you would never understand why the copy never terminates" That's not true. The correct behavior is to notify the user with a blinking task bar icon...*   There have been times when I clicked a button or something in a running program that causes a new modal dialog to be created (e.g., *open file*), but then I switch to another program before the dialog is created. As a result, the dialog is hidden and the other program can not be switched to and the dialog cannot be dismissed. Neither its taskbar button nor `Alt-Tab` works; only forcing the dialog to the front. – Synetech Jun 12 '12 at 04:46
  • 1
    @Synetech: Sometimes the only solution to the non-front dialog is to kill the task. The focus algorithms in Windows are really lousy. – harrymc Jun 12 '12 at 06:21
  • 2
    @harrymc, I never have to resort to killing one of the apps. I just run my window-manipulating program ([WinSpy++](http://www.catch22.net/software/winspy-17) does the trick just great) and hide the window in front, then I can dismiss the stuck-back dialog, then re-show the hidden window. It's not convenient, but it's better than killing either of the processes. – Synetech Jun 12 '12 at 15:06
  • @Synetech: It does let off some steam ... In all fairness, repeating Alt-Tab a few times is normally enough to correct the problem. – harrymc Jun 12 '12 at 17:38
  • 1
    @harrymc, not really; killing an app and losing stuff just makes more steam, and if it is a modal dialog (that locks the parent window and has no taskbar button), then it won't appear in the `Alt+Tab` list, and, in my experience, a window that has a modal dialog open does not always (never?) show the modal dialog with `Alt+Tab`, especially if the dialog never had a change to get focus. `:-|` – Synetech Jun 12 '12 at 18:31
  • Does the VB code still exist somewhere? The link seems to be broken – Superole May 27 '14 at 14:42
  • @Superole: I added the code to the answer. – harrymc May 27 '14 at 14:56
  • @harrymc: great :) now if I could just figure out how to use it... I tried compiling it with vbc, but it says 'Sub Main' was not found. – Superole Jun 02 '14 at 11:28
  • @Superole: You could also use other products, such as the AutoHotKey utility of Windows Spy. Or use C# with [this program](http://adrianswall.com/?p=193). – harrymc Jun 02 '14 at 11:49
  • Is there a way to abuse the focus-follows-mouse thing, with like a second virtual invisible mouse cursor that follows where focus is currently? – endolith Jan 23 '15 at 14:40
  • @endolith: AFAIK it's very hard to have 2 cursors on Windows. I really suggest looking for another solution to your problem, maybe in a new post. – harrymc Jan 23 '15 at 17:23
  • It would be closed as a duplicate of this post – endolith Jan 23 '15 at 18:15
  • @endolith: I meant rather the basic problem that motivated your solution of 2 cursors. It might have another solution than 2 cursors. – harrymc Jan 23 '15 at 18:18
  • I don't understand. The problem is windows popping up and stealing focus. You suggested focus follows mouse as a solution, but this requires you to manually hover your mouse over the window you are using at all times. I'm wondering if that can be automated as a workaround for this Windows bug. – endolith Jan 23 '15 at 18:33
  • @endolith: Perhaps using AutoHotKey or similar. – harrymc Jan 23 '15 at 19:43
5

Inspired by Der Hochstapler's answer, I decided to write a DLL injector, that works with both 64 and 32-bit processes and prevents focus stealing on Windows 7 or newer: https://blade.sk/stay-focused/

The way it works is it watches for newly created windows (using SetWinEventHook) and injects DLL very similar to Der Hochstapler's one into the window's process if not present already. It unloads the DLLs and restores the original functionality on exit.

From my testing, it works very well so far. However, the issue seems to go deeper than just apps calling SetForegroundWindow. For instance when a new window is created, it's automatically brought into foreground, which also interferes with a user typing into another window.

To deal with other methods of focus stealing, more testing is required and I'd appreciate any feedback on scenarios where it's happening.

edit: Source code now available.

blade
  • 346
  • 4
  • 5
  • I tried the app. It seems it needs to be started as admin, otherwise, it'll crash. ViveProSettings.exe caused it to crash for me too so I killed that processed. Once I've worked through these perhaps it's indeed working (haven't seen focus stealing since!) though I couldn't counter-test it by closing it since it crashed on exit too :). I'm not complaining, thank you for your work! I'd just like to figure out how to make it usable. I've e-mailed you with details. – Piedone Mar 24 '20 at 14:24
3

Ghacks has a possible solution:

It happens several times a day that some applications steal the focus of the active window by popping up. This can happen for a number of reasons, when I extract files or a transfer finishes for instance. It does not matter most of the time when this happens but sometimes I’m writing an article and it does not only mean that I have to type some words again but also that I lost concentration and have to click to regain focus.

The Pro Reviewer website has a tip on how to prevent this from happening. The easiest way of preventing focus stealing is to use Tweak UI which has a setting that is called “Prevent applications from stealing focus”. Checking this option prevents that other applications pop up suddenly and steal the focus of the window you are currently working in.

This only works when the application has been minimized before. Instead of stealing the focus it will flash a number of times which can be defined in the same menu in Tweak UI. If you do not want to use Tweak UI you can change the setting in the Windows Registry.

Navigate to the Registry key HKEY_CURRENT_USER > Control Panel > Desktop and change the ForegroundLockTimeout value to 30d40 (Hexadecimal) or 200000 (Decimal). The key ForeGroundFlashCount defines the amount of flashes of a window to alert the user where 0 means unlimited.

Ivo Flipse
  • 24,696
  • 32
  • 103
  • 147
  • 21
    This doesn't work on any OS after XP. That registry value is already set to that (by default, I believe) and doesn't work anyway. – EndangeredMassa Oct 15 '10 at 19:18
  • 1
    Just to second that I'm on Windows 7 (64-bit), experiencing focus-stealing (VS 2012 when finally active, f'r example), and the above registry-suggestion is already in-place. Technical confirmation in this answer: http://superuser.com/a/403554/972 – Michael Paulukonis Feb 24 '14 at 16:03
0

I figured out how to stop the TaskBar from flashing a newly activated target window after you programmatically activate, maximize, and focus the main window of that process from another process. First of all, there are a lot of restrictions on whether this operation will be allowed.

"The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-allowsetforegroundwindow

So if the controlling process is in the foreground, it can temporarily enable another process to fully steal the foreground by calling AllowSetForegroundWindow with the process id of the target process. Then after that, the target process can call SetForegroundWindow itself, using its own window handle, and it will work.

Obviously, this requires some coordination between the two processes, but it does work, and if you're doing this in order to implement a single-instance app which redirects all Explorer-click launches into the existing app instance, then you'll already have an (e.g.) named pipe to coordinate things anyway.

Glenn Slayden
  • 1,465
  • 12
  • 20