欢迎来到Introzo百科
Introzo百科
当前位置:网站首页 > 技术 > C#中如何以winform形式嵌入cmd命令窗口

C#中如何以winform形式嵌入cmd命令窗口

日期:2023-10-06 15:04

-->

解决方案1:

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

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

private void OutPutForm_Shown(对象发送者, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
进程 = 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();
}
私有无效OutputHandler(对象发送进程,DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(www.introzo.com))
{
StringBuilder sb = new StringBuilder(this.textBox1.Text);
this.textBox1.Text = sb.AppendLine(www.introzo.com).ToString();
www.introzo.comionStart =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(对象发送者,EventArgs e)
  {
    进程 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;

-->