Golang how to set window on top

Viewed 1433

I am developing an app that opens a portable browser to a specific page. The thing is that every once in a while I would like to switch the focus to the browser window, so that it will appear on top of the screen if it is minimized or if there is a window on top of it.

I've tried to do this using robotgo, by setting the active PID to my browser's PID and setting it as active, but that didn't work:

robotgo.ActivePID(26360)
handle := robotgo.GetHandle()
fmt.Println("handle: %s", handle)

mdata := robotgo.GetActive()

robotgo.SetActive(mdata)

Is there a way to do this?

Note: since I am opening this browser process myself using exec.Command, I have its PID, so I don't have to search for it.

Note 2: I am running this program on Windows.

1 Answers

Question is old but I had the exact same problem and I made a small package for it.

You can find it here : https://github.com/audrenbdb/goforeground

It's cross platform linux/windows; I have yet to implement it on darwin.

A summary on how it works : you enumerate all active windows and you check if PID match, once you've found the proper window you set it foreground.

On linux, it utilizes X11 (mostly); on windows win32 api. Now the trick on window is that a PID may be related to multiple windows. So we need to check two other things : Is window active, and Is window owned (see discussion here : How to get main window handle from process id?).

Related