user563413
user563413

Reputation: 21

How to create a win32 application without window in background with C?

The application do not need any window or console. It can be a console application if the console window can be removed or can be put into background. The application will do some simple tasks(such as cleaning rubbish files) and exit.

  1. I hope that the application should not be a windows service if possible.

  2. I hope that the application can be started with double-click in explorer window and run silently.

  3. When the application is running, I hope that the mouse cursor should not be changed to hourglass shape. That is to say, do not disturb the user when the application is running. Just run and exit silently.

  4. DO NOT NEED to run it when windows starts or user logins.

I hope this can be done in C if possible. What should I do?

task_finished = 0;
CreateThread(NULL, 65535, task_thread, para, 0, NULL);

MSG msg;
while(!task_finished){
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
        if(task_finished)
            break;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

Upvotes: 2

Views: 4536

Answers (2)

user541686
user541686

Reputation: 210781

All you need is a message loop -- just use this code (modified from here):

MSG msg;
BOOL bRet; 
while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
{ 
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg); 
        DispatchMessage(&msg); 
    } 
} 

Edit:

For I/O or other tasks, you can either (1) create another thread, and do everything from there, or (2) Use MsgWaitForMultipleObjects inside the loop (before the next GetMessage() call) to simultaneously wait on your I/O and on messages, so that you can be notified when there's either a message, or when your I/O is finished.

Warning:

I haven't figured out how to make the application not bring up the hourglass shape when starting. If you need that functionality, consider creating a Windows service instead. You can also compile as a console application, then use FreeConsole to hide the window.

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 373512

IIRC, you can do this by just writing a WinMain function that doesn't create or display a window or console. Lambert's answer about using a message loop will help you if you want your program to be able to send or receive messages from other programs, but if you're just doing simple background processing all you should need is a WinMain that doesn't make a window.

Upvotes: 2

Related Questions