Bringing Window to the Front in C# using Win32 API

2020-02-03 09:59发布

I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus).

What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work.

What is the best way to go about this? Any thoughts?

标签: c# winapi
6条回答
何必那么认真
2楼-- · 2020-02-03 10:05

You could use FindWindow to get the HWND of the window, then use the BringWindowToTop function found in the Win32 API.

查看更多
祖国的老花朵
3楼-- · 2020-02-03 10:09

What is the difference between SetForeGroundWindow, SetActiveWindow, and BringWindowToTop? It appears as if they all do the same thing.

According to MSDN, SetForeGroundWindow will activate the window and direct keyboard focus to it. This attempts to work even when your process is in the background. SetActiveWindow does the same thing as SetForeGroundWindow, but it doesn't do anything if your application isn't the frontmost application. Finally, BringWindowToTop only brings the window to the top, and doesn't change the keyboard focus.

查看更多
Fickle 薄情
4楼-- · 2020-02-03 10:09

SetWindowPos + SWP_NOACTIVATE does the job.

查看更多
We Are One
5楼-- · 2020-02-03 10:20

SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail.

The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window

Try capturing the focus with SetCapture prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.

查看更多
贼婆χ
6楼-- · 2020-02-03 10:28

You can try the BringWindowToTop function to not steal focus. I haven't used it, but it seems to be what you're looking for.

查看更多
冷血范
7楼-- · 2020-02-03 10:29

Have you tried using SetWindowPos. This is the canonical function for moving, resizing and setting z-order in Windows. There is a SWP_NOACTIVATE flag you can use. Look at http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx. I have not tried this on a window belonging to another process, but it is probably worth a try.

查看更多
登录 后发表回答