Feb 282009
 

What I mean is, if we type ‘Start->Run->Cmd.exe’ then command prompt directory is our user directory, for e.g. ‘c:\Documents and settings\Nibu’. So how can we do this through code is the question? Directory that we see when command prompt starts up is called working directory. Every executable in windows has a working directory which is in fact the first location it searches for a file. So using ‘CreateProcess’ it’s possible to set a working directory, since it has a function parameter which corresponds to this feature. So here is a simple dedicated function which sets working directory for command prompt…

void OpenCmdInDir( LPCTSTR lpctszDir )
{
   STARTUPINFO StrInf =  { 0 };
   StrInf.cb = sizeof( StrInf );

   PROCESS_INFORMATION ProcInfo = { 0 };
   VERIFY( CreateProcess( NULL, "C:\\Windows\\system32\\cmd.exe", NULL, NULL, FALSE, 0, 0, lpctszDir, &StrInf, &ProcInfo ));

   // Closing handles since not needed further
   CloseHandle( ProcInfo.hProcess );
   CloseHandle( ProcInfo.hThread );
}

// Usage
OpenCmdInDir( _T( "C:\\Windows\\System32\\Drivers" ));

See screenshot…

Command prompt working directory

Command prompt working directory

  One Response to “Starting command prompt in a particular directory”

  1. Old post, I know but ….

    The example you provide seems to work fine with cmd and other console applications.
    However, for GUI programs, the IpCurrentDirectory parameter you use in your example seems not taken into consideration. I have yet to find a work-around for this…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.