Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c# - Call an ICommand from Windows.Forms.NotifyIcon Event .MouseClick() [WPF Application]

I have created a custom NotifyIcon object inherited from Window Forms. Looking for the properties and the methods of the NotifyIcon Class here I saw that I can trigger an Event when the user clicks the NotifyIcon from Taskbar. So I have created the following code inside a ViewModel

namespace TestEnvironment
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public ICommand ShowWindowsCommand //this is the ICommand I want to call in .MouseClick()
        {
            get { return new DelegateCommand<object>(FunctionShowWindows); }
        }
        private void FunctionShowWindows(object parameter)
        {
            ProgressBarTemplate ProgressBarInstance = (ProgressBarTemplate)Application.Current.Windows.OfType<Window>().SingleOrDefault(window => window.Name == "ProgressBarScreen");
            if (ProgressBarInstance != null)
            {
                if (MainWindowInstance.MaxHeight > 725 & MainWindowInstance.MaxWidth > 1200)
                {
                    MainWindowInstance.WindowState = WindowState.Maximized;
                    MainWindowInstance.Activate();
                    //MainWindowInstance.Topmost = true;
                }
                else
                {
                    MainWindowInstance.WindowState = WindowState.Normal;
                    MainWindowInstance.Activate();
                    //MainWindowInstance.Topmost = true;
                }
                ProgressBarInstance.Show();
                ProgressBarInstance.WindowState = WindowState.Normal;
                //ProgressBarInstance.Topmost = true;
            }
            else
            {
                if (MainWindowInstance.MaxHeight > 725 & MainWindowInstance.MaxWidth > 1200)
                {
                    MainWindowInstance.WindowState = WindowState.Maximized;
                    MainWindowInstance.Activate();
                    //MainWindowInstance.Topmost = true;
                }
                else
                {
                    MainWindowInstance.WindowState = WindowState.Normal;
                    MainWindowInstance.Activate();
                    //MainWindowInstance.Topmost = true;
                }
            }
        }

        public ICommand RunCalculationCommand_Approach2
        {
            get { return new DelegateCommand<object>(ExecuteSqlAsync); }
        }
        private async void ExecuteSqlAsync(object obj)
        {
            Stream iconStream_one = Application.GetResourceStream(new Uri("pack://application:,,,/TestApp;component/Assets/loading.ico")).Stream;
            
            System.Windows.Forms.NotifyIcon notification_object = new System.Windows.Forms.NotifyIcon
            {
                Icon = new Icon(iconStream_one),
                Visible = true
            };

            // The complete Task API accepts a CancellationToken to allow cancellation.
            try
            {
                DateTime timestamp_start = DateTime.Now;

                await Task.Run(() => RunCalculationsMethod(object_progressbar, "LOG_DETAILS", 1, true, getconnectionstring, CatchErrorExceptionMessage, this.CancellationTokenSource.Token), this.CancellationTokenSource.Token);
                
                string[] time_passed = DateTime.Now.Subtract(timestamp_start).ToString().Split(@":");

                List<SucessfulCompletion> reportsucessfulcompletion = new List<SucessfulCompletion>();
                reportsucessfulcompletion = CheckLogsFailSuccessProcedure(SQLServerConnectionDetails());

                if (reportsucessfulcompletion[0].Result == 0)
                {
                    notification_object.ShowBalloonTip(5000, "Hi", "This is a BallonTip from Windows Notification", System.Windows.Forms.ToolTipIcon.None);
                    //notification_object.MouseClick += new System.EventHandler(ShowWindowsCommand);
                }
                else
                {
                    notification_object.ShowBalloonTip(5000, "Hi", "Hello World", System.Windows.Forms.ToolTipIcon.None);
                    //notification_object.MouseClick += new System.EventHandler(ShowWindowsCommand);
                }
            }
            catch (Exception ex)
            {
                //..
            }
            finally
            {
                //..
            }
        }
    }
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MainWindowViewModel();
            Closing += CancelSqlOperationsOnClosing;
        }
    }
}

XAML

<Window x:Class="TestEnvironment.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestEnvironment"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Show Toast"
        Padding="10"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Command="{Binding RunCalculationCommand_Approach2}"/>
    </Grid>
</Window>

What I want is to call the ICommand ShowWindowsCommand from the Event MouseClick.

//notification_object.MouseClick += new System.EventHandler(ShowWindowsCommand); -> This is what I want to fix

But this Event accepts EventHandlers. So, is there any way to call the ICommand from the MouseClick event of the NotifyIcon?

question from:https://stackoverflow.com/questions/65603204/call-an-icommand-from-windows-forms-notifyicon-event-mouseclick-wpf-applicat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since NotifyIcon is not actually a control that displays on a page, you can instantiate it in the ViewModel. In order to trigger the command when clicking on the icon, you simply need to implement a callback to the event.

MainWindowViewModel.cs

namespace TestEnvironment
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public ICommand ShowWindowsCommand
        {
            get { return new DelegateCommand<object>(FunctionShowWindows); }
        }

        private void FunctionShowWindows(object parameter)
        {
            // redacted
        }

        public ICommand RunCalculationCommand_Approach2
        {
            get { return new DelegateCommand<object>(ExecuteSqlAsync); }
        }

        private async void ExecuteSqlAsync(object obj)
        {

            Stream iconStream_one = Application.GetResourceStream(new Uri("pack://application:,,,/TestApp;component/Assets/loading.ico")).Stream;
            
            System.Windows.Forms.NotifyIcon notification_object = new System.Windows.Forms.NotifyIcon
            {
                Icon = new Icon(iconStream_one),
                Visible = true
            };

            notification_object.MouseClick += new System.Windows.Forms.MouseEventHandler(NotifyIcon_MouseClick);

            // redacted
        }

        private void NotifyIcon_MouseClick(object sender, EventArgs e);
        {
            FunctionShowWindows(null);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...