How to prevent a new WPF form from stealing focus?
Asked Answered
C

4

28

I have written a simple MSN-style program that will send and retrieve messages using WCF. The main form contains a Textbox to type in the message to be sent. In the background the application polls the server every few seconds for new messages. When a new message is received a new window is opened to display it. This has to be done on the UI thread using the Dispatcher class.

The problem is that when the new window is shown, the focus shifts away from the TextBox, so that typing is interrupted. This is very annoying! In MSN Messenger it is possible to continue typing your own message while receiving one. How is it done?

As a workaround I postpone the popup with the new message while the TextBox has focus, but there should be a better way!

Chatterer answered 21/9, 2009 at 20:0 Comment(1)
Is there a way to open a new window without it being focused?Proprietress
C
64

The answer is simple: Since .NET 3.5 SP1 WPF forms have a ShowActivated property. Set this to false and any form thus marked won't steal no focus no more!

Chatterer answered 22/9, 2009 at 5:59 Comment(1)
A WPF form? What's that?Maraca
E
0

An option to regain focus after showing another window is:

// inside your window that should remain in focus
yourWindow.Show();       // to show second window
this.focus();      // regain focus back instantly
Evert answered 14/3, 2024 at 16:8 Comment(0)
L
-2

You could set the Focusable property of the window to false.

Lignify answered 22/9, 2009 at 10:55 Comment(1)
Not in this case. The user must be able to interact with the formChatterer
F
-2

In my application I need to show a notification Window on top of all other windows while my MainWindow is minimized, but without stealing the focus.

So I just do this:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Topmost = true;
    this.Topmost = false;
}
Falla answered 23/9, 2015 at 12:0 Comment(1)
Since the loaded event fires after the window is already activated and shown, this does not stop if from stealing focus.Designer

© 2022 - 2025 — McMap. All rights reserved.