简体   繁体   中英

Get Keyboard events back, after WebBrowser gets focus

I have a situation where I would want to use WFP WebBrowser , but when the user presses a button something happens; however after WebBrowser gets focus, some keyboard and mouse events no longer fire in my app.

To reproduce: Create a new project, set XAML:

<Window x:Class="ProblemKeyboard.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <WebBrowser x:Name="browser" Height="177" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="479" />
    </Grid>
</Window>

and let the codebehide override OnKeyDown() event.

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        browser.Navigate("http://www.google.com");
        //The above line causes browser to focus 
        //and as a consequence the OnKeyDown() handler 
        //doesn't get called again
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.Enter) MessageBox.Show("Yey!");
        base.OnKeyDown(e);
    }
}

Okay, understandably the user might want to type his Google query. But at some point I want to get control back. To this end, I've devised a button. When you click this button I want keyboard control to come back to the WPF app. But no matter what the button does, I can't get OnKeyDown() to fire again.

My particular restrictions allow WebBrowser to be destroyed at this point. I tried clearing its parent container, tried calling Dispose() and the garbage collector. Tried Focus() ing on things that have that functionality. Nothing seems to get control back.

I'd rather avoid solutions which create new Window() or something to that effect.

EDIT

I've found that putting a TextBox and making it focus gets me back focus! However I have no textboxes in my window, and adding one just for giggles seems counter-intuitive at best.

EDIT 2

Current temporary solution puts an invisible (well, kinda, it's just 0 by 0, Visibility.Hidden doesn't work) TextBox - enables it, focuses it and disables it. Without disabling it first some keys are handled by TextBox instead of bubbling up to KeyDown() .

Yes it is reproducible for Enter key only and the fix is to use OnKeyUp() for Enter Key....

    protected override void OnKeyUp(KeyEventArgs e)
    {
        if (e.Key == Key.Enter) MessageBox.Show("Hi");
        base.OnKeyUp(e);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM