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

Apr 012008
 

I’ve seen people asking this question number of times, so for those people here is the answer…

When creating a process via CreateProcess we’ve got to give a STARTUPINFO structure as a parameter which specifies startup options for a process.

Set dwFlags member to STARTF_USESHOWWINDOW to indicate that we will be using wShowWindow member of STARTUPINFO. Then set wShowWindow to SW_HIDE to start a process as hidden.

To start a process as maximized use SW_MAXIMIZE, to start as minimized use SW_MINIMIZE, to start as restored use SW_RESTORE. Look up ShowWindow MSDN to for other options!

STARTUPINFO StartInfo = { 0 };
StartInfo.cb = sizeof( StartInfo );

// Use showwindow field of this structure
StartInfo.dwFlags = STARTF_USESHOWWINDOW;
StartInfo.wShowWindow = SW_HIDE;

PROCESS_INFORMATION pi = { 0 };
CreateProcess( _T( "C:\\windows\\Notepad.exe" ),
               NULL,
               NULL,
               NULL,
               FALSE,
               0,
               NULL,
               NULL,
               &StartInfo,
               &pi );

You won’t see notepad running since it’s hidden, open task manager to see notepad running!