Issue with Form.Close() in Winforms

I have a custom form called CustomMessageBox In that form, I have a method that defines a button click, when the button is clicked the form will record the action and close. I also have a method for CustomMessageBox_Formclosing(), which is called automatically when the form is closed. Now the issue is, within CustomMessageBox_Formclosing(), i have an implementation to handle if the close reason was user induced i.e. the user clicked the X button. But the kicker is that the button method defined earlier, interpretes the close method as a user induced close. How can i resolve this?
No description
No description
15 Replies
willCodeforFood
willCodeforFood3mo ago
What I have tried : Setting the form's .Visiblle to false, which works in theory, but i dont want to leave many forms open like that
No description
leowest
leowest3mo ago
I am not sure I understood your needs but how about this
bool button = false;
private void button1_Click(object sender, EventArgs e)
{
button = true;
this.Close();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && button)
{
// user clicked button
button = false;
return;
}
e.Cancel = true;
}
bool button = false;
private void button1_Click(object sender, EventArgs e)
{
button = true;
this.Close();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing && button)
{
// user clicked button
button = false;
return;
}
e.Cancel = true;
}
basically when button is clicked u set a flag to true and then it will check both the flag and the reason if they match it closes otherwise it ignores you can also hide the close button
willCodeforFood
willCodeforFood3mo ago
Will try this
leowest
leowest3mo ago
is that what u want to do?
willCodeforFood
willCodeforFood3mo ago
Not really but im open to trying a new approach
leowest
leowest3mo ago
what is your goal? because from what u said u want to know if the click came from the button vs the X
willCodeforFood
willCodeforFood3mo ago
Yes exactly I managed to find a solution, I used a slight modification to what you described. Thank you
leowest
leowest3mo ago
yeah I mean the idea is simple just using a bool to identify where it came from since its only 2 locations
MODiX
MODiX3mo ago
Use the /close command to mark a forum thread as answered
oke
oke3mo ago
can anyone use this when its done, or is this just for admins?
leowest
leowest3mo ago
its only for who created the thread and mods+ but the bot sending the message anyone can do its just $close
oke
oke3mo ago
so someone pasting a powershell script without code blocks could really fuck the bot over
leowest
leowest3mo ago
try and find out
oke
oke3mo ago
$close = "$close"
MODiX
MODiX3mo ago
Use the /close command to mark a forum thread as answered