I am trying to learn windows programming. I would like to launch an executable program.exe
(say) from c++ code. I am able to achieve this by using CreateProcess()
method in windows. However, my problem is if the process is already created and running in the background then the windows for program.exe
should come to foreground otherwise a new process should be created and brought to the foreground. Any help will be appreciated.
Asked
Active
Viewed 1,883 times
1

Akhilesh Pandey
- 868
- 8
- 18
-
There are functions to [find a (top-level) window](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindowa), from which you can get a handle to manipulate (e.g. move to foreground). – Some programmer dude Aug 06 '19 at 12:05
-
system() should work. – nada Aug 06 '19 at 12:43
-
1@nada `system()` would NOT work in this situation. All it does is spawns an instance of `cmd.exe` to invoke a command, and there is no native command-line command to do what Akhilesh is asking for. But even if there were, it is better to do this kind of stuff using native APIs then shelling out to an external process anyway. – Remy Lebeau Aug 06 '19 at 18:23
2 Answers
2
Look at Win32 API functions such as the following:
to discover if a given process is running, you can use:
CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS)
withProcess32First()
andProcess32Next()
. See Taking a Snapshot and Viewing Processes.
or
to find an existing window, you can use:
FindWindow()
orFindWindowEx()
, if you know the window's class name or title text ahead of time.
or
EnumWindows()
withGetClassName()
and/orGetWindowText()
, if the window's class name or title text are dynamic but follow a pattern you can look for.
to restore a window if it is minimized, you can use
IsIconic()
withSetWindowPos(SW_RESTORE)
.to bring a window into the foreground, you can use
BringWindowToTop()
and/orSetForegroundWindow()
.

Remy Lebeau
- 555,201
- 31
- 458
- 770
0
Is that program.exe
written by you? This functionality is better handled there: on start you check if there is already an instance running and if there is - activate it.
Otherwise - what do you do if there are multiple instances of program.exe
already running?

Vlad Feinstein
- 10,960
- 1
- 12
- 27
-
No, I am using existing .exe as of now (notepad.exe). The point is I don't have access to the .exe source code. – Akhilesh Pandey Aug 08 '19 at 05:55