C# - Calling function from another form

一曲冷凌霜 提交于 2020-04-30 07:51:08

问题


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.


回答1:


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");
    }
}



回答2:


don't need to allocate memory each time , try this

public partial class Form1 : Form
{

    public ControlPanel cp = new ControlPanel();
    ....

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



回答3:


Your public ControlPanel cp; variable has a null reference since its never initialized. In order to access ControlPanel, you need to set a valid reference to it. If your ControlPanel.cs is on another form, you need to get that reference from there. Either through a public property or interface.



来源:https://stackoverflow.com/questions/8208020/c-sharp-calling-function-from-another-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!