【问题标题】:How can i send close command to a CMD process by PID如何通过 PID 向 CMD 进程发送关闭命令
【发布时间】:2017-10-21 19:18:04
【问题描述】:

这个过程是由selenium启动的

所以我无法控制如何启动它

但是,CMD 进程有 X 按钮

我可以通过 PID 以编程方式调用那个 X 按钮吗?

C# 4.6.2 视窗 8.1

我可以终止该进程,但它的效果与单击 X 按钮的效果不同

【问题讨论】:

  • 这肯定和你的其他问题一样,只是包装不同......

标签: c# cmd process command-line-interface pid


【解决方案1】:

这是我使用系统命令 taskkill 的代码的一部分:

//starts a command
public static int RunCommandAndWait(string command, string args)
{
    int result = -1;

    Process p = new Process();
    p.StartInfo.Arguments = args;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.FileName = command;
    p.StartInfo.UseShellExecute = true;

    if (p.Start())
    {
        p.WaitForExit();
        result = p.ExitCode;
    }

    p.Dispose();
    return result;
}

//kills a process using its pid and above method
public static void KillProcessTree(int processId)
{
    RunCommandAndWait("taskkill", String.Format("/pid {0} /f /t", processId));
    try
    {
        Process p = Process.GetProcessById(processId);
        if (p != null)
            KillProcessTree(processId); //this sometimes may be needed
    }catch(Exception)
    {

    }
}

【讨论】:

    【解决方案2】:

    这应该可以解决问题:

    // Close process by sending a close message to its main window.
    myProcess.CloseMainWindow();
    // Free resources associated with process.
    myProcess.Close();
    

    【讨论】:

    • 您是否检查过您的进程是否有任何子进程阻止它关闭?通过调用 CloseMainWindow 退出进程的请求不会强制应用程序退出。应用程序可以在退出前要求用户验证,也可以拒绝退出。如link 中所述
    • CloseMainWindow 仅在进程有窗口时有效。此过程没有窗口。它从命令行开始。
    【解决方案3】:

    你需要找到windowsend message到窗口

    SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);

    喜欢描述here

    【讨论】:

    • 我无法访问除 PID 以外的进程
    • 打扰一下 - 您可以访问此系统上的 Win32API 吗?
    • 我看到了,让我们试试
    • 一般来说,您不需要访问其他进程,您只需要使用来自一个系统 dll (user32.dll) 的功能的权限——这就足够了
    猜你喜欢
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2011-11-03
    • 2014-07-31
    • 2013-11-05
    相关资源
    最近更新 更多