Run Logic When User Presses "x" in Windows Form - c#

I want to run some logic when the user presses the "x" in the upper right hand corner of my Windows Form application. There is a logout button but I am confident the user will not always logout. So I will run same logic on the click of "x". I have the following, but it will not hit the breakpoint.
Code
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//sql server queries to be executed
lblSucessMessage.Text = "Succesfully logged out";
}

Easiest way is to go to the Form's properties, find the FormClosed event, and double click on it. It will add the event to the Form and create the corresponding method. Move your code to the newly created method and delete the method you wrote.
That should get you rolling.

You have 'closed' and 'closing' events, that you can just implement in the constructor. Example:
public Form1()
{
InitializeComponent();
Closed += (sender, args) =>
{
/*Handle event*/
};
Closing += (snd, args) =>
{
/*Handle event*/
};
}

You need to attach handler to event. This can be done in constructor (as well as in designer of your form);
partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//sql server queries to be executed
lblSucessMessage.Text = "Succesfully logged out";
}
}

Related

Close the modal form which is opened by a button of a UserControl when I dispose the UserControl

I have an application in which I need to make sure the form opened by click on a button on a user control using ShowDialog(), will be closed and disposed when I dispose the user control.
I'm calling userControl.Dispose() in my main form through a timer.
Is there a way I can do that ?
Thanks...
Here is more details about the flow of the forms:
The MainForm of my application is creating a UserControl which has a Button. Than when the user clicks on the button of the user control, it shows a model form using ShowDialog.
Meanwhile, and after a few minutes, a timer in the main form replaces the existing user control with another instance of the user control. The main form calls the Dispose method of the previous user control, and the shows the new on.
But the problem is the modal dialog is still open on screen, blocking the main form. I want to close it, and the code placed after the ShowDialog method should not be executed.
Short answer
You can subscribe Disposed event of your UserControl and close the form which it shows. Regarding to the comments under the question, it looks like you have a UserControl containing a Button and in Click event of the button, you show a Form using ShowDialog().
To close and dispose the form, you need to subscribe Disposed event of your UserControl before showing the form as dialog.
More details
If you want to decide to run some logic depending to the dialog result of the form, you can check the dialog result and if it's OK, run the custom logic which you need.
To enhance the flow a bit, you can define some events and properties in your user control and handle them in the main form:
OKSelected event, and you can raise it immediately after closing the dialog if the dialog result is OK. It will let you to handle this event in the main form, for example to stop the timer if the user clicked OK in dialog.
ProcessingFinished, and you can raise it after you finished some processing after closing the dialog when the dialog result is OK. You can handle this in main form, for example to start the timer again.
You can define some properties in case you want to communicate some values with the main form.
Here is an example of the code in main form:
MyUserControl uc = null;
private void timer1_Tick(object sender, EventArgs e)
{
if (!(uc == null || uc.IsDisposed || uc.Disposing))
{
this.Controls.Remove(uc);
uc.Dispose();
}
uc = new MyUserControl();
this.Controls.Add(uc);
uc.OKSelected += (obj, args) => { timer1.Stop(); };
uc.ProcessingFinished += (obj, args) =>
{
MessageBox.Show(uc.Info);
timer1.Start();
};
}
And here is an example of the user control:
public partial class MyUserControl : UserControl
{
public MyUserControl() { InitializeComponent(); }
public EventHandler OKSelected;
public EventHandler ProcessingFinished;
public string Info { get; private set; }
private void button1_Click(object sender, EventArgs e)
{
using (var f = new Form()) {
var button = new Button() { Text = "OK" };
f.Controls.Add(button);
button.DialogResult = DialogResult.OK;
this.Disposed += (obj, args) => {
if (!(f.IsDisposed || f.Disposing)) {
f.Close(); f.Dispose();
}
};
if (f.ShowDialog() == DialogResult.OK) {
//If you need, raise the OKSelected event
//So you can handle it in the main form, for example to stop timer
OKSelected?.Invoke(this, EventArgs.Empty);
//
//Do whatever you need to do after user closed the dialog by OK
//
//If you need, raise the ProcessingFinished event
//So you can handle it in the main form, for example to start timer
//You can also set some properties to share information with main form
Info = "something";
ProcessingFinished?.Invoke(this, EventArgs.Empty);
}
}
}
}
Can you modify the forms that you want to close automatically? If so, try adding the following to each form:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
if (this.Owner != null)
this.Owner.HandleDestroyed += onOwnerHandleDestroyed;
}
void onOwnerHandleDestroyed(object sender, EventArgs e)
{
this.Close();
}
NOTE: You are already using Dispose() to close the main form, so this should work. If, however, you used Close() to close the main form, then it wouldn't work because Close() doesn't close a form if it is the parent of any modal dialog.

