运行DOS控制台EXE程序,并使用C#.net表单应用程序对其进行读写. [英] Run an DOS console EXE program, and read and write it with an C#.net form app.

查看:82
本文介绍了运行DOS控制台EXE程序,并使用C#.net表单应用程序对其进行读写.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个DOS控制台程序OpenSim.exe.
我想做的是运行Windows Form程序,如果我按启动OPENSIM"按钮,那么他将以控制台的形式启动opensim.exe.

现在,我编写了一个代码,可以将文本从控制台传输到应用程序中的richtextbox.一切都很好.但是在控制台启动后,我遇到很多奇怪的错误.

我正在使用我在互联网上找到的类"CmdProcessor".
但是RedirectStandardError = true会出错; RedirectStandardInput = true;和RedirectStandardOutput = true.

有人知道在哪里可以找到将控制台显示到Windows应用程序中的示例,并且还可以向控制台发送"shutdown"之类的命令以执行该命令吗?

这里有CmdProcessor的代码:

Hello all,

I have an DOS console program OpenSim.exe.
What i want to do is to run my windows Form program and if i press the button START OPENSIM then he is starting the opensim.exe as console.

Now i have make a code that i can tranfer the text from the console to an richtextbox in my application. all is going good. but after the console is started up i get a lot of wierd errors.

I''m using the "CmdProcessor" a class i have found on the internet.
but it is going wrong with the RedirectStandardError = true; RedirectStandardInput = true; and RedirectStandardOutput = true.

Does someone know where to find an example to show the console into an windows application, and olso to send command like "shutdown" to the console to execute that command?

Here i have the code of the CmdProcessor:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace OpenSimWin
{
    public class CmdProcessor
    {
        /// 
        /// Execute takes a command string to pass as the arguments to cmd.exe.       
        /// 
        /// The command to execute. 
        /// Examples: 
        ///   "dir" 
        ///   "type ..\..\comdprocessor.cs"
        /// 
        public void Execute(string command)
        {
            _process = InitializeProcess(command);
            _executing = true;
            _process.Start();
            AttachStreams();
            PrepareAsyncState();
            // read the streans asynchronously so 
            // control will return to the caller
            _standardOutput.BaseStream.BeginRead(
               _outputBuffer, 0,
               _outputBuffer.Length,
               _outputReady,
               _outputState
               );
            _standardError.BaseStream.BeginRead(
               _errorBuffer, 0,
               _errorBuffer.Length,
               _errorReady,
               _errorState
               );
        }
        // event fires when text arrives on standard output or standard inpuy      
        public event CmdProcessorEventHandler TextReceived;
        // Initializes a ProcessStartInfo for the Process.
        protected virtual ProcessStartInfo GetStartInfo(string command)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "OpenSim.exe";
            // /c tells cmd.exe to execute the following command and then terminate
            //psi.Arguments = "/c " + command;
            // UseShellExecute = false required for stream redirection
            psi.UseShellExecute = false;
            // we will redirect standard streams to our own
            psi.RedirectStandardError = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            // dont allow the DOS box to appear
            psi.CreateNoWindow = true;
            return psi;
        }
        protected virtual Process InitializeProcess(string command)
        {
            if (_executing)
            {
                // don't allow client to start another process while one is 
                // currently executing
                throw new ApplicationException("A Process is currently executing");
            }
            _process = new Process();
            _process.StartInfo = GetStartInfo(command);
            _process.EnableRaisingEvents = true;
            _process.Exited += new EventHandler(_process_Exited);
            return _process;
        }
        private void AttachStreams()
        {
            _standardOutput = _process.StandardOutput;
            _standardError = _process.StandardError;
        }
        private void _process_Exited(object sender, EventArgs e)
        {
            int exitCode = _process.ExitCode;
            if (TextReceived != null)
            {
                // return exit code as part of output
                //TextReceived(
                      //this,
                      //new CmdProcessorEventArgs("Exited with code: " + exitCode.ToString())
                   //);
            }
            _process.Dispose();
            _process = null;
            _executing = false;
        }

        // output has arrived on either standard output or standard error.
        // finish the asynch call, and if text has arrived raise an event.
        // finally, we need to try to read more from the steam in case not 
        // all the outout has arrived.
        private void OutputCallback(IAsyncResult ar)
        {
            AsyncState state = (AsyncState)ar.AsyncState;
            int count = state.Stream.BaseStream.EndRead(ar);
            if (count > 0)
            {
                if (TextReceived != null)
                {
                    string text = System.Text.Encoding.ASCII.GetString(state.Buffer, 0, count);
                    TextReceived(this, new CmdProcessorEventArgs(text));
                }
                state.Stream.BaseStream.BeginRead
                   (
                   state.Buffer, 0,
                   state.Buffer.Length,
                   _outputReady,
                   state
                   );
            }
        }
        // this method prepares the callback delegates which will be invoked when the 
        // asychronous reads have results, and also prepares a "state" object to carry
        // the stream and buffer objects used in the asynch calls
        private void PrepareAsyncState()
        {
            _outputReady = new AsyncCallback(OutputCallback);
            _outputState = new AsyncState(_standardOutput, _outputBuffer);
            _errorReady = new AsyncCallback(OutputCallback);
            _errorState = new AsyncState(_standardError, _errorBuffer);
        }
        private bool _executing = false;
        private Process _process;
        private StreamReader _standardOutput;
        private StreamReader _standardError;
        private byte[] _errorBuffer = new byte[512];
        private byte[] _outputBuffer = new byte[512];
        private AsyncCallback _outputReady;
        private AsyncState _outputState;
        private AsyncCallback _errorReady;
        private AsyncState _errorState;
    }
    public delegate void CmdProcessorEventHandler(object sender, CmdProcessorEventArgs e);
    public class CmdProcessorEventArgs : EventArgs
    {
        public CmdProcessorEventArgs(string text)
        {
            _text = text;
        }
        public string Output
        {
            get { return _text; }
            set { _text = value; }
        }
        protected string _text;
    }
    internal class AsyncState
    {
        public AsyncState(StreamReader stream, byte[] buffer)
        {
            _stream = stream;
            _buffer = buffer;
        }
        public StreamReader Stream
        {
            get { return _stream; }
        }
        public byte[] Buffer
        {
            get { return _buffer; }
        }
        protected StreamReader _stream;
        protected byte[] _buffer;
    }

}


