Notify Icon duplicates itself, when any event occurs - c#

I have a notify icon in my Winforms form and it seems that when any kind of event happens the tray icon is duplicated.
I have debugged one of the issues, being that it is duplicated when the dialog box is closed after using it.
It happens in debug and when released.
The other issue it with a timer that runs method.
I cannot see why this happens. My timer ran 60 times last night and each time it has four methods to run and there were hundreds of icons in the tray.
My code is as follows:
public Form1()
{
InitializeComponent();
notifyIcon1.BalloonTipText = "Mappi CSV Manager is running.";
notifyIcon1.BalloonTipTitle = "Mappi CSV Manager";
notifyIcon1.Text = "Mappi CSV Manager";
}
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
ShowIcon = false;
ShowInTaskbar = false;
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(1000);
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ShowInTaskbar = true;
notifyIcon1.Visible = false;
WindowState = FormWindowState.Normal;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Call Dispose to remove the icon out of notification area of Taskbar.
notifyIcon1.Dispose();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (CloseCancel() == false)
{
e.Cancel = true;
};
}
//When closing the form
public static bool CloseCancel()
{
const string message = "If you close the program, no files will be generated!";
const string caption = "Stop!";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
return true;
else
return false;
}
//Set new value for timer
private void UdTimerValue_ValueChanged(object sender, EventArgs e)
{
timer1.Interval = Convert.ToInt32(udTimerValue.Value) * 60000;
}
//Start generating CSV's
private void Timer1_Tick(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
if (AutoGenerateEnabled)
{
richLogWindow.AppendText("CSV Created at: " + DateTime.Now + "\r\n");
var startdate = "";
if(DateTime.Now.Hour == 1)
{
richLogWindow.Clear();
startdate = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
CSVGenerator.GenerateCSV(startdate, this);
}
else
{
startdate = DateTime.Today.ToString("yyyy-MM-dd");
CSVGenerator.GenerateCSV(startdate, this);
}
}
else
{
return;
}
}
}
Why is this code producing another tray icon every time a button is clicked or an event happens.
TIA

I found the error. I have put RichTextBoxAppend.AddNewText("test me", new Form1()); the new form was created each time a process was run. I am an idiot!

Related

C# windows app Minimize in system tray error

