简体   繁体   English

在没有触发的Windows窗体应用程序上单击与NotifyIcon关联的ContextMenu的MenuItem上的事件,但需要再单击一次图标才能工作

[英]Click event on MenuItem of a ContextMenu associated to NotifyIcon on a Windows form application not firing but requires one more click on icon to work

I have made an application to fetch data from client using asynchronous socket programming. 我已经创建了一个应用程序,使用异步套接字编程从客户端获取数据。 The user can see the application as a icon in tasktray and can 'close' the application by using right click menu on the tray icon. 用户可以在tasktray中将应用程序视为图标,并可以使用托盘图标上的右键菜单“关闭”应用程序。 To do this I wrote a Windows forms application, made form invisible, associated a notifyicon which is visible always. 为此,我编写了一个Windows窗体应用程序,它是一个隐形的窗体应用程序,它与一个始终可见的通知图标相关联。 In the notifyicon added a contextmenu and display a 'close' option as a contextmenu menuitem to the user. 在notifyicon中添加了一个contextmenu并向用户显示一个'close'选项作为contextmenu menuitem。

The contextmenu is displayed fine on right click on the tray icon. 右键单击托盘图标时,上下文菜单显示正常。 But when menuitem of the contextmenu is clicked, the application does not close as coded. 但是当单击contextmenu的menuitem时,应用程序不会按编码关闭。 It requires one more right click on the tray icon (after clicking the close option), which then closes all the resources. 它需要再次右键单击托盘图标(单击关闭选项后),然后关闭所有资源。 Please find the relevant code as under- 请查找相关代码,如下 -

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;
    }
}

I am suspecting it might be a multithreading problem, but I am new to programming and can't pinpoint. 我怀疑它可能是一个多线程问题,但我是编程新手,无法精确定位。 Any leads on how to resolve this issue is much appreciated. 任何有关如何解决此问题的线索都非常感谢。

It works fine with this below code 它适用于以下代码

 private void menuItem1_Click(Object sender, System.EventArgs e)
    {
     Application.ExitThread();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM