我已经创建了一个应用程序,使用异步套接字编程从客户端获取数据。 用户可以将应用程序视为tasktray中的图标,并可以使用“关闭”应用程序 右键菜单图标上的菜单。 为此,我编写了一个Windows窗体应用程序,它是不可见的,与可见的通知图标相关联 总是。在notifyicon中添加了一个contextmenu并向用户显示一个'close'选项作为contextmenu menuitem。
右键单击托盘图标时,上下文菜单显示正常。 但是当单击contextmenu的menuitem时,应用程序不会关闭 编码。它需要再次右键单击托盘图标(单击关闭选项后),然后关闭所有资源。 请在< - p>下找到相关代码
public partial class Form1 : Form
{
private ContextMenu m_menu;
public static ManualResetEvent allDone = new ManualResetEvent(false);
public Form1()
{
InitializeComponent();
m_menu = new ContextMenu();
m_menu.MenuItems.Add(0, new MenuItem("Close", new System.EventHandler(menuItem1_Click)));
notifyIcon1.ContextMenu =this.m_menu;
notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
// Initiate listening for sockets
StartListening();
}
private void Form1_Load(object sender, EventArgs e)
{
}
// State object for reading client data asynchronously
public class StateObject
{
// Client socket, size of receive buffer, receive buffer and received data string.
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
// socket program goes here, with msdn AcceptCallback and ReceiveCallback
public static void StartListening()
{ // Create a TCP/IP socket.
string port = ConfigurationManager.AppSettings["port"];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(port));
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(1);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception ex)
{
}
}
// AsyncResult tells status of asynchronous operation
private static void AcceptCallback(IAsyncResult AR)
{
// Signal the main thread to continue.
allDone.Set();
// handler is the socket to accept incoming connection and create socket to handle remote host communications
// Get the socket that handles the client request.
Socket listener = (Socket)AR.AsyncState;
Socket handler = listener.EndAccept(AR);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
private void menuItem1_Click(Object sender, System.EventArgs e)
{
this.Close();
// Application.Exit();
Environment.Exit(0);
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
Show();
ShowInTaskbar = true;
}
}
我怀疑它可能是一个多线程问题,但我是编程新手并且无法精确定位。任何有关如何解决此问题的线索都非常感谢。
答案 0 :(得分:1)
下面的代码
可以正常使用 private void menuItem1_Click(Object sender, System.EventArgs e)
{
Application.ExitThread();
}