Hello, I'm having some trouble troubleshooting a problem and finding a fix for it. I've spent a little over 4 hours now and I don't seem to be making any progress.
Here is some code that I used to recreate my problem in a new project.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test
{
public partial class Form1 : Form
{
frmPopup frm;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (frm != null && !frm.IsDisposed) frm.Dispose();
frm = new frmPopup();
frm.FormClosing += frm_FormClosing;
frm.Show();
}
void frm_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Test 1");
MessageBox.Show("Test 2");
}
}
}
In the above example code, 'frmPopup' is just a blank form that will call "this.Close()" when its deactivated event is fired. This way a user can click outside of the form to go ahead and close it, without having to click the "X" button every time. On "Form1", the closing event of "frmPopup" is captured so I can execute code when the popup form is closing.
However, for some reason during the closing event, the first MessageBox that displays "Test 1", will execute over and over again after closing it, and the second MessageBox will never execute. I added the following code to test the method and see exactly what was happening.
int countOne = 0;
int countTwo = 0;
int countThree = 0;
void frm_FormClosing(object sender, FormClosingEventArgs e)
{
countOne++;
MessageBox.Show(string.Format("Test 1{0}Count One: {1}{0}Count Two: {2}{0}Count Three: {3}", System.Environment.NewLine, countOne, countTwo, countThree));
countTwo++;
MessageBox.Show("Test 2");
countThree++;
}
After closing the first MessageBox the code continues on until right before the second MessageBox and then loops back to the beginning of the method. This continues until either the application crashes or I stop debugging. This problem seems to happen with the MessageBox control and any other Modal forms. If there is no MessageBox or Modal form at all, then the code executes like normal.
What would be causing my application, and the above example code that I wrote to behave this way? The problem persists even if I use the "FormClosed" event instead of "FormClosing". If I handle the "Deactivate" event on "Form1" and place my code there instead, it seems to work fine, but then if the popup form is closed manually (ex. clicking the "X" button) then the problem continues.
Thanks for your time and any help you can provide.