Skip to content

FileOpenPicker (et al) does not restore keyboard focus properly to the window #6505

@benstevens48

Description

@benstevens48

Describe the bug

Show a FileOpenPicker. After it closes, keyboard events do not seem to be invoked (until the user clicks somewhere) even though the window is focussed and FocusManager.GetFocusedElement reports a focussed element. The issue can be worked around by adding (FocusManager.GetFocusedElement(Content.XamlRoot) as UIElement)?.Focus(FocusState.Programmatic) after picking a file.

Steps to reproduce the bug

Use the following minimal code.

 public sealed partial class MainWindow : Window {
     public MainWindow() {
         InitializeComponent();
     }
     private void Grid_KeyDown(object sender, KeyRoutedEventArgs e) {
         System.Diagnostics.Debug.WriteLine("Key pressed");
     }
     private async void testStoragePickerButton_Click(object sender, RoutedEventArgs e) {
         var filePicker = new FileOpenPicker(AppWindow.Id);
         filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
         filePicker.FileTypeFilter.Add("*");
         try {
             var file = await filePicker.PickSingleFileAsync();
         } catch (Exception) { }
         System.Diagnostics.Debug.WriteLine(FocusManager.GetFocusedElement(Content.XamlRoot)); //Note that there is a focussed element, but no key press events are generated
         //(FocusManager.GetFocusedElement(Content.XamlRoot) as UIElement)?.Focus(FocusState.Programmatic); //Uncomment this to restore keyboard focus
     }
 }
<?xml version="1.0" encoding="utf-8"?>
<Window x:Class="TestFilePickerFocus.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:TestFilePickerFocus" Title="TestFilePickerFocus">
    <Grid KeyDown="Grid_KeyDown">
        <Button x:Name="testStoragePickerButton" Click="testStoragePickerButton_Click" Content="Pick file"></Button>
    </Grid>
</Window>

Click the button, pick a file, then press any key (even enter, which should press the button again), and observe no "Key pressed" message in debug output.

Expected behavior

Keyboard focus should be properly returned.

Screenshots

No response

NuGet package version

2.1.3

Packaging type

Packaged (MSIX)

Windows version

Windows 11 version 24H2 LTSC (26100, June Update)

IDE

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-File accessTopics related to Microsoft.Windows.Storage.Pickers APIs for selecting files/folders etc.needs-triage

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions