-8

下面的代码在 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
            {

            }                   
          }    
       } 
    }
4

2 回答 2

2

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

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

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

于 2012-12-10T12:35:18.000 回答
1

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

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

于 2012-12-10T12:40:05.233 回答