您上面给我的代码会报出D:\QtProject\DataServer\main.cpp:50: error: invalid conversion from 'const wchar_t*' to 'LPWSTR {aka wchar_t*}' [-fpermissive] if (!CreateProcessAsUser(hToken, NULL, qApp->applicationFilePath().toStdWString().data(), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { ^ 错误,请修复后给我完整代码
时间: 2024-01-13 12:02:48 浏览: 160
抱歉,因为 CreateProcessAsUser 函数需要的是非常量的 LPWSTR 类型参数,所以需要进行强制类型转换。修复后的代码如下:
```
#include "mainwindow.h"
#include <QApplication>
#include <windows.h>
#include <wtsapi32.h>
#pragma comment(lib, "Wtsapi32.lib")
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
HANDLE hToken = NULL;
DWORD dwSessionId = WTSGetActiveConsoleSessionId();
if (!WTSQueryUserToken(dwSessionId, &hToken)) {
QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("获取用户令牌失败!"));
return -1;
}
HANDLE mutex = ::CreateMutex(Q_NULLPTR, true, (LPCWSTR)qApp->applicationName().toStdWString().c_str());
if (GetLastError() == ERROR_ALREADY_EXISTS) {
QMessageBox warningBox(QMessageBox::Warning, QStringLiteral("警告"), QStringLiteral("程序[文本数据同步服务端]只能运行一个!"));
warningBox.setButtonText(QMessageBox::Ok, QStringLiteral("确定"));
warningBox.setStandardButtons(QMessageBox::Ok);
warningBox.exec();
::CloseHandle(mutex);
return 0;
}
else {
::ReleaseMutex(mutex);
}
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.lpDesktop = (LPWSTR)L"winsta0\\default";
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
if (!CreateProcessAsUser(hToken, NULL, (LPWSTR)qApp->applicationFilePath().toStdWString().data(), NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) {
QMessageBox::warning(nullptr, QStringLiteral("错误"), QStringLiteral("创建进程失败!"));
CloseHandle(hToken);
return -1;
}
CloseHandle(hToken);
return 0;
}
```
在调用 CreateProcessAsUser 函数时,我们使用 `(LPWSTR)` 进行强制类型转换,将 `qApp->applicationFilePath().toStdWString().data()` 的类型从 const wchar_t* 转换为 LPWSTR,以消除类型不匹配的错误。
阅读全文