如何从cmd生成的弹出框中获取文本?

S. *_* M. 1 c# windows cmd winforms

我正在尝试获取 Windows 的激活状态。我有这个代码:

 Process proc = new Process();


 proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
 proc.StartInfo.FileName = "cmd.exe";
 proc.StartInfo.Arguments = "/C slmgr /xpr";
 proc.StartInfo.UseShellExecute = false;
 proc.StartInfo.CreateNoWindow = true;
 proc.StartInfo.RedirectStandardOutput = true;
 proc.StartInfo.RedirectStandardInput = true;
 proc.Start();

 string x = "";

 while (!proc.HasExited)
 {
     x += proc.StandardOutput.ReadToEnd();
 }

 return x;
Run Code Online (Sandbox Code Playgroud)

有些人可能知道,命令“slmgr /xpr”会弹出一个窗口,通知您 Windows 激活状态。

执行此代码,我得到弹出框(并且“x”为空)。我想要的是获取其中的文本(以便它显示在我表单的标签上)。我想知道是否有任何方法可以从出现的弹出窗口中提取文本,在这种情况下,它会类似于“机器已永久激活”。

有什么简单的方法可以实现这一目标吗?

Ale*_* K. 5

slmgr实际上是一个 VBScript 文件而不是可执行文件,当您运行它时,它将默认使用WScript运行时,该运行时用于窗口脚本并使用消息框作为默认输出。如果更改为CScript,您将获得控制台输出:

proc.StartInfo.FileName = "cscript.exe";
proc.StartInfo.Arguments = "/nologo \"" + Path.Combine(Environment.SystemDirectory, "slmgr.vbs") + "\" /xpr";
Run Code Online (Sandbox Code Playgroud)

然后您可以捕获此内容:从 .NET 应用程序捕获控制台输出 (C#)

您还可以查看脚本文件内部,看看它在做什么并在代码中重新实现它(ymmv)。