C# - 从另一种形式调用函数

时间:2011-11-21 06:22:58

标签: c# oop tray

我需要从其他表单发送托盘通知。 ControlPanel.cs(默认表单,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(另一种形式):

...
public partial class Form1 : Form
{

    public ControlPanel cp;
    ....

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

在线cp.TrayP = "TRAY POPUP THIS";我收到NullException。 如果我将其更改为cp.TrayPopup("TRAY POPUT THIS", "test");,则会抛出异常。

如果我这样做:

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

,托盘弹出窗口显示,但它会创建第二个托盘图标,然后从新图标显示气球提示。我能做什么? P.S。:抱歉英语不好。

3 个答案:

答案 0 :(得分:2)

如果您要打开第二种形式" Form1"从ControlPanel,您应该将CP的实例传递给Form1,如

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

答案 1 :(得分:0)

每次都不需要分配内存,试试这个

public partial class Form1 : Form
{

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

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

答案 2 :(得分:0)

您的public ControlPanel cp;变量具有空引用,因为它从未初始化。要访问ControlPanel,您需要设置对它的有效引用。如果您的ControlPanel.cs在另一个表单上,您需要从那里获得该引用。通过公共财产或界面。