Search code examples
c#ooptray

C# - Calling function from another form


I need a tray notify from another form. ControlPanel.cs (default form, notifyicon here):

  ...
  public partial class ControlPanel : Form
    {
        public string TrayP
        {
            get { return ""; }
            set { TrayPopup(value, "test");}

        }

   public void TrayPopup(string message, string title)
    {
        TrayIcon.BalloonTipText = message;
        TrayIcon.BalloonTipTitle = title;
        TrayIcon.ShowBalloonTip(1);
    }

Form1.cs (another form):

...
public partial class Form1 : Form
{

    public ControlPanel cp;
    ....

    private void mouse_Up(object sender, MouseEventArgs e) {
        cp.TrayP = "TRAY POPUP THIS";
    }

On line cp.TrayP = "TRAY POPUP THIS"; I am getting a NullException. If i change it to cp.TrayPopup("TRAY POPUT THIS", "test"); an exception throws whatever.

If i make this:

private void mouse_Up(object sender, MouseEventArgs e) {
    var CP = new ControlPanel();
    CP.TrayPopup("TRAY POPUP THIS", "test");
}

, tray popup shows, but it`s creates the second tray icon and then show balloon hint from new icon. What can I do? P.S.: Sorry for bad English.


Solution

  • If you are opening second form "Form1" from ControlPanel, you should pass the instance of CP to Form1, like

    public partial class ControlPanel : Form
    {
    
        public void ShowForm1(){
            FOrm1 f1 = new Form1();
            f1.SetCp(this);
            f1.show();
        }
    
        public void TrayPopup(string message, string title)
        {
            TrayIcon.BalloonTipText = message;
            TrayIcon.BalloonTipTitle = title;
            TrayIcon.ShowBalloonTip(1);
        }
    }
    
    public partial class Form1 : Form
    {
    
        public ControlPanel _cp;
        public void SetCP(controlPanel cp){
                _cp = cp;
        }
    
        private void mouse_Up(object sender, MouseEventArgs e) {
                if(_cp != null)
                _cp.TrayPopup("TRAY POPUP THIS", "test");
        }
    }