Skip to content

msrdc.exe randomly stealing focus #894

Open

Description

@mha42

Version

10.0.22621.0

WSL Version

  • WSL 2
  • WSL 1

Kernel Version

5.15.74.2

Distro Version

Ubuntu 22.04

Other Software

Irrelevant, and happens as soon as the WSL instance is started.

Repro Steps

  1. Start any WSL instance. In my case I have a WSL v1 started without any WSLg support.
  2. Wait
  3. Focus is randomly stolen from your application.

I found an app somewhere at some point simply printing what process is currently getting focus. When focus is stolen I see the following line printed;

4300:C:\Program Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_1.0.0.0_x64__8wekyb3d8bbwe\msrdc.exe | Thu 17 November 12:26:04

Often I am having an outlook window open at the time in which I am composing a mail and suddenly I cannot write in it anymore.

Expected Behavior

WSL should not steal focus.

Actual Behavior

Focus is randomly stolen

Diagnostic Logs

N/A

Activity

  1. mha42 commented on Nov 17, 2022

    @mha42
    Author

    focus.zip

    I am attaching the focus tool incl source code.

  2. scottrudy commented on Dec 6, 2022

    @scottrudy

    I had this same issue today and used Focus Logger to find the culprit. It's also pointing to WSL's msrdc.exe. I've seen this happen with Notepad before, but today it seems to be related to opening Windows Explorer for me. I ran process explorer prior to starting Windows Explorer and watched several wslhost.exe processes start up, but one specifically fires up a conhost.exe process which then starts the msrdc.exe process, and that steals focus before shutting down. This all happens within seconds or less.

  3. maxhoesel commented on Dec 23, 2022

    @maxhoesel

    Can confirm this behavior on Windows 11, i had no issues until about 2 days ago. msrdc.exe seems to steal focus for a moment every 2 minutes, kicking me out of fullscreen applications.

    The only possible cause that I could think of is that I updated my VirtualBox install from from 6 to 7.X around that time. That could be a red herring though, unless someone else can confirm that correlation.

  4. mha42 commented on Dec 23, 2022

    @mha42
    Author

    Can confirm this behavior on Windows 11, i had no issues until about 2 days ago. msrdc.exe seems to steal focus for a moment every 2 minutes, kicking me out of fullscreen applications.

    The only possible cause that I could think of is that I updated my VirtualBox install from from 6 to 7.X around that time. That could be a red herring though, unless someone else can confirm that correlation.

    I don't run VirtualBox at all here.

  5. MarcoBrieden commented on Dec 26, 2022

    @MarcoBrieden

    This problem is driving me absolutely nuts!
    No matter what I'm using my computer for the focus is lost randomly every couple of minutes. Even trying to shut WSL down doesn't make any difference. I assume if I remove msrdc.exe I'll brick my system, but I really don't know what do do at this point.

    Has anyone found any way of fixing this?

    /edit:
    While wsl --shutdown didn't do anything killing the WSL process in the task manger seems to at least give temporary relief until the process gets auto started again, e.g. by using Windows Explorer.

  6. Lyqed commented on Jan 8, 2023

    @Lyqed

    Two possible solutions I found are:

    1. backup the msrdc.exe file and then delete it.

    2. Disable remote credential guard in the group policy editor by:

    First going to the local group policy editor, then navigating to Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security > Choose "Disabled" >Apply and restart pc

  7. ftvkyo commented on Jan 8, 2023

    @ftvkyo

    Can confirm, Windows 11 Pro, 22H2, 22621.963.

    Been wondering what was causing it since November, thought it is from my custom keyboard layout, because one of the symptoms was that the language menu (next to the clock) would disappear in these moments.

  8. zadjii-msft commented on Jan 18, 2023

    @zadjii-msft
    Member

    Craig Loewen (@craigloewen-msft) Any updates on this (or the other focus stealing threads)? I'm trying to rule out WSL from the cause of microsoft/terminal#13388, but that's proven... tricky.

  9. scottrudy commented on Jan 18, 2023

    @scottrudy

    I just uninstalled everything from my Windows 10 PC and reinstalled it, because it was so unstable. After re-installing I am still seeing the same issue. I can't even add a user to a new distribution because focus is stolen before I can enter a password for a new user.

    Using Process Explorer I can see the following hierarchy when the problem occurs:

    - wslservice.exe
      - wslhost.exe
        - conhost.exe
        - msrdc.exe
          - msrdc.exe
          - WerFault.exe
    

    Location of msrdc.exe
    C:\Program Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_1.0.3.0_x64__8wekyb3d8bbwe\msrdc.exe

    Command line argument
    msrdc.exe /v:0C22B93D-1735-409E-86C1-A57BAABA42C2 /hvsocketserviceid:4C7A87FC-FACB-11E6-BD58-64006A7986D3 /silent /wslg /plugin:WSLDVC_PACKAGE /wslgsharedmemorypath:WSL\0C22B93D-1735-409E-86C1-A57BAABA42C2\wslg "C:\Program Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_1.0.3.0_x64__8wekyb3d8bbwe\wslg.rdp"

  10. rwasef1830 commented on Jan 18, 2023

    @rwasef1830

    I've seen crashes in msrdc.exe in this background process when using the "Sound for remote desktop" (https://www.sound-over-rdp.com/) software. The cause of the crash was an issue in a DLL they inject in all processes, seemingly to force the output sound device. There was a way to enable crash memory dumps I think with the global flags tool, if you get such a dump may help narrow down the cause of the crash.

  11. scottrudy commented on Jan 18, 2023

    @scottrudy

    The issue I am seeing today shows the following in Problem Details

    Source
    Remote Desktop

    Summary
    Stopped working

    Date
    ‎1/‎18/‎2023 12:45 PM

    Status
    Report sent

    Description
    Faulting Application Path: C:\Program Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_1.0.3.0_x64__8wekyb3d8bbwe\msrdc.exe

    Problem signature
    Problem Event Name: MoAppCrash
    Package Full Name: MicrosoftCorporationII.WindowsSubsystemForLinux_1.0.3.0_x64__8wekyb3d8bbwe
    Application Name: praid:msrdc
    Application Version: 1.2.3575.0
    Application Timestamp: 633c8bef
    Fault Module Name: KERNELBASE.dll
    Fault Module Version: 10.0.19041.2364
    Fault Module Timestamp: 5b7d4d22
    Exception Code: c06d007e
    Exception Offset: 000000000002cd29
    OS Version: 10.0.19044.2.0.0.256.4
    Locale ID: 1033
    Additional Information 1: 3895
    Additional Information 2: 3895d839a7fe3f6903b9cbca03bd030e
    Additional Information 3: 3981
    Additional Information 4: 3981f255f8e6b8e54242bfc4bce248e4

    Extra information about the problem
    Bucket ID: 1bdacafa384471b8e7d131b0fc19a97e (0)

  12. thheller commented on Jan 27, 2023

    @thheller

    This has to be the most infuriating thing I have ever encountered. I can't code in IntelliJ anymore, feels like every other second something is stealing my focus. Using the Focus Logger tool I also identified the "msrdc.exe" as the cause. In the midst of typing some code the focus is just gone, then returns after a few seconds.

    I just did a clean install Win11 Pro and did all the updates. Now the Computer is basically unusable.

  13. thheller commented on Jan 27, 2023

    @thheller

    I found #523, and created the $HOME/.wslconfig (windows home, C:\Users\..\.wslconfig not in linux) with

    [wsl2]
    guiApplications=false
    

    That at least seems to bring some relief.

  14. meiskam commented on Jan 28, 2023

    @meiskam

    having the same issue

    WSL version: 1.0.3.0
    Kernel version: 5.15.79.1
    WSLg version: 1.0.47
    MSRDC version: 1.2.3575
    Direct3D version: 1.606.4
    DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
    Windows version: 10.0.22621.1105
    

    neither wsl --shutdown nor $HOME/.wslconfig .. guiApplications=false helped

  15. 66 remaining items

  16. blkot commented on Jan 26, 2026

    @blkot

    yeah GPT gave me this powershell script and catch this thief msrdc.exe for me and point me all the way here.
    and .wslconfig + shutdown temporarily gave me relief but i'm not sure whether this is a good idea because i actually need WSLg with Arch and Colmap (probably)

    Add-Type @"
    using System;
    using System.Runtime.InteropServices;
    public class Win32 {
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
    }
    "@
    
    $lastPid = 0
    while ($true) {
        $hwnd = [Win32]::GetForegroundWindow()
        $procId = 0
        [Win32]::GetWindowThreadProcessId($hwnd, [ref]$procId) | Out-Null
    
        if ($procId -ne $lastPid -and $procId -ne 0) {
            $p = Get-Process -Id $procId -ErrorAction SilentlyContinue
            "$(Get-Date -Format HH:mm:ss.fff) FG → $($p.ProcessName) ($procId)"
            $lastPid = $procId
        }
        Start-Sleep -Milliseconds 50
    }
    
    
  17. AJolly commented on Feb 6, 2026

    @AJolly

    Still getting this issue all the time

  18. vectorkovacspeter commented on Feb 12, 2026

    @vectorkovacspeter

    same on here latest windows 11, thats crazy...

    my detective script:

    # FocusLogger.ps1
    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        using System.Text;
        public class WindowHelper {
            [DllImport("user32.dll")]
            public static extern IntPtr GetForegroundWindow();
            
            [DllImport("user32.dll")]
            public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
            
            [DllImport("user32.dll")]
            public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
        }
    "@
    
    $logFile = "$env:USERPROFILE\Desktop\focus_log.txt"
    $lastWindow = ""
    
    while ($true) {
        $hwnd = [WindowHelper]::GetForegroundWindow()
        $sb = New-Object System.Text.StringBuilder 256
        [WindowHelper]::GetWindowText($hwnd, $sb, 256) | Out-Null
        $windowTitle = $sb.ToString()
        
        $processId = 0
        [WindowHelper]::GetWindowThreadProcessId($hwnd, [ref]$processId) | Out-Null
        $process = Get-Process -Id $processId -ErrorAction SilentlyContinue
        
        $currentWindow = "$windowTitle | Process: $($process.ProcessName)"
        
        if ($currentWindow -ne $lastWindow) {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            "$timestamp - $currentWindow" | Add-Content $logFile
            Write-Host "$timestamp - $currentWindow"
            $lastWindow = $currentWindow
        }
        
        Start-Sleep -Milliseconds 500
    }
  19. cyraid commented on Feb 12, 2026

    @cyraid

    Kovács Péter (@vectorkovacspeter) What happens if the window title changes but the process name stays the same? Wouldn't it be a window focus change in the log? Why couldn't you just have $currentWindow/$lastWindow keep track of the Window Handle $hwnd for current window? (or better yet, Process ID)

    Also a thing to note is C# now has single file improvements, so you could (if you wanted), have the entire script in a single .cs file, and use dotnet run with it. :)

  20. vectorkovacspeter commented on Feb 13, 2026

    @vectorkovacspeter

    Dennis Fehr (@cyraid) its not a coding tutorial or a polished product or some opensource ppull-request, just AI crap good enogh for me, to track what happens, and find the root cause whitin 5 min, and just post it to help thoose who need it ;)

    But thanks for the review, I told it to the modell who wrote it :D

  21. cyraid commented on Feb 13, 2026

    @cyraid

    Kovács Péter (@vectorkovacspeter) lol fair enough! You show that AI bot! Get em'!

  22. GyllenByte commented on Mar 1, 2026

    @GyllenByte

    Every 30 seconds like clockwork; and it started happening so arbitrarily. I had WSL installed and used it for ... months at this point. What changed? A few weeks ago, I cloned some repos and compiled them under Ubuntu (WSL). No issues up until yesterday or so. It's insane. How can this still be an issue after four years? An invisible, untracable app playing pranks. I thought I had caught some malware randomly. Like the others, I used a similar "FocusThief" logger via PowerShell script. W10 Pro 22H2.

    I couldn't make the guiApplications=false stick. First mistake, accidentally omited the [wsl2] section header. Not sure if that worked already. One other niche: Been using Everything (voidtools) search util. Recently, probably around the time this bug started occuring, I added \wsl$.. as an explicitly indexed folder.. So I can search the tiny distro quickly without pulling up a file explorer each time. Unchecked "Attempt to monitor changes" for its folder settings (Settings > Indexes > Folders > \wsl$..). For me, I think that's what kept waking the gui subsystem 😡

  23. slashy commented on May 23, 2026

    @slashy

    How is this still a problem almost 4 years later? I was getting this since basically forever and it was annoying when it happened to my IDE, but it's now also happening when I am playing fullscreen games and they keep losing all input when it happens... pretty annoying. So I decided to check what exactly it is via Focus Logger and found this to be the culprit.

    I don't have voidtools Everything, so it's clearly something else also triggers an WSL conhost.

  24. korypostma commented on Jun 2, 2026

    @korypostma

    @korypostma, what tool did you use to get your focus output?

    Sorry, I didn't see the tag until now, it was a custom python script:

    # Import necessary libraries
    import win32gui
    import win32process
    import psutil
    import time
    from datetime import datetime
    
    # Function to get the title of a window given its handle
    def get_window_title(hwnd):
        """
        Retrieves the text of the specified window's title bar (if it has one).
        :param hwnd: The handle to the window.
        :return: The window title as a string.
        """
        return win32gui.GetWindowText(hwnd)
    
    # Function to get the process name from a process ID (PID)
    def get_process_name(pid):
        """
        Retrieves the name of the process associated with the given PID.
        :param pid: The Process ID.
        :return: The process name as a string, or "N/A" if not found.
        """
        try:
            process = psutil.Process(pid)
            return process.name()
        except psutil.NoSuchProcess:
            return "N/A"
    
    # Function to get the command line arguments of a process
    def get_process_command_line(pid):
        """
        Retrieves the command line arguments of the process associated with the given PID.
        :param pid: The Process ID.
        :return: The command line arguments as a string, or "N/A" if not found.
        """
        try:
            process = psutil.Process(pid)
            return " ".join(process.cmdline())
        except psutil.NoSuchProcess:
            return "N/A"
        except Exception:
            return "N/A" # Catch other potential errors
    
    # Function to get parent process information
    def get_parent_process_info(pid):
        """
        Retrieves the name and PID of the parent process for a given PID.
        :param pid: The Process ID.
        :return: A tuple (parent_process_name, parent_pid) or ("N/A", "N/A") if not found.
        """
        try:
            process = psutil.Process(pid)
            parent_process = process.parent()
            if parent_process:
                return parent_process.name(), parent_process.pid
            else:
                return "N/A", "N/A" # No parent process (e.g., initial system processes)
        except psutil.NoSuchProcess:
            return "N/A", "N/A"
        except Exception:
            return "N/A", "N/A" # Catch other potential errors
    
    def monitor_active_window():
        """
        Monitors the active window and prints its name, application name, parent process,
        command line arguments, and the time of focus change.
        """
        print("Starting window focus monitor...")
        print("Press Ctrl+C to stop.")
    
        last_active_window_hwnd = 0
        last_active_window_title = ""
        last_process_name = ""
        last_parent_process_name = "" # Not strictly needed for logic, but good for tracking
        last_command_line = ""
    
        try:
            while True:
                # Get the handle of the foreground window
                current_active_window_hwnd = win32gui.GetForegroundWindow()
    
                # Check if the active window has changed
                if current_active_window_hwnd != last_active_window_hwnd:
                    # Get the window title
                    current_window_title = get_window_title(current_active_window_hwnd)
    
                    # Get the process ID of the window
                    # win32process.GetWindowThreadProcessId returns a tuple (thread_id, process_id)
                    _, pid = win32process.GetWindowThreadProcessId(current_active_window_hwnd)
    
                    # Get the process name
                    current_process_name = get_process_name(pid)
    
                    # Get the command line arguments
                    current_command_line = get_process_command_line(pid)
    
                    # Get the parent process info
                    parent_process_name, parent_pid = get_parent_process_info(pid)
    
                    # Get the current time
                    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
                    # Print the information
                    print(f"[{current_time}] Focus Changed:")
                    print(f"  Window Title      : '{current_window_title}'")
                    print(f"  Application       : '{current_process_name}' (PID: {pid})")
                    print(f"  Command Line Args : '{current_command_line}'") # New line for command line
                    print(f"  Parent Process    : '{parent_process_name}' (PID: {parent_pid})")
                    print("-" * 40) # Separator for readability
    
                    # Update the last active window details
                    last_active_window_hwnd = current_active_window_hwnd
                    last_active_window_title = current_window_title
                    last_process_name = current_process_name
                    last_command_line = current_command_line
                    # last_parent_process_name = parent_process_name # Optional: for tracking if needed later
    
                # Wait for a short period before checking again to reduce CPU usage
                time.sleep(0.5)
    
        except KeyboardInterrupt:
            print("\nWindow focus monitor stopped.")
        except Exception as e:
            print(f"An error occurred: {e}")
    
    if __name__ == "__main__":
        # Instructions for the user:
        # 1. Ensure Python is installed.
        # 2. Install required libraries using pip:
        #    pip install pywin32 psutil
        # 3. Run this script from a command prompt:
        #    python your_script_name.py
        monitor_active_window()
  25. lidonwonk commented on Jun 11, 2026

    @lidonwonk

    just encounter this. shocked at it hasn't been fixed.it's really annoying.so i disabled wslg and use VcXsrv now

  26. liugangnhm commented on Jul 29, 2026

    @liugangnhm

    ms is stupid

  27. campbell-reid-displayr commented on Aug 11, 2026

    @campbell-reid-displayr

    Another victim of this annoying thing. Glad other people vibe coded tools to figure this out too lol.

  28. TheDirigible commented on Aug 17, 2026

    @TheDirigible

    Still happening 4 years later. Maddening.

  29. serious-angel commented on Oct 9, 2026

    @serious-angel

    Wonderful day!

    Apparently, if Sublime Text v4215 has opened a file from \\wsl.localhost, it may frequently lose focus when returning to it. I've tried monitoring windows focus, and got the following when I switched to a Sublime Text window:

    ============== New program has foreground window ============
    C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
    ============== New program has foreground window ============
    D:\Programs\Installed\Sublime Text\sublime_text.exe
    ============== New program has foreground window ============
    C:\Program Files\WSL\msrdc.exe
    

    The above is an output of a program found Focusmonitor by Nicholas Chapman (@Ono-Sendai) , thank you very much! Oh! What if the program would also print the precise time of the event? ^^"

    It's worth to mention that the layout also disappears from the Taskbar when Sublime Text loses the focus suddenly. Perhaps similar to the above case mentioned:

    ...because one of the symptoms was that the language menu (next to the clock) would disappear in these moments.

    ~ Rei Stepanenko (@ftvkyo)
    Source: #894 (comment)

    I am not the most frequent on Windows (am mainly at Linux), but I'll try do more research if required.


    $ wsl --version
    WSL version: 3.0.1.0
    Kernel version: 6.18.40.1-1
    WSLg version: 1.0.79
    MSRDC version: 1.2.7214
    Direct3D version: 1.611.1-81528511
    DXCore version: 10.0.26100.1-240331-1435.ge-release
    Windows version: 10.0.19045.6466
    
  30. rio197 commented on Nov 15, 2026

    @rio197

    Four years on and it's still happening. Here's some PowerShell code that Gemini suggested on how to confirm that msrdc.exe indeed steals your focus:

    Add-Type @"
    using System;
    using System.Runtime.InteropServices;
    public class FocusTracker {
        [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    }
    "@
    $lastHwnd = [IntPtr]::Zero
    Write-Host "Monitoring focus changes... Press Ctrl+C to stop." -ForegroundColor Cyan
    while ($true) {
        $hwnd = [FocusTracker]::GetForegroundWindow()
        if ($hwnd -ne $lastHwnd -and $hwnd -ne [IntPtr]::Zero) {
            $pidOut = 0
            [void][FocusTracker]::GetWindowThreadProcessId($hwnd, [ref]$pidOut)
            $proc = Get-Process -Id $pidOut -ErrorAction SilentlyContinue
            $time = Get-Date -Format "HH:mm:ss.fff"
            Write-Host "[$time] Process: $($proc.ProcessName) (PID: $pidOut) | Title: '$($proc.MainWindowTitle)'"
            $lastHwnd = $hwnd
        }
        Start-Sleep -Milliseconds 150
    }
    

    • Trigger the issue. Leave the PowerShell terminal (with the above code) running in the background and use your computer normally until your window loses focus.
    • Check the output. Look at the timestamp when the interruption occurred to see the exact executable name and process ID (PID) that grabbed focus, even if the window vanished immediately. Press Ctrl + C in the terminal to stop the script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions