Possible to have Win32 application block until it exits? - c++

When I open a command line in Windows (cmd) and start a program, for example calc, the prompt immediately returns and the program is started (the calculator window is displayed).
This is contrary to how I know it from the Linux world: when I start a (possibly with GUI) application, the prompt does not return until I exit the started program.
Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?

Possible to have Win32 application block until it exits?
Call CreateProcess to create the process. This will yield a handle to the process in the PROCESSINFORMATION struct that is returned. Pass that process handle to WaitForSingleObject to wait until the process is signaled.
Based on the comments it seems that what you really want is an executable that will behave like a console app when its parent process is a console app. And behave like a GUI app otherwise. It's not possible to do both from a single executable. The target subsystem is determined by metadata in the executable file.
The standard way to handle this is to have two executables, each targeting the different subsystems. One a console app, the other a GUI app. The common examples of this are java.exe and javaw.exe, python.exe and pythonw.exe.

Using the w32 api, is it possible to program it so that my app displays a window, but the prompt is only returned after the user closes the window?
I think there are a few questions here.
First, how do you create a process in Windows? To create a process Windows, you use CreateProcess.
Second, how does CreateProcess work? CreateProcess obviously creates a new process (like calc.exe), and it offers a lot of options to create the process. It also returns a BOOL to let you know if the call failed or succeeded.
In the case the call fails, you get a failure immediately. That's a "synchronous" failure, and you can continue moving along in your procedures.
In the case the call succeeds, your process is "detached" from the child. Its more like an "asynchronous" call to the function. You can synchronize with the child process, and you can learn that it has exited by waiting on the hProcess member of the PROCESS_INFORMATION structure.
Third, not everyone starts processes from the command line. It might be started by clicking it on the desktop. This is true in the Linux/X11 (et al) world too.
Fourth, from the Windows command line, I believe you can use CALL for other batch files. But I don't recall if it applies to programs, too.

Related

How to write a Windows application that doesn't immediately release control to the calling application

I am writing a small application (.exe) that does some tasks and then returns an exit status. It is meant to be run regularly from another application (which I have no control over) that uses the status code to determine further action.
It works just fine if I compile and link it as a console app. However, that makes the console window flash briefly on the screen every time it is run, which is a little bit annoying. I tried to make it a Windows app, but the problem then is that Windows releases control to the calling application (or the OS) immediately after start. Thus, any exit status my application generates is returned too late and is never seen by the calling application.
Is there a way to force my app to stay in the foreground, so to speak, and not release control before it actually exits? I tried to force the entry point to be the "main" function instead of "WinMain", but that didn't help.
It isn't a question of whether the child "releases control" or not - Windows is a preemptive multitasking operating system, so all processes run at once. If the parent process waits for the child to exit, it is because the programmer told it to wait for the child to exit.
It isn't easy to make a program wait for console programs but not non-console programs. The command shell (cmd.exe) works this way when run interactively, but there isn't any API that does this as far as I know. Assuming that it isn't deliberate - which would be very strange in this context - the only explanation I can think of is that the program is running an interactive command shell and feeding in your command via standard input. That's the wrong thing to do, but I have seen people trying to do it that way before.
Presumably you can choose the command line that the parent executes. Try this:
start /wait myapp.exe
(That's how you would do it in an interactive command shell.)
If that doesn't work, you may have to consult the author of the parent process for advice.

Stopping a user from running a program directly

I am writing an application in Qt which gets executed by a launcher app. How can I detect whether the Qt application was launched by the user or the launcher. Is command line parameters the only way or is there a better way?
Both the Qt app and launcher are written by me.
Lots of ways. A command line parameter could be easily sniffed (by Process Explorer, e.g.), if that's a concern. But a named mutex or some other interprocess handle that can be inherited by the child app would be more difficult to spoof.

Windows Parent and Child Process creation

I want to create 5 child process in Windows using C++. But I am confused that CreateProcess asks for lpApplicationName and not like fork in which I can figure out whether I am child or parent. how to do this in Windows
Unfortunately the CreateProcess function can only be used to load a program and start a new process for that program.
You can however use CreateProcess to simulate the fork functionality, by asking it to load the program you are already running, and then ask it to jump to the correct position. This is what is (or was, at least) done by Cygwin, as referenced by this old answer.
It is usually preferable in Windows to use threading rather than multiple processes, because processes are much heavier objects in Windows than in UNIX.
However, you can do what you're asking by passing the name and path of your application to CreateProcess (using GetModuleFileName if you don't already know it) and including a command-line argument to tell your application that it is being launched as a child process.
Keep in mind that the child processes will be started from scratch, they will not have a copy of the parent's memory as they would if you were using fork.

