Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmd commands in ShellExecute [closed]

I am trying in execute netsh winsock reset catalog command in command prompt from an elevated(has admin privileage) c++ application.

HINSTANCE retVal = ShellExecute(NULL, "open", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL); 

It just opens the command prompt and nothing else happens. I have tried

HINSTANCE retVal = ShellExecute(NULL, "runas", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL); 

and

HINSTANCE retVal = ShellExecute(NULL, "open", "cmd", " netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL); 
like image 478
Akhil V Suku Avatar asked Sep 15 '25 10:09

Akhil V Suku


2 Answers

Switch character was causing the problem. It worked when switch character was changed from \c to /c.

From

HINSTANCE retVal = ShellExecute(NULL, "open", "cmd", "\c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);

to

HINSTANCE retVal = ShellExecute(NULL, "open", "cmd", "/c netsh winsock reset catalog > CUninstall.log", NULL, SW_NORMAL);
like image 149
Akhil V Suku Avatar answered Sep 18 '25 08:09

Akhil V Suku


It took some trial and error to find the optimal way, so I would like to share my solution. Put aside my recomendation to use Asynchronized calls, here is my DoRun() function:

BOOL DoRun(WCHAR *command)
{
    BOOL Result = FALSE;
    DWORD retSize;
    LPTSTR pTemp = NULL;
    TCHAR Command[BUFSIZE] = L"";
    if (!(DeleteFile(RESULTS_FILE)))
    {
        //return L"Can't delete previous results";
    }
    _tcscpy_s(Command, L"/C ");
    _tcscat_s(Command, command);
    _tcscat_s(Command, L" >");
    _tcscat_s(Command, RESULTS_FILE);
    wprintf(L"Calling:\n%s\n", Command);
    Result = (BOOL) ShellExecute(GetActiveWindow(), L"OPEN", L"cmd", Command, NULL, 0L);
    if(!Result)
    {
        retSize = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_ARGUMENT_ARRAY,
            NULL,
            GetLastError(),
            LANG_NEUTRAL,
            (LPTSTR)&pTemp,
            0,
            NULL);
        MessageBox(NULL,pTemp,L"Error",MB_OK);
    }
    return Result;
}
like image 25
Michael Haephrati Avatar answered Sep 18 '25 09:09

Michael Haephrati