0

I am a foreign student learning programming. I am using WPF in C# for the first time. However, I got an 'InvalidOperationException' error. This makes me very confusing. What is the problem with this code and how can I fix it?

namespace Test
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();


            // Please do not edit here
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Elapsed += delegate
            {
                Dispatcher.Invoke(new Action(delegate
                {
                    Mouse.Capture(this);
                    System.Windows.Point pointToWindow = Mouse.GetPosition(this);
                    System.Windows.Point pointToScreen = PointToScreen(pointToWindow);
                    Mouse.Capture(null);
                }));
            };
            timer.Interval = 1;
            timer.Start();

            //set system tray
            var menu = new System.Windows.Forms.ContextMenu();
            var noti = new System.Windows.Forms.NotifyIcon
            {
                Icon = Properties.Resources.Icon,
                Visible = true,
                Text = "title",
                ContextMenu = menu,
            };
            var item = new System.Windows.Forms.MenuItem
            {
                Index = 0,
                Text = "bye"
            };
            item.Click += (object o, EventArgs e) =>
            {
                System.Windows.Application.Current.Shutdown();
            };

            menu.MenuItems.Add(item);
            noti.ContextMenu = menu;


        }

    }
}
  • 1
    Have you tried to debug your code? Here is a doc how debugger works in VS [msdn debugger](https://learn.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019) – Omelian Levkovych Dec 17 '20 at 17:25
  • Try using a `DispatcherTimer` rather than `System.Timers.Timer` - that's designed for use with WPF and you won't have to mess around with Dispatcher.Invoke calls. – Peregrine Dec 17 '20 at 17:50

0 Answers0