WPF MainWindow显示1秒后将自动关闭。我在wpf项目中只有这个主窗口。运行该应用程序时没有错误显示。在不显示任何错误的情况下,MainWindow加载后不久便关闭了。 App.xaml.cs中没有任何代码。
这是在MainWindow中编写的代码。
public partial class MainWindow : Window
{
private Socket clientSocket;
private byte[] buffer;
public MainWindow()
{
InitializeComponent();
}
private bool CheckField()
{
if (txtIP.Text == string.Empty)
{
MessageBox.Show("Please specify IP Address");
return false;
}
if (txtPort.Text == string.Empty)
{
MessageBox.Show("Please specify Port Number");
return false;
}
return true;
}
private void btnGreen_Click(object sender, RoutedEventArgs e)
{
if(CheckField()) SendMessage("GREEN");
}
private void btnRed_Click(object sender, RoutedEventArgs e)
{
if (CheckField()) SendMessage("RED");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// if below code commented, window will not close
clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback,
3333), new AsyncCallback(ConnectCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ConnectCallback(IAsyncResult ar)
{
clientSocket.EndConnect(ar);
}
public void SendMessage(string xmlstring)
{
try
{
byte[] xmlbuffer = Encoding.ASCII.GetBytes(xmlstring);
clientSocket.BeginSend(xmlbuffer, 0, xmlbuffer.Length,
SocketFlags.None, new AsyncCallback(SendCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void SendCallback(IAsyncResult ar)
{
clientSocket.EndSend(ar);
buffer = new byte[clientSocket.ReceiveBufferSize];
}
}
这是怎么了?