C#中winform窗体如何嵌入cmd命令窗口

时间:2021-07-31 06:50:35

解决方法一:

  自己放一个文本框,改成黑色,然后输入命令,执行时,你Process.Start cmd ,此时CMD窗口不显示,然后,将CMD的返回值,再取出来,设回文本框。

  如何用这种方法实时获取cmd返回的数据,简单实现如下

     private void OutPutForm_Shown(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
process = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.Start();//启动程序
process.BeginOutputReadLine();
}
private void OutputHandler(object sendingProcess,DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
StringBuilder sb = new StringBuilder(this.textBox1.Text);
this.textBox1.Text = sb.AppendLine(outLine.Data).ToString();
this.textBox1.SelectionStart =this.textBox1.Text.Length;
this.textBox1.ScrollToCaret();
}
}

解决方法二:

  直接上代码

    [DllImport("User32.dll ", EntryPoint = "SetParent")]
  private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
  [DllImport("user32.dll ", EntryPoint = "ShowWindow")]
  public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
  private void button3_Click(object sender, EventArgs e)
  {
    Process p = new Process();
   p.StartInfo.FileName = "cmd.exe ";
   p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;//加上这句效果更好
   p.Start();
   System.Threading.Thread.Sleep();//加上,100如果效果没有就继续加大
  
   SetParent(p.MainWindowHandle, panel1.Handle); //panel1.Handle为要显示外部程序的容器
   ShowWindow(p.MainWindowHandle, );
  }

  备注:记得引用 using System.Runtime.InteropServices;

C#中winform窗体如何嵌入cmd命令窗口

C#中winform窗体如何嵌入cmd命令窗口