Program Resource

Resource libraries for programmers and developers

When developing simple tool or doing automation, calling shell command might be easy and fast.

However, calling “cmd /c” with ShellExecute brings up shell window, and might return to code before command completes.

In such case, use CreateProcess to call cmd. You can hide shell window and wait for process to complete, and even get return value by using CreateProcess API.

Below is simple sample code for calling takeown command, which is a command to take ownership of system files which can’t be modified even with Administrator privilege.

BOOL runcmdproc(CString cmd)
{
	STARTUPINFO  si;
	PROCESS_INFORMATION pi;
	DWORD ret;
	HANDLE hWndmain;

	memset(&si, 0, sizeof(si));
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;

	ret = CreateProcess(NULL, cmd.GetBuffer(0), NULL, NULL, FALSE,
                      CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS,
                      NULL, NULL, &si, &pi);
	hWndmain = pi.hProcess;
	CloseHandle(pi.hThread);
	WaitForSingleObject(hWndmain, INFINITE);
	CloseHandle(hWndmain);
	return (ret);
}

BOOL TakeOwn(CString filename)
{
	CString param;
	param.Format("cmd /c takeown /f \"%s\" && icacls \"%s\" /grant administrators:F",filename,filename);
	if (runcmdproc(param))
		return TRUE;
	else
		return FALSE;
}

This post is also available in: Japanese

Leave a Reply

Your email address will not be published. Required fields are marked *


*