Window Form Application in C#

I am new to programming. I am using window form in VisualStudio C#.
My problem is after clicking the first button in my Window Form, It opens the browser and go to Url that I want to login and after that when I click the Second button on my Window Form, it doesn't run the second block of codes. I don't get any error message.
Can anyone help me because I am totally a beginner. Thank you so much in advance!
public partial class Form1 : Form
{
IWebDriver driver = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
driver = new FirefoxDriver();
driver.Url = "https://accounts.google.com/ServiceLogin";
driver.Manage().Window.Maximize();
}
private void button2_Click(object sender, EventArgs e)
{
driver.Url = "https://accounts.google.com/ServiceLogin";
var email = driver.FindElement(By.Id("Email"));
email.SendKeys("-------------");
var password = driver.FindElement(By.Id("Passwd"));
password.SendKeys("---------");
password.FindElement(By.Id("signIn"));
Add button2.Click += button2_Click; to your Form constructor, right after InitializeComponent();. This line adds the event handler button2_Click to the event Button.Click of button2.
Normally, this kind of stuff does the designer for you. If you prefer this way, go to the preview page of your Form, then to the property manager, click the lightning "events" and double click your desired event, in this case Click. Having this done, the method body for the button2 click event handler will be generated.

Windows form opening other forms

What I want
I am creating an application which has two functionalities. Both functionalities have their own form (called FactuurForm and VerhuurForm). I have another Form called Home, which has, among others, two buttons. Depending on which button is clicked, I wish to open one of the two forms, and complete close the Home-form.
What I have
Currently, I have the following code:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Home home = new Home();
home.ShowDialog();
if (home.kiesFactuur)
{
FactuurForm factuur = new FactuurForm();
home.Close();
factuur.ShowDialog();
}
else if (home.kiesVerhuur)
{
VerhuurForm verhuur = new VerhuurForm();
home.Close();
verhuur.ShowDialog();
}
}
}
kiesFactuur and kiesVerhuur are booleans which in my Home class, initialized as false. As soon as I click on of the buttons, the corresponding boolean will flip to true, triggering the if-statements to close the home-form and open the new form.
My question
Altough my current codes works, it seems a bit much for such a simple functionality. I feel like I wouldn't need the booleans and this go all be done easier. So is there an easier/better way to do this?
I've also thought about creating multiple Main functions. Clicking a button would activate the corresponding new Main function and terminate the current Main. Is this even possible and if so, is it a good solution?
I don't exactly understand the need to completely close the home form. I'd just place 2 eventhandlers for each of the buttons and call the following code on them. The first form will be hidden and closed when you close your subform.
private void ShowSubDialog(Form form)
{
this.Hide(); //makes your main form invisible before showing the subform
form.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
ShowSubDialog(new FactuurForm());
Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
ShowSubDialog(new VerhuurForm());
Dispose();
}
private void Factuur_Click(object sender, EventArgs e) {
LoadForm(new FactuurForm());
}
private void Verhuur_Click(object sender, EventArgs e) {
LoadForm(new VerhuurForm());
}
private void LoadForm(Form f) {
this.Hide();
f.ShowDialog();
this.Show();
}
Add this to your Home form, remove everything after home.ShowDialog() from Main, and make Facturr_Click and Verhurr_Click handle their respective button's click events. This will allow Home to hide/show automatically.
You should replace your code like this :
if (home.kiesFactuur)
{
FactuurForm factuur = new FactuurForm();
factuur.Show();
this.Hide();
}
else if (home.kiesVerhuur)
{
VerhuurForm verhuur = new VerhuurForm();
verhuur .Show();
this.Hide();
}
In the VerhuurForm and FactuurForm you may ovveride the event of closure like this :
public VerhuurForm()
{
InitializeComponent();
this.FormClosed += new FormClosedEventHandler(VerhuurForm_FormClosed);
}
void FormClosedEventHandler(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
To be sure that your application is closed if you close the form because the Home still active but hidden.

How to close form

Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he wants to perform the action. The dialog has 2 buttons, a "Yes"-button and a "No"-button. If the user clicks the "Yes"-button, I want both DialogSettingsCancel and WindowSettings to be closed.
My button_Click event handler in DialogSettingsCancel:
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
WindowSettings settings = new WindowSettings();
this.Close();
settings.Close();
}
When I run my application, and go to the settings form, and click the "Cancel"-button, and then click the "Yes"-button, only DialogSettingsCancel closes without closing WindowSettings.
Why won't it work?
I've also tried changing
this.Close();
settings.Close();
to
settings.Close();
this.Close();
But still the same result.
You need the actual instance of the WindowSettings that's open, not a new one.
Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.
Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.
Something like this:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel();
dialogSettingsCancel.OwningWindowSettings = this;
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
public WindowSettings OwningWindowSettings { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Close();
if(OwningWindowSettings != null)
OwningWindowSettings.Close();
}
This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.
If the two are always connected, you should instead use a constructor parameter:
In WindowSettings:
private void showDialogSettings_Click(object sender, EventArgs e)
{
var dialogSettingsCancel = new DialogSettingsCancel(this);
dialogSettingsCancel.Show();
}
In DialogSettingsCancel:
WindowSettings _owningWindowSettings;
public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
if(owningWindowSettings == null)
throw new ArgumentNullException("owningWindowSettings");
_owningWindowSettings = owningWindowSettings;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
_owningWindowSettings.Close();
}
You can also close the application:
Application.Exit();
It will end the processes.
new WindowSettings();
You just closed a brand new instance of the form that wasn't visible in the first place.
You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.
Why not use the DialogResult method to close the form?
if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
//this will close the form but will keep application open if your
//application type is "console" in the properties of the project
this.Close();
}
For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.
Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:
private void button1_Click(object sender, EventArgs e)
{
Settings newSettingsWindow = new Settings();
if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
{
newSettingsWindow.Close();
}
}
send the WindowSettings as the parameter of the constructor of the DialogSettingsCancel and then on the button1_Click when yes is pressed call the close method of both of them.
public class DialogSettingsCancel
{
WindowSettings parent;
public DialogSettingsCancel(WindowSettings settings)
{
this.parent = settings;
}
private void button1_Click(object sender, EventArgs e)
{
//Code to trigger when the "Yes"-button is pressed.
this.parent.Close();
this.Close();
}
}
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
There are different methods to open or close winform.
Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed.
Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Form.Hide()
Application.Exit()
Some methods to Open/Start a form
Form.Show()
Form.ShowDialog()
Form.TopMost()
All of them act differently , Explore them !

