首页 > 解决方案 > 无法通过服务运行 cmd.exe。似乎没有命令在工作

问题描述

我正在尝试调用一个非常具体的命令,我可以使用服务通过 cmd 调用该命令。我正在使用一项服务,因为我希望每次登录时都运行这个命令,所以我继承自ServiceBase.

class Program
{
    static void Main(string[] args)
    {
        ServiceBase.Run(new RestartService());
    }
}

public class RestartService : ServiceBase
{
    public RestartService()
    {
        CanHandleSessionChangeEvent = true;
    }

    protected override void OnStart(string[] args)
    {
        Log("Starting");
        base.OnStart(args);
    }

    protected override void OnSessionChange(SessionChangeDescription changeDescription)
    {

        Log($"Session was changed: {changeDescription.Reason}");

        if (changeDescription.Reason == SessionChangeReason.SessionLogon || changeDescription.Reason == SessionChangeReason.SessionUnlock)
        {
            Log("Logon/unlock detected");

            try
            {
                var psi = new ProcessStartInfo()
                {
                    FileName = "C:\\Windows\\system32\\cmd.exe",
                    Arguments = "/c msg %username% hello",
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    RedirectStandardInput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                var p = Process.Start(psi);

                string result = p.StandardOutput.ReadToEnd();

                Log(result);
            }
            catch (Exception e)
            {
                Log($"ERROR: {e}");
            }
        }

        base.OnSessionChange(changeDescription);
    }

    public static void Log(string logMessage)
    {
        using (StreamWriter w = File.AppendText("C:\\Users\\username\\Desktop\\log.txt"))
        {
            w.Write("\r\nLog Entry : ");
            w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
            w.WriteLine("  :");
            w.WriteLine($"  :{logMessage}");
            w.WriteLine("-------------------------------");
        }
    }
}

我也尝试过使用:

[DllImport("msvcrt.dll")]
public static extern int system(string format);

然后打电话system("msg %username% hello"),但不幸的是这也不起作用。

当我打开 log.txt 文件时,我可以看到:

Log Entry : 12:29:44 PM Tuesday, September 15, 2020
  :
  :Session was changed SessionLock
-------------------------------

Log Entry : 12:29:45 PM Tuesday, September 15, 2020
  :
  :Session was changed SessionUnlock
-------------------------------

Log Entry : 12:29:45 PM Tuesday, September 15, 2020
  :
  :Logon/unlock detected
-------------------------------

Log Entry : 12:29:45 PM Tuesday, September 15, 2020
  :
  :
-------------------------------

所以我锁定 PC,解锁 PC,然后调用cmd.exe /c msg %username% hello. 但是,弹出窗口没有出现。无论我尝试哪个命令,它都不起作用。

我确实进入并勾选了“允许服务与桌面交互”选项,但不幸的是这也不起作用。

标签: winapi.net-corewindows-services

解决方案


推荐阅读