简体   繁体   中英

c# - Setting current window as the foreground window

How can we set the currently opened window an application as the foreground window?

This scenario may be valid if, for example, you have to show the user another application until a condition is met, and then bring your application into his/her focus.

Of course, bringing a window to the foreground may be easily achieved using the SetForegroundWindow API. But this involves working with the System.Runtime.InteropServices namespace, and thus including unmanaged code in your application. An easier approach is a trick I found while looking for a way to do this.

It is as simple as setting our form's TopMost property to true and then immediately setting it back to false .

Setting it to true will determine the operating system to show it on top of any other windows, no matter if it is focused or not. And then, we restore the default behavior, by setting the property back to false : the window will go to the background if another application gets focus, and thus, comes to the foreground.

So, insert the following code snippet wherever you need such functionality:

this.TopMost = true;
this.TopMost = false;

A neat trick to save a lot of code lines!

Just use the correct .NET function:

form.Activate();

Don't use any TopMost things, it's not necessary.

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