ShellExecute具有特定工作目录的cmd提示符

时间:2016-06-25 23:20:29

标签: c++ windows visual-c++ cmd

我想在Windows中将提升的命令提示符启动到特定的工作目录。例如,我试过这个:

ShellExecute(
    hWnd,
    L"runas",
    L"cmd.exe",
    NULL,
    m_szSelectedFile,
    SW_SHOW
);

m_szSelectedFile = L"C:\\Users\\User\\Desktop"

ShellExecute记录为

HINSTANCE ShellExecute(
  _In_opt_ HWND    hwnd,
  _In_opt_ LPCTSTR lpOperation,
  _In_     LPCTSTR lpFile,
  _In_opt_ LPCTSTR lpParameters,
  _In_opt_ LPCTSTR lpDirectory,
  _In_     INT     nShowCmd
);

不幸的是,它总是发布到C:\WINDOWS\system32。我做错了什么?

2 个答案:

答案 0 :(得分:6)

Microsoft在Windows 8中将此添加为安全功能。每当cmd.exe检测到它正在升级时,它会忽略其启动参数并始终在%SystemRoot%\System32中启动。您无法覆盖此行为。

但是,您可以将目录更改为提示中的第一个命令。为此,请将lpFile正常设置为"cmd.exe"。然后将lpParameters设置为"/k cd /d d:\your\path"。 CMD将在启动时立即更改目录,然后保持打开状态以进一步执行命令。

答案 1 :(得分:-1)

我测试了解决方案,但没有一个能解决问题,但最终我搜索了一个解决方案:

//-----------------------------------------------------------------------
    TCHAR szPath[_MAX_PATH];
    VERIFY(::GetModuleFileName(AfxGetApp()->m_hInstance, szPath, _MAX_PATH));
    CString csPath(szPath);
    CString csParameter;
    int nIndex = csPath.ReverseFind(_T('\\'));
    if (nIndex > 0)
    {
        csPath = csPath.Left(nIndex);
    }
    else
    {
        csPath.Empty();
    }

    if (IsWow64())
    {
        m_StatusText += "The process is running under Windows 64\r\n";
        UpdateData(false);
        csPath += "\\driverKey64";
        csParameter += "/c install.cmd";
        if (ShellExec(csParameter, csPath, true))
        {
            m_StatusText += "Drivers Installed\r\n";
        }
        else
        {
            m_StatusText += "Drivers were not Installed\r\n";
        }
        UpdateData(false);
    }

int CDriverKeyDlg::ShellExec(LPCTSTR lpApplicationName,LPCTSTR lpDirectory, bool bWait)
{
    int iReturn = -1;
    SHELLEXECUTEINFO shExInfo = { 0 };
    shExInfo.cbSize = sizeof(shExInfo);
    shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    shExInfo.hwnd = 0;
    shExInfo.lpVerb = _T("runas");          // Operation to perform
    shExInfo.lpFile = _T("cmd.exe");        // Application to start    
    shExInfo.lpParameters = lpApplicationName;    // Additional parameters
    shExInfo.lpDirectory = lpDirectory;
    shExInfo.nShow = SW_SHOW;
    shExInfo.hInstApp = 0;

    if (ShellExecuteEx(&shExInfo))
    {
        if (bWait)
        {
            WaitForSingleObject(shExInfo.hProcess, INFINITE);
        }
        iReturn = 1;
    }
    CloseHandle(shExInfo.hProcess);
    return iReturn;
}

//-----------------------------------------------------------------------

文件“ install.cmd”是批处理文件,并存储在以下文件夹中:路径可执行模块+“ driverKey64”,此示例的驱动程序存储在此文件夹中,并且从该文件夹中批量执行而不会出错。 在Windows 64位7、8、10,xp中进行的测试与32位类似...已编码MFC C ++

致谢