您可以在 ExecuteCommand
方法中添加一个关闭窗体的逻辑判断。具体来说,您可以使用 FormClosing
事件来处理用户尝试关闭窗体的情况。在这个事件中,您可以询问用户是否确定要关闭窗体,并相应地处理命令的执行状态。
下面是经过修改后的代码示例:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CmdExecutor
{
public partial class MainForm : Form
{
private Process cmdProcess; // 用于保存当前执行的cmd进程
public MainForm()
{
InitializeComponent();
InitializeComboBox();
}
private void InitializeComboBox()
{
// 添加可选的CMD命令
comboBoxCommands.Items.Add("ping");
comboBoxCommands.Items.Add("ipconfig");
comboBoxCommands.Items.Add("mkdir");
}
private void buttonExecute_Click(object sender, EventArgs e)
{
// 获取选中的命令和用户输入的参数
string selectedCommand = comboBoxCommands.SelectedItem?.ToString();
string additionalParams = textBoxCommandInput.Text.Trim();
// 检查是否选择了命令以及额外参数是否输入
if (string.IsNullOrEmpty(selectedCommand))
{
MessageBox.Show("请从下拉列表中选择一个CMD命令!");
return;
}
if (string.IsNullOrEmpty(additionalParams))
{
MessageBox.Show("请输入有效的额外参数!");
return;
}
// 组合完整的CMD命令,以空格分隔
string command = $"{selectedCommand} {additionalParams}".Trim();
ExecuteCommand(command);
}
private async void ExecuteCommand(string command)
{
textBoxLog.Clear();
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
cmdProcess = new Process { StartInfo = processStartInfo };
cmdProcess.OutputDataReceived += (sender, args) =>
AppendLog(args.Data);
cmdProcess.ErrorDataReceived += (sender, args) =>
AppendLog(args.Data);
cmdProcess.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await Task.Run(() =>
{
process.StandardInput.WriteLine(command);
process.StandardInput.WriteLine("exit");
process.WaitForExit();
});
}
private void AppendLog(string message)
{
if (!string.IsNullOrEmpty(message))
{
if (textBoxLog.InvokeRequired)
{
textBoxLog.Invoke(new Action<string>(AppendLog), message);
}
else
{
textBoxLog.AppendText(message + Environment.NewLine);
textBoxLog.ScrollToCaret();
}
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (cmdProcess != null && !cmdProcess.HasExited)
{
var result = MessageBox.Show("正在执行CMD命令,确认要关闭吗?", "确认", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
// 终止进程并关闭窗体
cmdProcess.Kill();
e.Cancel = false; // 允许关闭窗体
}
else
{
e.Cancel = true; // 取消关闭操作
}
}
}
}
}
修改说明:
新字段:在
MainForm
类中添加了一个私有字段cmdProcess
来保存当前正在执行的 CMD 进程。更新
ExecuteCommand
方法:将启动的进程存储在cmdProcess
中,以便后续引用。重写
OnFormClosing
方法:- 在窗口关闭时检查 CMD 进程是否仍在运行。
- 如果是,则显示一个确认对话框,让用户决定是否要终止进程并关闭窗口。
- 根据用户选择,通过设置
e.Cancel
属性来控制窗口是否继续关闭。
这样,当您尝试关闭窗口时,如果 CMD 命令仍在运行,会提示用户进行确认。如果用户选择“是”,将终止该进程并关闭窗口;如果选择“否”,则继续执行 CMD 命令。
内容由零声教学AI助手提供,问题来源于学员提问