如何在c#中给进程赋予ctrl + c?

问题描述 投票:0回答:2

我正在尝试创建一个后台工作者来创建一个进程,该进程会发出一些 ovf 命令。在这期间,我尝试通过发送 ctrl+c 来中止操作。该网站上也有类似的问题,但都没有解决问题。

private void DeployOVF()
{
    p = new Process();
    ProcessStartInfo pi = new ProcessStartInfo("ovftool.exe", "--machineOutput "+ FileName + " vi://uname:pwd@Ip Address");
    pi.UseShellExecute = false;
    pi.RedirectStandardOutput = true;
    pi.RedirectStandardInput = true;
    pi.RedirectStandardError = true;
    pi.CreateNoWindow = true;
    p.StartInfo = pi;
    p.Start();
    StreamReader myStreamReader = p.StandardOutput;
    string myString;
    bool progressStarted = false;
    while ((myString = myStreamReader.ReadLine()) != null)
    {
        //Logic to display the progress
    }
    p.WaitForExit();
    p.Close();
}

这是我发送 ctrl+c 来中止进度的地方,

private void button1_Click(object sender, EventArgs e)
{
    p.StandardInput.Write("\x3");
    p.StandardInput.Close();
}
c# .net multithreading command-line vmware
2个回答
1
投票

如果进程正在响应(即其前台线程正在响应信号),那么您应该使用:

p.CloseMainWindow();

如果没有,您应该能够使用

Kill
:

中止该过程(不干净)
p.Kill();

//Then wait for the process to end
p.WaitForExit();
p.Close();

0
投票

我不知道这会有多大帮助,因为我不熟悉

ofv
,但也许可以尝试MedallionShell。它具有多平台实现,支持将
Ctrl + C
信号发送到应用程序。

var command = Command.Run("dotnet", "run", "--project", "C:\MyRepo\MyProj\MyProj.csproj");

// Business logic here...

await command.TrySignalAsync(CommandSignal.ControlC);

我尝试使用一个 ASP.Net Core 应用程序向另一个 ASP.Net Core 应用程序发送

Ctrl + C
信号,并且
MedallionShell
非常有效!

© www.soinside.com 2019 - 2024. All rights reserved.