Thursday, September 11, 2008

C++ : How to Launch a Background in Windows Program

In linux it is easy to launch a background process at the command line with ampersand.

./app_to_launch &

In windows there is no easy command line suffix which will launch your program in the background. However it is relatively easy to code one up. If you install Visual C++ Express 2005, and the Microsoft Platform SDK (see configuration below) just compile this application as BKLAUNCH.exe and you will soon be able launch apps in the background from batch files.

I created an empty win32 project named BKLAUNCH, no precompiled header, and compiled the following code.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <windows.h>
#include <shellapi.h>
#include <tchar.h>

int _tmain(int argc, _TCHAR* argv[])
{
if (argc!=2)
{
printf("Usage:\n");
printf(" BKLAUNCH.EXE [apptolaunch]\n");
printf(" BKLAUNCH.EXE notepad.exe\n");
exit(0);
}
ShellExecute(NULL, TEXT("open"), argv[1], NULL, NULL, SW_SHOW);
return 0;
}


Once BKLAUNCH has successfully compiled, place it in a folder that is in the PATH. Now, go to Start > Run > cmd.exe [OK], and enter the following:
BKLAUNCH notepad.exe

You will notice notepad.exe is launched in the background, perfect for batch files.

Troubleshooting
If you are like me and use default settings, look under
Project > Project Properties > Linker > Input > Additional Dependencies
it will will have only kernel32.lib. When you compile there will be linker errors.

Because of the #include <windows.h> and #include <shellapi.h>
you need to add the following to your Additional Dependencies
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib in order to resolve the linker errors.

Microsoft Platform SDK Config
In order to use the MS Platform SDK in Visual C++ Express 2005, you have make the platform SDK visible to the compiler.

Go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=include files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include
(or wherever you installed the MS Platform SDK\Include)

Now, go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=library files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Lib
(or wherever you installed the MS Platform SDK\Lib)

No comments: