如何将此winforms应用程序转换为控制台应用程序?

时间:2012-12-10 12:28:21

标签: c#

以下代码在Windows窗体应用程序中运行正常,但我需要在控制台中运行它。

namespace TelnetApp
{
    public partial class TelnetForm : Form
    {
        public TelnetForm()
        {
            InitializeComponent();
        }

        private Socket clientSocket;

        IPAddress hostAddress;
        public void telnetSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
        {    
            try
            {    
                if (e.SocketError == SocketError.Success)
                {

                    if (e.LastOperation == SocketAsyncOperation.Connect)
                    {    
                        MessageBox.Show("Service Is Running", hostAddress.ToString(),
                            MessageBoxButtons.OK, MessageBoxIcon.Information);    
                    }    
                }    
                else
                {    
                    MessageBox.Show("Service Is not Running", e.SocketError.ToString(),
                       MessageBoxButtons.OK, MessageBoxIcon.Error);

                }    
            }

            catch (SocketException ex)
            {    
                MessageBox.Show(ex.Message, "Service Is not Running",    
                    MessageBoxButtons.OK, MessageBoxIcon.Error);    
            }
        }

        private void TelnetButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(IPTextBox.Text))
                    return;   
                if (string.IsNullOrEmpty(PortTextBox.Text))    
                    return;
                int port;    
                hostAddress = IPAddress.Parse(IPTextBox.Text);
                int.TryParse(PortTextBox.Text, out port);
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
                telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress,port);
                telnetSocketAsyncEventArgs.Completed += new
                EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);
                clientSocket.ConnectAsync(telnetSocketAsyncEventArgs);

            }    
            catch (SocketException ex)
            {    
                MessageBox.Show(ex.Message, "Service Is not Running",    
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

            }    
            finally
            {

            }                   
          }    
       } 
    }

2 个答案:

答案 0 :(得分:2)

创建一个新的控制台应用程序项目,将代码复制到其中,并将按钮单击事件中的代码放入main方法中。您可能需要更改其他方法签名以包含static

移除对MessageBox的来电,并将其替换为Console.WriteLine。此外,由于您没有供用户输入数据的文本框,因此您需要解析命令行参数,这很容易,因为它们是static void Main(string[] args)中的数组。

然后,启动调试器并检查是否有问题。

答案 1 :(得分:1)

只需将代码复制到控制台应用中,然后添加对System.Windows.Forms的引用,并将using System.Windows.Forms;添加到using指令中以保留消息框。

如果您不想使用消息框,请改用Console.WriteLine