0


Im new to c#, and trying to write code w/o vs.
i am trying to build a system tray app that will change the notifyIcon at runtime.

I read a few tutorials on the topic, and wrote the following code, but i am getting these errors, and cannot get around it:

new 2.cs(41,9): error CS0103: The name 'notifyIcon1' does not exist in the current context
new 2.cs(41,37): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer

Can anyone help me out? (this is a pared down version of my code... tried to isolate the problems.)

using System;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
using System.Diagnostics;

namespace sysTrayApp
{
   static class Program
   {
    [STAThread]
    static void Main()
    {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         NotifyIcon notifyIcon1 = new NotifyIcon();
         ContextMenu contextMenu1 = new ContextMenu();
         MenuItem menuItem1 = new MenuItem();
         contextMenu1.MenuItems.AddRange(new MenuItem[] { menuItem1 });

         menuItem1.Index = 0;
         menuItem1.Text = "Exit";
         menuItem1.Click += new EventHandler(menuItem1_Click);

         notifyIcon1.Icon = new Icon("On.ico");
         notifyIcon1.Text = "some text";
         notifyIcon1.ContextMenu = contextMenu1;
         notifyIcon1.Click += new EventHandler(notifyIcon1_Click);
         notifyIcon1.Visible = true; 

        Application.Run();
    }

    private static void menuItem1_Click(object Sender, System.EventArgs e)
    {
         Application.Exit();
    }

    private static void notifyIcon1_Click(object Sender, EventArgs e)
    {
        notifyIcon1.Icon = new Icon(this.GetType(),"Off.ico");
    }
  }
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • notifyIcon1 is defined inside Main, and you are trying to access it in notifyIcon1_Click. Did you mean to declare in the class itself? (ie; outside Main) – Dinesh Rajan Aug 11 '14 at 23:08
  • `this.GetType()` is not what you want either. `this` will be `Program`, not really sure what you are trying to do there, no reason for that method to be static. – crthompson Aug 11 '14 at 23:19
  • declare NotifyIcon in the class scope and in its click handler instead of this.GetType() place typeof(Program) ,because you are inside a static method which belongs to the class itself not an instance of it. – terrybozzio Aug 11 '14 at 23:28

1 Answers1

0

I think problem in your notifyIcon1_Click EventHandler. change the code as give sample below.

    private static void notifyIcon1_Click(object Sender, EventArgs e)
    {
        ((NotifyIcon)Sender).Icon = new Icon(Sender.GetType(), "Off.ico");
        //notifyIcon1.Icon = 
    }
Seminda
  • 1,745
  • 12
  • 15