Beispiel #1
0
        private System.Windows.Forms.ToolStripButton BuildConnectionToolStripButton(string text, IConnectable connectable, Func <IAccesoUPVService, UserControls.ConnectionEventArgs, Task> connectHandler, Func <UserControls.ConnectionEventArgs, Task> disconnectHandler = null)
        {
            async void ConnectionHandler(object sender, EventArgs e)
            {
                System.Windows.Forms.ToolStripButton button = (sender as System.Windows.Forms.ToolStripButton);
                button.Enabled = false;
                try
                {
                    bool isChecked = button.Checked;

                    if (isChecked)
                    {
                        if (disconnectHandler != null)
                        {
                            await disconnectHandler.Invoke(UserControls.ConnectionEventArgs.CreateFrom(connectable, false));
                        }
                        else
                        {
                            await connectable.DisconnectAsync();
                        }
                    }
                    else
                    {
                        if (connectHandler != null)
                        {
                            await connectHandler.Invoke(_service, UserControls.ConnectionEventArgs.CreateFrom(connectable, true));
                        }
                        else
                        {
                            await connectable.ConnectAsync();
                        }

                        if (connectable is IOpenable openable)
                        {
                            openable.Open();
                        }
                    }

                    button.Checked = !isChecked;
                }
                catch (OperationCanceledException)
                {
                    // El usuario canceló algo, así que no importa
                }
                finally
                {
                    button.Enabled = true;
                }
            }

            System.Windows.Forms.ToolStripButton toolStripButton = new System.Windows.Forms.ToolStripButton(text, null, ConnectionHandler);

            void updateConnectionStatusHandler(object s, EventArgs e) => toolStripButton.Checked = connectable.IsConnected;

            updateHandlers.Add(updateConnectionStatusHandler);
            UpdateConnectionStatus += updateConnectionStatusHandler;

            return(toolStripButton);
        }