- 1 year ago
Keep the windows forms of the application within the application and block launch of another forms already one form is opened
To keep the windows forms of the application within the application and prevent the launch of another form when one form is already opened, you can use the Application.OpenForms
property in Windows Forms. This property provides access to the collection of currently open forms in the application. Here's an example:
csharpusing System;
using System.Linq;
using System.Windows.Forms;
namespace YourNamespace
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Create and show the initial form
var mainForm = new MainForm();
Application.Run(mainForm);
}
}
public partial class MainForm : Form
{
private bool isAnotherFormOpen;
public MainForm()
{
InitializeComponent();
}
private void OpenAnotherFormButton_Click(object sender, EventArgs e)
{
if (!isAnotherFormOpen)
{
isAnotherFormOpen = true;
var anotherForm = new AnotherForm();
anotherForm.FormClosed += (s, args) => isAnotherFormOpen = false;
anotherForm.Show();
}
}
}
}
In this example, the MainForm
is the initial form of your application. When the "OpenAnotherFormButton" is clicked, it checks whether isAnotherFormOpen
is false
. If it is false
, it creates and shows the AnotherForm
. The FormClosed
event handler for AnotherForm
updates the isAnotherFormOpen
flag to false
when the form is closed.
By using this approach, you can control the opening of multiple forms within your application, ensuring that only one instance of the "AnotherForm" is allowed at a time.