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
Related
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!
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.
i doing window app using c#.net.
i have a form name form_1 with menu-strip.
from the menu-strip of form_1, i am opening same form form_1 and closing the same form_1 after using it but if i click that for the second time it is not showing,if i click that for third time it is showing.
edit:
mainform
form fm;
bool frm= false;
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
if (frm== false)
{
fm= new form();
fm.MdiParent = this;
fm.Show();
frm= true;
}
else
{
if (fm.IsDisposed)
{
frm= false;
}
}
}
form
form fm = new form();
fm.MdiParent = this;
fm.Show();
this.Close();
If you expect your function addToolStripMenuItem_Click to always open fm (assuming it is disposed), then you'll need fm.show() in the else condition as well. You could try something like this instead...
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!frm || fm.IsDisposed)
{
if (fm != null && fm.IsDisposed) { frm = false; }
fm = new form();
fm.MdiParent = this;
fm.Show();
frm = true;
}
}
This probably makes your bool frm obsolete, but I left it in in case you're using it for something else.
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
I have a TextBox in my winforms. When a user starts typing in it I will like to set the AcceptButton property to call another function. However it is calling another function which is called by a Button in my ToolStrip. To elaborate, here is my code below:
private void locNameTxtBx_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = searchBtn;
}
private void searchBtn_Click_1(object sender, EventArgs e)
{
if (locNameTxtBx.Text != "")
{
List<SearchLocation> locationsArray = new List<SearchLocation>();
var location = locNameTxtBx.Text;
SearchLocation loc = new SearchLocation();
loc.Where = location;
locationsArray.Add(loc);
mapArea.VE_FindLocations(locationsArray, true, true, null);
mapArea.VE_SetZoomLevel(14);
}
else
{
MessageBox.Show("Please Enter Location");
}
}
searchBtn is a Button in the ToolStrip. So, when I try to run this code, I get this error
Cannot implicitly convert type 'System.Windows.Forms.ToolStripButton' to 'System.Windows.Forms.IButtonControl'. An explicit conversion exists (are you missing a cast?)
I have tried casting it as a ToolstripButton like this:
private void locNameTxtBx_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = (ToolStripButton)searchBtn;
}
You could use two delegates and set the delegate to use in the locNameTxtBx_TextChanged method.
private delegate void ToUseDelegate();
ToUseDelegate delegateIfNoText = delegate{
MessageBox.Show("Please Enter Location");
}
ToUseDelegate delegateIfText = delegate{
List<SearchLocation> locationsArray = new List<SearchLocation>();
var location = locNameTxtBx.Text;
SearchLocation loc = new SearchLocation();
loc.Where = location;
locationsArray.Add(loc);
mapArea.VE_FindLocations(locationsArray, true, true, null);
mapArea.VE_SetZoomLevel(14);
}
ToUseDelegate delToUse = delegateIfNoText;
private void locNameTxtBx_TextChanged(object sender, EventArgs e)
{
this.AcceptButton = searchBtn;
if (locNameTxtBx.Text != ""){
delegateToUse = delegateIfNoText;
} else {
delegateToUse = delegateIfText;
}
}
private void searchBtn_Click_1(object sender, EventArgs e)
{
delegateToUse();
}