Hi Friends i have written the program for minimize the form into system tray it is working fine for the minimize and in tray i can see new icon is appeared.
and in double click it restores, But the error is when i restore the form into its normal state then some labels are automatically goes visible false and the timer i have used in form that timer automatically stops please let me know if anyone have faced the same issue and have any idea about this issue.
please refer below code
private void User_Projects_SizeChanged(object sender, EventArgs e)
{
try
{
bool Mousepointontaskbar = Screen.GetWorkingArea(this).Contains(Cursor.Position);
if (this.WindowState == FormWindowState.Minimized && Mousepointontaskbar)
{
notifyIcon1.Icon = SystemIcons.Application;
notifyIcon1.BalloonTipText = "Tracker Has bin Minimized in System Tray";
notifyIcon1.ShowBalloonTip(1000);
this.ShowInTaskbar = false;
notifyIcon1.Visible = true;
//this.SizeChanged += new EventHandler(User_Projects_SizeChanged);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void User_Projects_Resize(object sender, EventArgs e)
{
this.Resize += new EventHandler(User_Projects_SizeChanged);
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
if (this.WindowState == FormWindowState.Normal)
{
this.ShowInTaskbar = true;
this.Visible = true;
notifyIcon1.Visible = false;
}
}

Timer Run Once,Not continuous

I apologize for the use of language translation
I want to run the timer once. Next blogger.I'm saving it to the database.
Ongoing notification..One in 4 seconds
timer1 :Enabled ,Interval :4000
MyCode:
public bool InternetKontrol()
{
try
{
System.Net.Sockets.TcpClient kontrol_client = new System.Net.Sockets.TcpClient("www.google.com.tr", 80);
return true;
}
catch (Exception)
{
label1.Text = "";
return false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (InternetKontrol()==false)
{
NetGelenGiden ngg = new NetGelenGiden();
ngg.GidenZaman = "Net Gitti " + DateTime.Now.ToLongTimeString().ToString();
ngg.GelenZaman = "";
dat.NetGelenGidens.Add(ngg);
dat.SaveChanges();
notifyIcon1.Icon = SystemIcons.Information;
notifyIcon1.ShowBalloonTip(3000, "Net Durum", "Net Gitti " + DateTime.Now.ToLongTimeString().ToString(),ToolTipIcon.Info);
notifyIcon1.Visible = true;
label2.Text ="Net Gitti "+ DateTime.Now.ToLongTimeString().ToString();
}
I think you are defining Timer control in a Windows Forms (that's because you don't put the timer1 declaration).
At the beginning of your event timer1_Tick, disable or stop the timer:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private bool InternetKontrol() { /* your code */ }
public bool flagInternetService = true;
private void timer1_Tick(object sender, EventArgs e)
{
var newResult = InternetKontrol();
var warn = false;
if (flagInternetService != newResult){
if (newResult == false) warn = true;
flagInternetService = newResult;
}
if (warn)
{
/* your code warning */
label2.Text = DateTime.Now.ToLongTimeString();
}
}
}

How to close multiple dialogs in the right way?

I pasted the most important parts of my code below.
As you can see I'd like to work with multiple Forms. But this is how my Form behaves:
It opens Selector, when I press the second button it find the .ini file and opens ExplorerForm, but Selector IS STILL OPEN. Ofcourse I don't want that. I can't click the Selector, I just hear an error sound and the Explorer Window blinks. When I close the Explorer, both, the Explorer AND the Selector close.
But NOW the Path form opens...
When I press one of the other buttons in the Selector, it doesn't find the .INI file (that's right) and opens the Path form (and closes it in the right way).
I already used search and even implemented one of the answers there:
How I can close a 1st form without closing the full application?
My Program.cs:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Selector());
Selector.cs:
private void button1_Click(object sender, EventArgs e)
{
Path pathForm = new Path(0);
this.Hide();
pathForm.ShowDialog();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Path pathForm = new Path(1);
this.Hide();
pathForm.ShowDialog();
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
Path pathForm = new Path(2);
this.Hide();
pathForm.ShowDialog();
this.Close();
}
Path.cs:
public Path(int currGame)
{
intGame = currGame;
if(MyIni.KeyExists("Path"+intGame))
{
var GamePath = MyIni.Read("Path"+intGame);
if(Directory.Exists(GamePath))
{
if (Directory.GetFiles(
GamePath, gameEXE(intGame), SearchOption.TopDirectoryOnly).Count() > 0)
{
InitializeComponent();
Explorer explorerForm = new Explorer();
this.Hide();
explorerForm.ShowDialog();
this.Hide();
}
}
}
InitializeComponent();
label1.Text = label1.Text + " " + gameString(currGame) + "!";
RegistryKey rk = Registry.LocalMachine;
RegistryKey sk1 = rk.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 12100");
// III Steam
RegistryKey sk2 = rk.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 12110");
// Vice City Steam
RegistryKey sk3 = rk.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App 12120");
// San Andreas Steam
if(intGame == 0)
{
if (sk1 != null)
{
if (sk1.GetValueNames().Contains("InstallLocation")
&& sk1.GetValue("InstallLocation").ToString() != "")
{
textBox1.Text = sk1.GetValue("InstallLocation").ToString();
}
}
}
else if(intGame == 1)
{
if(sk2 != null)
{
if(sk2.GetValueNames().Contains("InstallLocation")
&& sk2.GetValue("InstallLocation").ToString() != "")
{
textBox1.Text = sk2.GetValue("InstallLocation").ToString();
}
}
}
else if (intGame == 2)
{
if (sk3 != null)
{
if (sk3.GetValueNames().Contains("InstallLocation")
&& sk3.GetValue("InstallLocation").ToString() != "")
{
textBox1.Text = sk3.GetValue("InstallLocation").ToString();
}
}
}
}
Try modify involved code of your Selector.cs in this way:
private void button1_Click(object sender, EventArgs e)
{
this.StartPathForm(1);
}
private void button2_Click(object sender, EventArgs e)
{
this.StartPathForm(2);
}
private void button3_Click(object sender, EventArgs e)
{
this.StartPathForm(3);
}
private void StartPathThread(int currGame)
{
System.Threading.Thread pathThread = new System.Threading.Thread(PathThreadStart);
pathThread.SetApartmentState(System.Threading.ApartmentState.STA);
pathThread.Start(currGame);
this.Close();
}
private void PathThreadStart(object currGame) {
Application.Run(new Path((int) currGame));
}
With this modification, a new thread would be initialized and the Path form will run on it. Then, the Selector form would close immediately. Hope this fit your use.

Form close after button click with no this.close() call

This is a simple question, but i donĀ“t know where is the problem. I have a form that have some code, when i click into "crear" button, in that button i call to the function "Comprobar" that cheks if the textboxs are empty, if "Comprobar" is false then i show a message.
The problem: After clicking the button "Crear" the form show the message (if all are empty) and then the form close.
Here is the code
public partial class FrmNuevaCita : MetroForm
{
DataTools mytool = new DataTools();
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
// string searchDate = "";
int codigoPaciente = -1;
FrmBuscarPaciente BuscarPaciente = new FrmBuscarPaciente();
public FrmNuevaCita()
{
InitializeComponent();
BuscarPaciente.SetCode += new EventHandler(YouCliked);
}
private void YouCliked(object sender, EventArgs e)
{
codigoPaciente = BuscarPaciente.GetCodigoPaciente;
//MessageBox.Show("Codigito es " + codigoPacienteActual.ToString());
txtPaciente.Text = codigoPaciente.ToString();
}
public DateTime SetDate
{
set { dtpFechaCita.Value = value; }
}
private void mbCancelar_Click(object sender, EventArgs e)
{
this.Close();
}
private void metroRadioButton_CheckedChanged(object sender, EventArgs e)
{
this.cmbHora.Items.Clear();
if (metroRadioButton1.Checked == true)
{
this.cmbHora.Items.AddRange(new object[]
{"8:00","8:30","9:00","9:30","10:00","10:30","11:00","11:30"});
}
else if (metroRadioButton2.Checked == true)
{
this.cmbHora.Items.AddRange(new object[] { "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00" });
}
}
private void mtBuscar_Click(object sender, EventArgs e)
{
BuscarPaciente.Show();
}
private void mbCrear_Click(object sender, EventArgs e)
{
if (Comprobar()==false)
MessageBox.Show("Por favor complete todos los campos");
}
private bool Comprobar()
{
bool result = false;
if (txtPaciente.Text.Trim().Length != 0 && txtObservaciones.Text.Trim().Length != 0 && cmbHora.Text.Trim().Length != 0)
result = true;
return result;
}
}
Make sure, that "Clear" button has DialogResult property set to DialogResult.None.
And that form's CancelButton property is not set to "Clear" button.
have you debug it step-by-step?
Possible Problems:
The "CancelButton"-Option of your form is set to the "mbCrear_Click"-Button.
There might be some missformed linking of the events in your Form's Designerfile.
"mbCancelar_Click"-Event & "mbCrear_Click"-Event refers to the same button
Best thing would be, to set a breakpoint to "mbCrear_Click" and debug it step by step then you see where your form is closed. ;)
Hope i could help

how to call MdiChild from MDIParent form

I create a new MdiChild from MainForm using this method:
AdminLogInForm adminForm;
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null)
{
adminForm = new AdminLogInForm();
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
Why when i close my child, using in chld form "this.close()" using that method i cant open it anymore?
there i call close();
private void cancelLogInButton_Click(object sender, EventArgs e)
{
this.MdiParent.Activate();
if(this.MdiParent!=null)
((MainForm)this.MdiParent).LogInAsAdminMenuItem.Enabled = true;
this.Close();
}
by the way to make work that I asked before I hed to plase this.Close(); after all statements .
By closing the form you are not making adminForm instance to null (Which is what your if condition will check when you try to open it next time.)
On diposal of your form make adminForm = null and then your if condition will work next time.
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null)
{
adminForm = new AdminLogInForm(this);
adminForm.Disposed += new EventHandler(adminForm_Disposed); //Add Disposed EventHandler
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
void adminForm_Disposed(object sender, EventArgs e)
{
adminForm = null;
}
As Described by Marshal that the closing of a form makes it disposed you should add a condition for disposing as well like this
AdminLogInForm adminForm;
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null || adminForm.IsDisposed)
{
adminForm = new AdminLogInForm();
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
Or you can also create a function to use a form as mdi
like this

Categories