Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set system focus on my application

Tags:

focus

wpf

I have an application that will mainly operate in the background. I want certain system events that it handles to cause the app to steal focus from the foreground app, whatever that is. But UIElement.Focus() seems to only set the focus within the WPF app. That is, if the WPF app already has the focus as a whole, then Focus() sets the focus to the right control. But I need to steal focus from another app and put it on my app. How can I do this?

I do not want a system modal dialog. That is, after the window steals focus, it should be possible for the user to immediately switch to another app without dismissing my app's window.

The app may already been in a restored, minimized, or even "minimize to tray" state when it needs to steal system focus. So assuming that it is minimized and stealing focus while restoring the window is not acceptable.

like image 697
Andrew Arnott Avatar asked Nov 25 '25 06:11

Andrew Arnott


1 Answers

If you don't mind doing som p/invokes, the SetForegroundWindow function should be able to help you:
http://pinvoke.net/default.aspx/user32/SetForegroundWindow.html

like image 182
Tormod Fjeldskår Avatar answered Nov 27 '25 07:11

Tormod Fjeldskår



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!