gpt4 book ai didi

delphi - Windows 上的普通用户可以启动服务吗?

转载 作者:行者123 更新时间:2023-12-03 15:41:13 25 4
gpt4 key购买 nike

我有一个使用 Delphi 创建的服务应用程序,并设法使用提升的权限从另一个 Delphi 应用程序安装它。

该服务设置为以本地系统帐户登录(这是在 Delphi 中创建服务应用程序时的默认帐户)。

我有另一个 Delphi 应用程序,普通用户应该能够启动或停止上述服务。

我的问题是:Windows 允许这样做吗?当我尝试使用 Delphi 中的代码启动服务时,它失败并显示“代码 5。访问被拒绝”。我怎样才能防止这个错误的发生?我希望能够让普通用户运行应用程序(不在管理员模式下,因此不具有提升的权限)来启动/停止服务。这可能吗?如果可能的话怎么办?下面是我的代码:

function ServiceStart(sMachine, sService: string): boolean;
var
schm, schs: SC_Handle;
ss: TServiceStatus;
psTemp: PChar;
dwChkP: DWord; // check point
begin
ss.dwCurrentState := 0;
// connect to the service control manager
schm := OpenSCManager(PChar(sMachine), nil, SC_MANAGER_CONNECT);
// if successful...
if (schm <> 0) then
begin
// open a handle to the specified service
// we want to start the service and query service
// status
schs := OpenService(schm, PChar(sService), SERVICE_START or SERVICE_QUERY_STATUS);
// if successful...
if (schs <> 0) then
begin
psTemp := nil;
if (StartService(schs, 0, psTemp)) then
begin
// check status
if (QueryServiceStatus(schs, ss)) then
begin
while (SERVICE_RUNNING <> ss.dwCurrentState) do
begin
// dwCheckPoint contains a value that the
// service increments periodically to
// report its progress during a
// lengthy operation. Save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of
// time the calling program should wait
// before calling QueryServiceStatus()
// again. Idle events should be
// handled here...
Sleep(ss.dwWaitHint);
if not QueryServiceStatus(schs, ss) then
begin
// couldn't check status break from the
// loop
break;
end;

if ss.dwCheckPoint < dwChkP then
begin
// QueryServiceStatus didn't increment
// dwCheckPoint as it should have.
// Avoid an infinite loop by breaking
break;
end;
end;
end;
end
else
begin

if MessageDlg('Start Service failed. Do you want remove it?',
mtWarning, [mbYes, mbNo], 0) = mrYes then
begin
InstallUninstallService(1);
end;

end;

// close service handle
CloseServiceHandle(schs);
end else RaiseLastOSError;
// close service control manager handle
CloseServiceHandle(schm);
end;
// Return TRUE if the service status is running
Result := SERVICE_RUNNING = ss.dwCurrentState;
end;

最佳答案

默认情况下,您需要具有管理员权限才能启动、停止、安装和删除服务。

您必须安排您的服务公开其自己的 Active 属性,这与 Windows 术语中的“运行”不同。安排它始终以 Windows 方式运行,但当其 Active 属性为 false 时处于惰性状态。

您必须为您的用户应用程序实现一种控制机制。我已经使用命名管道完成了此操作,但还有其他可用的 IPC 方法。

关于delphi - Windows 上的普通用户可以启动服务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7172942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com