c++ - 使用 CreateProcess 函数

标签 c++ windows winapi

我正在尝试使用 Microsoft Visual Studio Express 2013 for Windows Desktop 在 c++ 中创建类似于 cmd 的东西,我的功能之一应该通过键入“skype.exe”来启动类似打开 skype 的进程。我在互联网上搜索并找到了应该为我完成这项工作的 CreateProcess 函数。当我创建一个函数来接收我创建的名为 Line 的类值(类的名称,但它并不是真正的 metter)并以如下所示的方式使用 CreateProcess 函数时,我必须输入我的 cmd“开始skype.exe”,但我希望它像在常规 cmd 中一样工作,只写“skype.exe”,我该怎么做? (l.parameter 只是一个包含单词 skype 的字符串)

void execute(Line l){

STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
LPSTR s = const_cast<char *>(l.parameter.c_str());
if (!CreateProcess(NULL, s, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    printf("CreateProcess failed (%d).\n", GetLastError());
    return;
}

// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);

// Close process and thread handles. 
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);}

最佳答案

首先是:

LPSTR s = const_cast<char *>(l.parameter.c_str());

是个坏主意,CreateFile出于某种原因接受 lpCommandLine 非 const 缓冲区 - 它可能会修改它:

The system adds a terminating null character to the command-line string to separate the file name from the arguments. This divides the original string into two strings for internal processing.

所以你应该传递一个数组,例如:

TCHAR szCmd[MAX_PATH] = {0};

那么对于您的问题,如果“启动 skype.exe”对您有效并且您只想在命令行输入 skype.exe - 那么为什么不连接字符串呢?例如:

_tcscat(szCmd, _T("start "));
_tcscat(szCmd, parameter.c_str());

并将 szCmd 传递给 CreateProcess

问题是你是否使用 UNICODE 构建,如果是,那么确保参数是 std::wstring,否则如果你使用非 UNICODE 构建(看起来是这样),那么 std::string 就可以了。

关于c++ - 使用 CreateProcess 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754174/

相关文章:

c++ - 具有 DirectX 桌面框架的消费者-生产者线程

c++ - 未捕获 WM_PAINT 中的访问冲突

windows - 使用 Windows API 在 Rust 中创建弹出窗口

c++ - 纯虚拟类和集合( vector ?)

c# - Windows 服务更改/删除注册表值

c++ - 子进程为 cmd 时 GenerateConsoleCtrlEvent 崩溃

c++ - CreateMutex、OpenMutex 和进程同步

c# - 工作 C# 示例 : Writing & Reading NTFS Alternate Data Stream Under Win7 64 bit

c++ - goroutines 和 boost.fiber 之间的区别

c++ - 在使用 C++ 的 win32 GUI 编程中,如何在 TreeViewCtrl 的根项之前添加扩展按钮?