Troubles with onFormClosing in c#

I'm trying to implement some code that asks if the user wants to exit the application I've made.
It's in c# and is a windows form application.
I've had very little sleep this week and can't seem to get my head around the onFormClosing event. Could some please give me the exact code I should use to have code executed when the user clicks on the close button (the 'x' in the top right).
Please find it in your heart to help a sleep deprived moron.
Double-click the form's FormClosed event in the events tab of the Properties window in the designer.
The FormClosing event allows you to prevent the form from closing by setting e.Cancel = true.
Well, the event is called FormClosing and is cancellable. Subscribe to it, do your stuff and let the user close their form. This event is fired if the "x" button is used or if you close the form yourself.
You can subscribe to it in the designer by highlighting the form and looking in the events tab of the properties window, as SLaks says, then double-click it. You don't need to do anything special to cope with the "x" button.
The easiest way is to activate the form in the designer and find the event FormClosing in the properties windows and then just double click the event.
Then just do the following:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
var result = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo);
if (result != System.Windows.Forms.DialogResult.Yes)
{
e.Cancel = true;
}
}
}
If you do not specify that the reason has to be UserClosing, it will stop windows from shutting down if you do not exit the program first which is not a good practice.
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you sure that you wan't to close this app", "Question", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
e.Cancel = true;
}
I hope this helps
You can add event handler manually. Example to add event handler in constructor:
public frmMain()
{
InitializeComponent();
FormClosing += frmMain_FormClosing;
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
//your code
}
Make derive your form fromf the System.Windows.Forms.Form and put this override:
protected override void OnFormClosing(CancelEventArgs e)
{
if (bWrongClose)
{
bWrongClose = false;
e.Cancel = true; // this blocks the `Form` from closing
}
base.OnFormClosing(e);
}

Categories