web analytics

How to run VBScript code programmatically from an C++ application?

Options

davegate 143 - 921
@2016-02-01 08:22:43

I have an C++ application, How can I run VBScript code programmatically or any other application from the existing C++ application?

Solution

You can use CreateProcess function to creates a new process and run any VBScript in that process. The following code demonstrates how to create an independent process to run a VBScript named myvbscript.vbs with two parameters.

   #include <string>
   #include <windows.h>
   
   ....
   
   string vbscript = "cscript /nologo \"C:\temp\myvbscript.vbs\" 100 200";
   
   STARTUPINFO si;
   PROCESS_INFORMATION pi;

   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );
   
   CreateProcess( NULL,   // No module name (use command line)
    (LPSTR)vbscript(),        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory
    &si,            // Pointer to STARTUPINFO structure
    &pi )   ;        // Pointer to PROCESS_INFORMATION structure

   // Wait until child process exits.
   WaitForSingleObject( pi.hProcess, INFINITE );

   // Close process and thread handles.
   CloseHandle( pi.hProcess );
   CloseHandle( pi.hThread );

If CreateProcess succeeds, it returns a PROCESS_INFORMATION structure containing handles and identifiers for the new process and its primary thread. The thread and process handles are created with full access rights, although access can be restricted if you specify security descriptors. When you no longer need these handles, close them by using the CloseHandle function.

Generally, you can use CreateProcess function to run any application prgrammatically from the existing C++ application. One thing we need to pay attention to is that the new process runs in the security context of the calling process, even if the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token.

To run the new process in the security context of the user represented by the impersonation token, use the CreateProcessAsUser or CreateProcessWithLogonW function.

@2016-02-01 08:23:45

See here for more details about CreateProcess function.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com