然后是应用程序的内容:


and here from the application:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace OpenSimWin
{
    public partial class main : Form
    {
        private Timer t = new Timer();
        public Boolean scrollPause = true;
        public Process[] myProcesses;
        public CmdProcessor cmd = new CmdProcessor();

        public main()
        {
            InitializeComponent();
            t.Interval = 1;
            t.Tick += new EventHandler(t_Tick);
            t.Enabled = false;
        }

        void t_Tick(object sender, EventArgs e)
        {
            Start_OpenSim.Enabled = true;
            Kill_OpenSim.Enabled = false;
            txtCommand.Enabled = false;
            Run_Command.Enabled = false;
            groupBox_Commands.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //public CmdProcessor cmd = new CmdProcessor();
            //cmd.TextReceived += new CmdProcessorEventHandler(cmd_TextReceived);
            if (!File.Exists("OpenSim.exe"))
            {
                MessageBox.Show("No OpenSim.exe found, please copy this program in the Main Directory.             (for example C:/Program files/OpenSim) and try again!!");
                Close();
            }

        }

        private void Run_Command_Click(object sender, System.EventArgs e)
        {
            txtOutput.Text = String.Empty;

            //CmdProcessor cmd = new CmdProcessor();
            cmd.TextReceived += new CmdProcessorEventHandler(cmd_TextReceived);
            cmd.Execute(txtCommand.Text);
            txtCommand.Clear();
        }

        private void cmd_TextReceived(object sender, CmdProcessorEventArgs e)
        {
            if (InvokeRequired)
            {
                object[] args = { sender, e };
                Invoke(new CmdProcessorEventHandler(cmd_TextReceived), args);
            }
            else
            {
                txtOutput.Text += e.Output;
            }
        }

        private void Start_OpenSim_Click(object sender, EventArgs e)
        {
            if (File.Exists("OpenSim.exe"))
            {
                //CmdProcessor cmd = new CmdProcessor();
                cmd.TextReceived += new CmdProcessorEventHandler(cmd_TextReceived);
                txtOutput.Clear();
                cmd.Execute(null);
                Start_OpenSim.Enabled = false;
                Kill_OpenSim.Enabled = true;
                txtCommand.Enabled = true;
                Run_Command.Enabled = true;
                groupBox_Commands.Enabled = true;
            }
            else
            {
                MessageBox.Show("No OpenSim.exe found, please copy this program in the Main Directory.             (for example C:/Program files/OpenSim) and try again!!");
            }
        }

        private void txtOutput_TextChanged(object sender, EventArgs e)
        {
            if (scrollPause == true)
            {
                txtOutput.SelectionStart = txtOutput.Text.Length;
                txtOutput.ScrollToCaret();
            }
        }

        private void ChkWordWrap_CheckedChanged(object sender, EventArgs e)
        {
            if (ChkWordWrap.CheckState == CheckState.Checked)
            {
                txtOutput.WordWrap = false;
            }
            else
            {
                txtOutput.WordWrap = true;
            }
        }

        private void Kill_OpenSim_Click(object sender, EventArgs e)
        {
            myProcesses = Process.GetProcessesByName("OpenSim");
            foreach (Process myProcess in myProcesses)
            {
                myProcess.Kill();
            }
            Start_OpenSim.Enabled = true;
            Kill_OpenSim.Enabled = false;
            txtCommand.Enabled = false;
            Run_Command.Enabled = false;
            groupBox_Commands.Enabled = false;
       }

        private void ChkScrollPause_CheckedChanged_1(object sender, EventArgs e)
        {
            if (ChkScrollPause.CheckState == CheckState.Checked)
            {
                scrollPause = false;
            }
            else
            {
                scrollPause = true;
            }
        }
    }
}



