改变 createprocess 启动的子进程独立控制台标题
时间: 2024-11-12 12:35:07 浏览: 16
在Windows系统中,如果你想要改变由`CreateProcess`函数启动的子进程的控制台标题,可以利用额外的一些API调用来获取和设置进程的控制台会话。下面是一个简单的C++示例:
```cpp
#include <windows.h>
#include <string>
#include <iostream>
// 创建新进程并设置其标题
std::string ChangeConsoleTitle(const char* processName, const char* title) {
STARTUPINFO si = { sizeof(STARTUPINFO), };
PROCESS_INFORMATION pi;
// 获取当前控制台会话ID
DWORD sessionId = GetCurrentProcessId();
// 创建新进程
if (!CreateProcess(processName, nullptr, nullptr, nullptr, FALSE,
CREATE_NEW_CONSOLE | DETACHED_PROCESS, nullptr, nullptr, &si, &pi)) {
return "Failed to create process.";
}
// 打开子进程的控制台
HANDLE hConsole = OpenProcessToken(pi.hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, nullptr);
// 如果打开成功
if (hConsole != nullptr) {
// 获取控制台窗口句柄
HCONSOLE hConsoleWindow = FindWindowA("ConsoleWindowClass", nullptr);
if (hConsoleWindow != nullptr) {
// 尝试调整权限以允许修改控制台标题
LUID luid;
LookupPrivilegeValueA(NULL, SE_SET_NAME_TOKEN_NAME, &luid);
TOKEN_PRIVILEGES tp = { 1, { luid }, FALSE };
AdjustTokenPrivileges(hConsole, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
// 设置新标题
if (SetConsoleTitle(title, hConsoleWindow)) {
CloseHandle(hConsole);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return "Title updated successfully.";
} else {
CloseHandle(hConsole);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return "Failed to update title.";
}
} else {
CloseHandle(hConsole);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return "Failed to find console window.";
}
} else {
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return "Failed to open process token.";
}
}
int main() {
std::string result = ChangeConsoleTitle("notepad.exe", "Modified Process Title");
std::cout << "Result: " << result << std::endl;
return 0;
}
```
请注意,这需要管理员权限,并且不是所有操作都保证能成功,特别是对已存在的控制台窗口进行标题更改。
阅读全文