Application.OpenForms.Count Incorrectly Reporting Zero
In some instances, the Application.OpenForms count returns an incorrect value of zero, obscuring the actual number of open forms. This issue arises when specific properties are modified after window creation, particularly those that impact window styling.
Consider the following example, where the ShowInTaskbar property is changed post-initialization:
public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; } private void button1_Click(object sender, EventArgs e) { Console.WriteLine(Application.OpenForms.Count); this.ShowInTaskbar = !this.ShowInTaskbar; Console.WriteLine(Application.OpenForms.Count); } }
Upon modifying ShowInTaskbar, the form disappears from the Application.OpenForms collection even though it remains open. This is due to an underlying Windows Forms bug where modifying specific properties triggers a recreation of the native window using CreateWindowEx(). As a result, the Application class loses track of the form, leading to incorrect OpenForms counts.
To avoid this bug, refrain from modifying the following properties after window creation:
Instead, set these properties during form construction or through other means that do not involve CreateWindowEx() recreation. Additionally, avoid solely relying on Application.OpenForms and consider passing form references directly to classes that display message boxes.
The above is the detailed content of Why Does Application.OpenForms.Count Return Zero When Forms Are Open?. For more information, please follow other related articles on the PHP Chinese website!