问题
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