Active window (program) unexpectedly loses focus in Windows 7
Solution 1
As and31415 advised me, I took a careful look at what is in my Startup
tab of msconfig
program, but found nothing unusual.
It is now clear that this is 99% caused by some external program (though not noticed before and though I haven't installed anything new recently), not by Windows. This is the most important point for me here.
I googled a little bit more and got some ideas / advice, namely that I should try to press Alt+F4 immediately after I notice a steal of a focus. This should exit process that could cause this focus stealth. Then, I may try to use Process Monitor
from Sysinternals
package to trace the process that has just exited.
This may give me some idea of what is causing this problem.
Solution 2
I programmed a C# program to monitor fluctuating processes. Here is the code if someone needs to find out what process is causing this problem.
using System;
using System.Diagnostics;
using System.Linq;
namespace ProcessMonitor
{
class Program
{
static void Main(string[] args)
{
var lastPros = Process.GetProcesses().Select((x) => x.Id).ToList();
var oldProcessList = Process.GetProcesses();
while (true)
{
var processlist = Process.GetProcesses();
var currentPros = processlist.Select(x => x.Id).ToList();
var diff = lastPros.Except(currentPros).ToList();
Console.ForegroundColor = ConsoleColor.Red;
var pro = oldProcessList.Where(x => diff.Contains(x.Id)).ToList();
if (diff.Count == 0)
{
pro = processlist.Where((x) => diff.Contains(x.Id)).ToList();
diff = currentPros.Except(lastPros).ToList();
Console.ForegroundColor = ConsoleColor.Green;
pro = processlist.Where((x) => diff.Contains(x.Id)).ToList();
}
foreach (var oldPid in diff)
{
Console.Write("PID {0}", oldPid);
try
{
Console.WriteLine(" name {0}", pro.Where((x) => x.Id == oldPid).ToList()[0].ProcessName);
}
catch (Exception e)
{
Console.WriteLine($" Hit exception {e}");
}
}
if (diff.Count > 0)
{
lastPros = currentPros;
oldProcessList = processlist;
}
System.Threading.Thread.Sleep(100);
}
}
}
}
Output sample showing process starting (green) and terminating (red)
Solution 3
The focus is probably stolen by a buggy background task. It opens a window, which steals focus, and it is very quickly closed, but the focus does not return. Lately, Microsoft Office had such a bug.
To discover such processes, you can use tools like Window Focus Logger (mirror) or a custom C# program similar to Process Monitor:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ProcessMonitor
{
class Program
{
const int pollDelay = 100;
static void Main(string[] args)
{
var lastProcesses = GetDescriptions();
while (true)
{
System.Threading.Thread.Sleep(pollDelay);
var now = DateTime.Now;
var processes = GetDescriptions();
var started = processes.Except(lastProcesses);
var stopped = lastProcesses.Except(processes);
foreach (var p in started)
{
Print(now, p, ConsoleColor.Green);
}
foreach (var p in stopped)
{
Print(now, p, ConsoleColor.Red);
}
lastProcesses = processes;
}
}
static void Print(DateTime dateTime, ProcessDescription process,
ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine("{0:hh\\:mm\\:ss\\.ff}\tPID {1}\t{2}",
dateTime.TimeOfDay, process.Id, process.Description);
Console.ResetColor();
}
static List<ProcessDescription> GetDescriptions()
{
return Process.GetProcesses().Select(x => GetDescription(x)).ToList();
}
static ProcessDescription GetDescription(Process p)
{
int pid = -1;
string description;
try
{
pid = p.Id;
description = p.ProcessName;
}
catch (Exception e)
{
description = "Hit exception " + e;
}
return new ProcessDescription { Id = pid, Description = description };
}
struct ProcessDescription
{
public int Id;
public string Description;
public override bool Equals(object obj)
{
return obj != null && Id == ((ProcessDescription)obj).Id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
}
Polished and bugfixed version of the code provided by Omar Alshaker. Also does not require C# 6. Requires .NET 3.5 or newer.
You can compile it using the C# compiler (csc.exe
) that comes with your .NET Framework installation and run the resulting executable to get a real-time log of processes that start (green) or end (red). Use Ctrl + C to terminate it.
To find the compiler, run where /R %windir%\Microsoft.NET csc.exe
. Pick the one from the latest .NET version installed, no matter whether 32b or 64b. Save the C# code in Program.cs
and compile it to Program.exe
:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe Program.cs
Solution 4
In my case it was that wermgr.exe (Windows error reporting) started again and again. I followed the below solution to stop it from starting automatically, and that solved the problem.
- Start button -> In the search box type Action center -> Enter.
- Click on the arrow next to Maintenance to expand.
- Under Check for solutions to problem reports, click on Settings.
- Click on Change report settings for all users.
- Check the radio button next to Each time a problem occurs, ask me before checking for solution.
- OK your way out, by clicking OK.
Solution 5
The Hint with using Alt+F4
to exit the interrupting program worked well. Instead of tracing the just exited program with SysInternal
's ProcessManager
, I did traced the program as follows:
- Open
Task manager
- Take a screenshot of open processes
- Switch to Browser, Mail etc and "wait on focus loss"
- Press
Alt+F4
to exit the interrupting program - Go to
Task manager
and compare open processes with screenshot - The now "missing" process caused the problem
In my case it was twcu.exe
, a program that starts with TP-Link Configuration tool
. It is used by external WIFI-USB Sticks. As reported here (twcu.exe at file.net) and here (twcu.exe at computerbase.de [german]), TP-Link Configuration tool
is not needed for the WIFI connection itself. I removed it from Autostart (msconfig
> system start
), restarted the computer and it still connects to the WIFI flawless - and the focus loss problems are gone!
Related videos on Youtube
Thomas Baruchel
Updated on September 18, 2022Comments
-
Thomas Baruchel over 1 year
I am writing a code in Python by using the
sqlite3
module. Do I need to perform a commit between the two following queries:DELETE FROM xxx WHERE user="foobar"; INSERT INTO XXX ... ; -- new stuff about user "foobar"
What I want is deleting anything related to "foobar" before adding some (new) stuff, but I would like to be sure that order of both queries will be kept during the commit.
-
and31415 about 10 yearsDoes the problem happen in Safe Mode too (with or without networking) too? Start
msconfig
, and select the Startup tab. What programs are there? -
trejder about 10 yearsIt is very hard to "catch" described problem, because it does not happens too often. For example -- no trace for past two days. So I would have to work days in Safe Mode to try to "catch" this. But, thanks for the idea. Also, see my answer below.
-
-
and31415 about 10 yearsFrom
msconfig
, select the Services tab and enable the Hide all Microsoft services. Check that too. Here's an official KB article which can be useful: Perform a clean startup to determine whether background programs are interfering with your game or program. Also, even if you don't see anything unusual, I think it would be a good idea to list all third party startup items and services you got. -
trejder about 8 yearsGood idea and nice piece of code. But, since this is a site for users, not developers (this is Super User, not Stack Overflow), then you should add some explanation on how non-C#-developer is able to run your code?
-
Ryan over 7 years@trejder, did you need to download technet.microsoft.com/en-us/sysinternals/bb896645 or something else, or are you referring to a built-in feature of Windows that lets you look at a list of processes that recently exited? Thanks!
-
trejder over 7 years@Ryan Nope, as in answer --
Process Monitor
fromSysinternals
package. -
Daryl Van Sittert over 7 yearsWhen using
Process Monitor
, go to the Filter menu and add the following filter: Operation is notProcess Exit
then Exclude. My touchpad driver was throwing an error and trying to report it with Windows Problem Reporting. Thank %#!@ for these Q&A sites or else I would have destroyed my laptop. -
MickyD about 7 yearsI just had this happen to me. Turned out to be C:\Program Files (x86)\ViveSetup\PCClient\HTCVRMarketplaceUserContextHelper.exe - a program for the HTC Vive. I deleted the whole directory. I suspect it is a problem with their update earlier this week
-
Palec almost 7 yearsI created an improved version of this and put it in my own answer, including the answers to your questions, @trejder.
-
OmarL about 6 yearsThis code gives me the error "The type or namespace 'Process' could not be found". So I needed to add a reference to System.dll.
-
Palec about 6 yearsStrange, @Wilson. Which version of csc.exe are you using?
-
Palec about 6 yearsBy the way, the command line will be
csc.exe -reference:System.dll Program.cs
then. See -reference C# compiler option docs. -
OmarL about 6 yearsI have
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
-
Palec about 6 yearsThat version seems to be from an older build of VS 2017 (or its build tools). I cannot reproduce the problem with current VS 2017 (15.6.4,
csc -version
2.7.0.62715 (db02128e)). Still, thanks for sharing the issue and its solution. -
Motassem MK almost 6 yearsit was hilarious to say "so much fun" about not having an issue xD
-
phuclv almost 6 yearsprobably convert this into PowerShell which doesn't need a C# compiler?
-
Omar Alshaker almost 6 years@phuclv sure go ahead :D
-
Stevoisiak about 3 yearsCan a compiled version be provided?