How would I detect if a program is running not on the top-level? If it were top-level i'd just use FinWindow(), but I am yet to find an alternative of FindWindow() for lower-level processes. I want my process to check if it is already running, but it is not a top-level process.
Pseudo Code:
1 2 3 4 5 6
Starts.
Checks if'MyProcessName' is already running in the background
if yes
exit()
if no
continue with the program
#include <iostream>
#include <windows.h>
bool already_running()
{
// note: the Global\ prefix for the name indicates that the event is created
// in the global kernel namespace. this implies that two different clients
// (typically two different users) will not be able to run this program at the same time
// To allow different clients to run the program at the same time, but disable
// any one client from running more than one instance of the program at one time,
// create the event object in the session local namespace by dropping the
// Global\ prefix or by replacing it with the Local\ prefix.
staticconstchar event_name[] = "Global\\my_program/event/this_program_is_already_running" ;
::CreateEventA( nullptr, TRUE, TRUE, event_name ) ;
return GetLastError() == ERROR_ALREADY_EXISTS ;
}
int main()
{
if( already_running() )
{
std::cerr << "the program is already running\n" ;
return 1 ;
}
// else continue with program
// ...
}
This seems like a viable option! If not I plan to look into Enuming all Processes, but with the CreateEvent() would that event be deleted when my program closes?
> but with the CreateEvent() would that event be deleted when my program closes?
Yes.
Kernel objects are reference counted; when the program closes (process exits or is terminated), the reference (in the case of the only one running instance, the only reference) to the event object is automatically released, and the object and its associated entry in the object manager namespace are removed (the event is deleted by the kernel).
You can verify this by running the program once again, after terminating the instance that was already running.