Monitoring open programs with Win32

I've searched the web, and various forums, but I can't find one thing, how to continually monitor open programs and then close another program (not the one being monitored) if something happens to the program being monitored.
For example, say that there is an already open Notepad window, and then the user or some other program opens a Windows Explorer window. I want to know how to close the Notepad window without interacting with the Windows Explorer window (other than realizing that it is indeed open), as well as closing the Notepad window if the user closes the Windows Explorer window.
Thanks in advance! :D
On windows, you can use PSAPI (The Process Status API) to know when processes are started and terminate. The EnumProcesses function can give you this information.
A more reliable method to determine that a process terminated (since process ids can be reused) is to wait on its process handle (you will need the SYNCHRONIZE access right) which you can obtain using OpenProcess and the process' id obtained from EnumProcesses.
To terminate a process, there is always TerminateProcess. To call TerminateProcess, you will need a handle to the process with the PROCESS_TERMINATE access right. All of this assumes that you have the privileges needed to perform these actions on the process to be terminated.
One thing to be aware of is that processes and programs - or at least what the user regards as a program - are not necessarily the same thing.
If you use the PSAPI to get a list of all the processes running, you'll see a lot of background process that don't correspond to open windows at all. There's also cases where a single process can have multiple top-level windows open. So while you have simple cases like notepad where once notepad.exe process corresponds to one Notepad window, you also have cases like:
Word, where one word process handles all the word documents currently open (one process, many windows)
Explorer, where a single exploere.exe process handles all the open explorer windows, and also things like control panel windows and the task bar.
Chrome (and other browsers), where each tab gets its own process (many processes, one window!)
Using TerminateProcess is perhaps not the best way to close an app: it's not directly equivalent to clicking the close button. It forcibly terminates the entire process there and then, without giving it any chance to clean up. If you do this on Word, when it restarts, it will go into 'recovery mode', and act as though it hadn't shut down cleanly the last time. It's best left as a last resort if a process has stopped responding. Also, if you TerminateProcess on a process like Word or Explorer, you'll end up closing all windows owned by that process, not just one specific one.
Given all of this, if you want to essentially write some sort of program manager, you might be better off taking a window-centric approach rather than a process centric one. Instead of monitoring running processes, monitor top-level application windows.
There are several ways to listen for changes to windows; SetWinEventHook with EVENT_CREATE/DESTROY is one way to listen for HWNDs being created or destroyed (you'll need to do filtering here, since it will tell you about all HWNDs - and more! - but you only care about top-level ones, and only app ones at that). SetWindowsHookEx may have other options that could work here (WH_CBT). You can also use EnumWindows to list the windows currently present (again, you'll need to filter out owned dialogs and tooltips, currently invisible HWNDs, etc).
Given a HWND, you can get process information if needed by using GetWindowThreadProcessId.
To close a window, sending WM_SYSCOMMAND/SC_CLOSE is the best thing to try first: this is closer to clicking the close button, and it gives the app a chance to clean up. Note that some apps will display a "are you sure you wish to close?" dialog if you haven't saved recently - again, it's consistent with clicking the close button with the mouse.
The most well-known way of doing this on Windows is to use the Process Status API. You can use this API to enumerate processes However, this API is annoying in that it doesn't guarantee you get the full list or processes.
A better way to enumerate processes is using the Tool Help Library, which includes a way to take a complete snapshot of all processes in the system at any given time.
You need the Microsoft PSAPI (Processes API), for example to see the open processes you can use the openProcess function.

Check if windows shell has finished loading startup programs

How can i programatically check if the windows shell (explorer) has loaded all startup programs & the user login process is over ?
There is a somewhat documented event you can wait for, but it is signaled when explorer has started loading. On XP this event is called "msgina: ShellReadyEvent" and "ShellDesktopSwitchEvent" on Vista. I linked to the sources of some alternative shells in a post related to this event.
Another alternative would be to listen for the Taskbar Creation Notification message. It can fire more than once so you would need to keep track of that.
On Vista+ there is one last alternative that might just work: Programs set to run at startup are part of a job object so they cannot run at high priority. If your program runs at startup you could maybe check for this, either by using IsProcessInJob or SetPriorityClass+GetPriorityClass in a loop. (SetPriorityClass will lie about its return value IIRC)