如何在 C# 中从 Windows 窗体应用程序关闭控制台窗口?



我有一个 c# 程序,目前我运行 2 个窗口,第一个是窗体窗口,第二个是用于调试的控制台窗口。

创建的控制台窗口包含以下内容:

Create a Windows Form project...
Then: Project Properties -> Application -> Output Type -> Console Application

如何通过单击按钮从窗体关闭控制台窗口?

编辑:

我尝试执行以下操作,但这仅关闭表单窗口。

private void button1_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
}

编辑 2: 前面的代码仅在执行以下代码之前有效。

using (process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.StartInfo.WorkingDirectory = @"C:";
process.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
// Redirects the standard input so that commands can be sent to the shell.
process.StartInfo.RedirectStandardInput = true;
// Runs the specified command and exits the shell immediately.
//process.StartInfo.Arguments = @"/c ""dir""";
process.OutputDataReceived += ProcessOutputDataHandler;
process.ErrorDataReceived += ProcessErrorDataHandler;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();

// Send a directory command and an exit command to the shell
process.StandardInput.WriteLine("cd " + currentPath);
process.StandardInput.WriteLine("ibt -mic");
}

您可以使用 System.Diagnostics.Process 来启动和停止另一个 exe。

在表单的 Dispose 函数中,您可以编写:

protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
//Get the process Id
var pr = Process.GetCurrentProcess();
//Look for the parent ID
using (var query = new ManagementObjectSearcher(
"SELECT * " +
"FROM Win32_Process " +
"WHERE ProcessId=" + pr.Id))
{
var dadP = query
.Get()
.OfType<ManagementObject>()
.Select(p => Process.GetProcessById((int)(uint)p["ParentProcessId"]))
.FirstOrDefault();
//Kill the parent
dadP.CloseMainWindow();
}            
}

最新更新