【发布时间】:2019-07-03 04:23:40
【问题描述】:
我想以提升的权限从我的 FMX 应用程序(在 Win32 上)生成一个批处理文件。从 Remy 在 ShellExecute 底部of this thread 的回答中,我找到了如何启动批处理文件。现在,我不知道如何以提升的权限启动它。以下是我的代码:
String Prog = "c:\\Users\\rwp\\Desktop\\test.bat";
int nErrorCode = (int) ShellExecute(NULL, L"runas", Prog.c_str(), NULL, NULL, SW_SHOWNORMAL);
if (nErrorCode <= 32) {
ShowMessage("an error occured");
}
在阅读this 后,我为第二个参数添加了“runas”,但无济于事。手动运行批处理文件(右键单击并以管理员身份运行)有效。这是批处理文件 fyi 的内容(只是系统映像的一部分):
c:\Windows\system32\wbAdmin.exe start backup -backupTarget:D: -include:C: -allCritical -quiet
我如何以管理员身份 ShellExecute 这个批处理文件?
更新 1:我正在尝试根据 Remy 的建议使用 CreateProcess。这是我的代码(基于this example):
//Code is inside a __fastcall button click
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.lpReserved = NULL;
siStartInfo.lpReserved2 = NULL;
siStartInfo.cbReserved2 = 0;
siStartInfo.lpDesktop = NULL;
siStartInfo.dwFlags = 0;
// String strCmdLine = "C:\\Users\\rwpatter\\Desktop\\test.bat";
String strCmdLine = "C:\\Windows\\System32\\wbAdmin.exe start backup -backupTarget:T: -include:C: -allCritical -quiet";
// Create the child process.
int rtrn = CreateProcess(
NULL,
strCmdLine.c_str(),
NULL, // process security attributes
NULL, // primary thread security attributes
0, // handles are inherited
0, // creation flags
0, // use parent's environment
0, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// Wait for the processs to finish
DWORD rc = WaitForSingleObject(
piProcInfo.hProcess, // process handle
INFINITE);
ShowMessage(IntToStr(rtrn));
如果我如图所示运行它(右键单击 exe 并以管理员身份运行),它会返回 0,这意味着它是 failed。如果我通过将 wbAdmin 命令行放在 test.bat 文件中来运行它(请参阅代码中 String strCmdLine 正上方的注释行),则 CreateProcess 返回 1(成功)但 wbAdmin 仍然没有运行。它闪现了一个 DOS 窗口,我捕获了它,如下图所示。它在标题栏中显示东方字符,并表示无法识别为内部或外部命令。但是,如果我直接(提升)运行那个 test.bat,它运行 wbAdmin 没问题。
关于什么是错的任何想法?除了我显然是无知的。 (附言我将在此之后在 ShellExecute 上测试 Golvind 的答案......)
【问题讨论】:
-
由于
bat由一个命令组成,我将直接使用CreateProcess()运行wbAdmin.exe,如果它还没有自行提升运行,那么让您的应用程序运行提升在调用该命令之前。 -
不是直接的答案,但您可以从那里获得灵感:github.com/TurboPack/DOSCommand
标签: winapi firemonkey c++builder