Hi @Joseph Querijero , Welcome to Microsoft Q&A,
You can use the FormClosing
event in WinForms to achieve this goal. A more elegant way is to use the FormClosing
event to detect whether the user attempts to close the window, and decide whether to allow closing based on the running status of the event or method.
private bool isRunning = false; // Flag indicating whether an event or method is running
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isRunning)
{
MessageBox.Show("The operation is in progress and the form cannot be closed.");
e.Cancel = true; // Cancel the closing operation
}
}
// Example of a long-running operation
private async void LongRunningOperation()
{
try
{
isRunning = true;
// Simulate a long-running task
await Task.Delay(5000);
}
finally
{
isRunning = false; // Reset the flag after the operation is completed
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.