使用控制台应用程序卡在 C# 中的 GenerateConsoleCtrlEvent

Stuck on GenerateConsoleCtrlEvent in C# with console apps(使用控制台应用程序卡在 C# 中的 GenerateConsoleCtrlEvent)

本文介绍了使用控制台应用程序卡在 C# 中的 GenerateConsoleCtrlEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难让这个工作,希望你们中的一个人以前做过.

I'm having the hardest time trying to get this to work, hoping one of you has done this before.

我有一个 C# 控制台应用程序,它正在运行一个继承其控制台的子进程.我希望将外部应用程序捕获的 ctrl-c 传递给内部应用程序,以便它有机会很好地关闭.

I have a C# console app that is running a child process which inherits its console. I want a ctrl-c caught by the outer app to be passed along to the inner app so that it can have a chance to shut down nicely.

我有一些非常简单的代码.我启动一个进程,然后使用 WaitForExit(10) 轮询它.我还注册了一个 CancelKeyPress 处理程序,它在触发时将 bool 设置为 true.轮询循环也会检查这一点,当它为真时,它会调用 GenerateConsoleCtrlEvent()(我已通过 pinvoke 映射).

I have some very simple code. I start a Process, then poll it with WaitForExit(10). I also have a CancelKeyPress handler registered, which sets a bool to true when it fires. The polling loop also checks this, and when it's true, it calls GenerateConsoleCtrlEvent() (which I have mapped through pinvoke).

我已经尝试了很多参数组合到 GenerateConsoleCtrlEvent().第一个参数为 0 或 1,第二个参数为 0 或子进程的 ID.似乎没有任何效果.有时我得到一个错误的回复并且 Marshal.GetLastWin32Error() 返回 0,有时我得到一个真实的回复.但没有一个会导致子应用收到 ctrl-c.

I've tried a lot of combinations of params to GenerateConsoleCtrlEvent(). 0 or 1 for the first param, and either 0 or the child process's ID for the second param. Nothing seems to work. Sometimes I get a false back and Marshal.GetLastWin32Error() returns 0, and sometimes I get true back. But none cause the child app to receive a ctrl-c.

为了绝对肯定,我编写了一个测试 C# 应用程序作为子应用程序,它会打印出它正在发生的事情,并验证在它运行时手动键入 ctrl-c 确实会导致它退出.

To be absolutely sure, I wrote a test C# app to be the child app which prints out what's going on with it and verified that manually typing ctrl-c when it runs does properly cause it to quit.

我已经为此苦苦思索了几个小时.谁能给我一些关于该去哪里的指示?

I've been banging my head against this for a couple hours. Can anyone give me some pointers on where to go with this?

推荐答案

不太确定这是一个好方法.这仅适用于使用 CreateProcess() 的 CREATE_NEW_PROCESS_GROUP 标志创建的子进程.然而,System.Diagnostics.Process 类不支持这一点.

Not so sure this is a good approach. This only works if the child process is created with the CREATE_NEW_PROCESS_GROUP flag for CreateProcess(). The System.Diagnostics.Process class however does not support this.

考虑使用 Main() 方法的返回值.Windows SDK 中已经为 Ctrl+C 中止定义了一个唯一值,即 STATUS_CONTROL_C_EXIT 或 0xC000013A.父进程可以从 Process.ExitCode 属性中获取该返回码.

Consider using the return value from the Main() method. There is already a unique value defined in the Windows SDK for Ctrl+C aborts, STATUS_CONTROL_C_EXIT or 0xC000013A. The parent process can get that return code from the Process.ExitCode property.

这篇关于使用控制台应用程序卡在 C# 中的 GenerateConsoleCtrlEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用控制台应用程序卡在 C# 中的 GenerateConsoleCtrlEvent

基础教程推荐