This problem (active window loses focus) can be caused by a lot of different processes. It's not always BluetoothUIServer or CoreServicesAgent. In this discussion on
apple.stackexchange.com people report many other culprits, including Symantec Quick Menu, Google Drive.app, RecordIt, SystemUIServer, BetterTouchTool, and "Corel's buggy antipiracy program for CorelDraw."
There are python scripts posted on the page I referred to above that can help you track down what program or process is causing the focus loss on your system. What the script does is monitor window focus changes, and print out the name of the process that is gaining the window focus. Thus, by watching this output in a Terminal window, you can see what program or process is "stealing" the focus.
Unfortunately the script stopped working in recent releases of macOS due to changes in the supplied python environment. But by combining with the info in this
developer.apple.com forum I was able to get the python script to work on Monterey (macOS 12.6). I'll attempt to summarize what I did here...
Warning: I am not an expert with python. In particular I admit I don't know all the possible effects of creating this python "virtual environment". I
believe it will only have effect within the newly-created directory, and that it can be un-done by simply deleting that directory and its contents. I could be wrong, though! Try this at your own risk.
First, we need to create a python "virtual environment" as described at
developer.apple.com. It will create a new directory called 'python-env'. Enter these terminal commands, one at a time:
Code:
/usr/bin/python3 -m venv ~/python-env
cd ~/python-env
source bin/activate
pip install pyobjc
A lot of messages will scroll by after that last command.
Stay in that same directory and create a plain-text file called 'get_active_focus.py' with the following contents (I used "kenorb" 's version of the script):
Code:
#!./bin/python3
# Prints current window focus.
# See: https://apple.stackexchange.com/q/123730
from AppKit import NSWorkspace
import time
workspace = NSWorkspace.sharedWorkspace()
active_app = workspace.activeApplication()['NSApplicationName']
print('Active focus: ' + active_app)
while True:
time.sleep(1)
prev_app = active_app
active_app = workspace.activeApplication()['NSApplicationName']
if prev_app != active_app:
print('Focus changed to: ' + active_app)
Save the file. Run it by entering
Now bring different windows to active focus, and you'll see their names printed in the Terminal window. The script checks every second to see if focus has changed. When your window focus is "stolen", the last line should indicate what program gained the focus.
Once you've determined the problem program, kill the script by typing Ctrl-C. Once your problem is fully resolved, you can delete the directory and its contents with:
Hope that helps!