How to make a C++ program process in background until the computer's shut down?

Step 1: If you are using an IDE then during project-creation it will most likely ask 'console-app' vs. 'window-app'. Choose window-app, which means that it will start without opening a console.

enter image description here enter image description here

Step 2: Now within the code your IDE probably will have generated some code that makes a Window visible. Remove that code:

enter image description here

Your program now runs but is not visible on the task-bar:.

enter image description here

For running your own code you have 2 options. Which of them is appropriate depends on your situation, but the second one is generally preferred:

  • either use one of the generated methods like WinMain to start your own method which should contain a loop and within that loop your code plus a call to Sleep().

  • use windows-messages to run some of your code on-demand. (preferred)

The program will run until your computer is shut down; then it will no-longer run.


A few notes on when to use option 1 vs. option 2:

Option 2 is what is typically considered better because it works with the operating system (Windows), it only executes code when the OS tells it that something changed. Option 1 on the other hand does not depend on windows messages - sometimes you need this independence. It comes at a price though: your code will probably 'manually' check if something changed, sometimes do something, but most of the time choosing to Sleep(). This is called ->polling btw. so prefer Option 2.


And this is how to modify WndProc for option-2-apps. Example: make a beep every second.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    switch (message)
    {
    #define IDT_TIMER1 123 // todo find out which numbers are allowed
                           // which depends on windows AND your organization
    case WM_CREATE:
        SetTimer(hWnd, IDT_TIMER1, 1000, (TIMERPROC) NULL);
    break;
    case WM_TIMER: 
        switch (wParam) { 
        case IDT_TIMER1:
            Beep(100,50);
        break;
        }
    break;
    case WM_COMMAND:
    ...

For that purpose you need to hide your window.

For console: ShowWindow (GetConsoleWindow(), SW_HIDE);

For Win32 project: either do not create window using CreateWindow or CreateWindowEx, or ShowWindow(hWnd, SW_HIDE)


Or the best solution, you can create service, some sample

Tags:

Windows

C++