C++ Executing CMD Commands

Viewed 53975

I'm having a serious problem here. I need to execute a CMD command line via C++ without the console window displaying. Therefore I cannot use system(cmd), since the window will display.

I have tried winExec(cmd, SW_HIDE), but this does not work either. CreateProcess is another one I tried. However, this is for running programs or batch files.

I have ended up trying ShellExecute:

ShellExecute( NULL, "open",
    "cmd.exe",
    "ipconfig > myfile.txt",
    "c:\projects\b",
    SW_SHOWNORMAL
);

Can anyone see anything wrong with the above code? I have used SW_SHOWNORMAL until I know this works.

I really need some help with this. Nothing has come to light, and I have been trying for quite a while. Any advice anyone could give would be great :)

6 Answers

I have a similar program [windows7 and 10 tested] on github

https://github.com/vlsireddy/remwin/tree/master/remwin

This is server program which

  1. listens on "Local Area Connection" named interface in windows for UDP port (5555) and receives udp packet.
  2. received udp packet content is executed on cmd.exe [please not cmd.exe is NOT closed after running the command and the output string [the output of the executed command] is fedback to the client program over same udp port].
  3. In other words, command received in udp packet -> parsed udp packet -> executed on cmd.exe -> output sent back on same port to client program

This does not show "console window" No need for someone to execute manually command on cmd.exe remwin.exe can be running in background and its a thin server program

To add to @Cédric Françoys answer, I fixed a few things in his code for a Windows build:

Missing function definition:

To make the code compile, add the following function definition:

#define UNICODEtoANSI(str)   WCHARtoCHAR(str, CP_OEMCP)

LPSTR WCHARtoCHAR(LPWSTR wstr, UINT codePage) {
    int len = (int)wcslen(wstr) + 1;    
    int size_needed = WideCharToMultiByte(codePage, 0, wstr, len, NULL, 0, NULL, NULL);
    LPSTR str = (LPSTR)LocalAlloc(LPTR, sizeof(CHAR) * size_needed);
    WideCharToMultiByte(codePage, 0, wstr, len, str, size_needed, NULL, NULL);
    return str;
}

Unsafe CRT string function calls:

To make the code compile, replace strcpy and strcat with the following calls

strcpy_s(output, sizeof(output), "");

strcat_s(output, RESULT_SIZE, buffer);

Remove redundant null-termination:

Remove in the do-while loop:

buffer[bytesRead] = '\0';

because strcat_s takes care of that.

You could use

 string command = "start /B cmd /c " + myCommand;
 system(command.c_str());

Hopefully this works for you

Related