0

I have a notifyIcon on my Main form, and want to set the baloontip from another class. Now I get the following error: The name 'TaskbarIcon' does not exist in the current context.

Now this makes sense, since it's not in the scope but how would I still access this? Do I need an interface? According to https://stackoverflow.com/a/5647064/659731 I do need one (but it's a textbox) and you can pass a string, while with the baloontip I need to pass more arguments: ShowBalloonTip(2000, "Nu:", result[0] + " - " + result[1], ToolTipIcon.Info);

It's declared with public System.Windows.Forms.NotifyIcon TaskbarIcon;

Community
  • 1
  • 1
Devator
  • 3,686
  • 4
  • 33
  • 52

1 Answers1

1

You would need a reference to your Main form, which would need to be passed to your class (probably in the constructor):

public class MyClass
{
    private Form Main { get; set; }

    public MyClass(Form main, ...)
    {
        Main = main;
    }
}

Then you'd call the item from your class:

private method DoSomething(...)
{
    Main.TaskbarIcon.ShowBalloonTip(...);
}

However, as you mentioned, it's better to put something between your class and the actual object.

Edit: You could also pass a delegate to invoke that will make the changes for you, or you could pass a reference to the item (again, not recommended). However, make sure you're doing this all on the same thread.

Edit2: Building on the link, your interface could look like this:

interface IYourForm
{
    void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon);
}

Your form would then implement the interface:

class YourForm : Form, IYourForm

And the method:

public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon)
{
    TaskbarIcon.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
}

This would then change your DoSomething method to look like this:

private method DoSomething(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon)
{
    Main.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
}

Again, make sure this is all on the same thread. Otherwise, this needs to be handled differently.

Community
  • 1
  • 1
zimdanen
  • 5,508
  • 7
  • 44
  • 89
  • Could you tell me how I would create such interface which will handle those multiple arguments? – Devator Apr 25 '12 at 15:09
  • Thanks, however it throws me the error `Method must have a return type` for – Devator Apr 25 '12 at 15:27
  • Sorry, I edited it again, but I guess not before you got to it. I was missing the **void** on the interface method. – zimdanen Apr 25 '12 at 15:28
  • Cheers, that part works now. However I get one final error, please have a look at http://pastebin.com/t5TDQ54R – Devator Apr 25 '12 at 15:35
  • Did you add the property and assign to it in the constructor? See the first code block in my answer. – zimdanen Apr 25 '12 at 15:39