[英]How to close Console window from windows form applications in C#?
I have ac# program and currently I run 2 windows, the first one is form window and and the second one is console window for debugging.我有 ac# 程序,目前我运行 2 个窗口,第一个是表单窗口,第二个是用于调试的控制台窗口。
The console window created accoeding the following:创建的控制台窗口如下:
Create a Windows Form project... Then: Project Properties -> Application -> Output Type -> Console Application
How can I close the console window from the form by button click?如何通过单击按钮从表单关闭控制台窗口?
Edit:编辑:
I tried to do the following but this is close the form window only..我尝试执行以下操作,但这只是关闭表单窗口..
private void button1_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
}
Edit 2: the previous code works only before the following code performed.编辑 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。
In the Dispose function of the Form you can write:在 Form 的 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.