很抱歉main.cs的编程错误,因为我正在尝试服务器式支持,但没有结果.



Sorry for the bad programming of the main.cs that''s because i was trying serveral sulotions, but no result.

推荐答案


之间 最好选择TCP套接字连接方案
否则
您可以使用Windows消息队列
或可以使用Windows消息传递
您可以从本文尝试Windows Messenger
http://ryanfarley.com/blog/archive/2004/05/10/605.aspx [^ ]
Seems like u want 2 applition to communicate between
Better go for a TCP socket connection scenario
Or else
u can use Windows message queing
Or can use windows messaging
u can try out windows messagin from this article
http://ryanfarley.com/blog/archive/2004/05/10/605.aspx[^]


您好,TCP通信无法正常工作.我在这里放了2个程序的屏幕快照的2个链接,您可以看到DOS控制台EXE程序和带有绿色文本的Windows应用程序.

DOS控制台EXE程序: [单击此处查看图片]

Windows应用程序: [单击此处获取图片]

Windows应用程序中的绿色文本来自DOS控制台程序.我使用RedirectStandardOutput()做到了这一点,但是如果您在Windows应用程序中查看绿色文本底部的内容,您会发现我开始出现错误.

我唯一想做的就是将文本从DOS控制台显示到Windows应用程序窗体,如果它是Richtextbox或TAB屏幕或其他内容,并且使用按钮,我只希望将命令发送到DOS控制台在该程序中执行命令.一个查看命令是:关机,显示用户,备份,地形填充21等,等等

所以我希望有人举一个例子,或者可以帮助我解决这个小问题.

最好的问候,

否认者
Hello, TCP communication is not going to work. i put here 2 links of an screenshot of the 2 programs, you can see the DOS console EXE program and the Windows Application with the green text.

DOS Console EXE Program: [Click here for Picture]

and here the Windows Application: [Click here for Picture]

The green text in the windows application is from the DOS console program. i did that with the RedirectStandardOutput() but if you look in the windows application at the bottum of the green text you will see that i starting to get error''s.

what i only want to do is to show the text from the DOS console to an windows application form, if it is an richtextbox or an TAB screen or what ever, and with the buttons i make i only want to send commands to the DOS console to execute the commands in that program. a view commands are: shutdown, show users, backup, terrain fill 21, etc, etc

SO i was hoping that someone has an example or can help me with this little problem i have.

Best Regards,

Repudiator


这篇关于运行DOS控制台EXE程序,并使用C#.net表单应用程序对其进行读写.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