winapi - 无法通过服务运行 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
. 但是,弹出窗口没有出现。无论我尝试哪个命令,它都不起作用。
我确实进入并勾选了“允许服务与桌面交互”选项,但不幸的是这也不起作用。
解决方案
推荐阅读
- python - 在 Python HTTP 客户端 urllib3 和请求之间进行选择
- phpunit - 无法在 phpunit 中运行 Drupal::service()
- android - 即使在模拟器上,“adb root”命令也会返回“adbd 无法在生产版本中以 root 身份运行”?
- javascript - AJAX - “POST”请求首先执行“GET”请求,然后是“POST”请求
- java - ExoPlayer 流mp3
- javascript - Q. 如何查询一个模型,在一对多的关系中,返回关联的记录?
- powerpc - 在 trace32 中更改新版本的地址位置
- javascript - 如何在 Vue.js 中获取对象数组中的键
- operating-system - Xinu - 为暂停状态进程设置新的优先级
- apache - 没有名为 'encodings' 的模块,apache2 + wsgi /+virtualenv