How do I focus on a form after entering a textbox - c#

I'm not sure if focus is the right word but I have an on key up event on my form that will open a new form and close the current form, however after i enter a textbox or other such object i can't re select the form to be able to activate the key up event
This is code a I am using currently when i click on my form, to try select my currently open form however it does not close the current form when i active the key up event, when i do it this way
private void frmLevel1_Click(object sender, EventArgs e)
{
this.BackColor = GlobalClass.BG;
frmLevel1 lvl1 = new frmLevel1();
lvl1.Select();
}

I'm not 100% sure, but you have a few different questions. I hope it helps.
// Button click event
private void button1_Click(object sender, EventArgs e)
{
// Focus on textbox
this.ActiveControl = textBox1;
}
// Form load event
private void Form1_Load(object sender, EventArgs e)
{
// Focus on textbox
this.ActiveControl = textBox1;
}
// Close the current form and open another one. Use any event what you want
private void button1_Click(object sender, EventArgs e)
{
using (Form2 frm = new Form2())
{
// Hide the current form. If you close it it will dispose of all further events
this.Hide();
// Open the new form
frm.Show();
// Close the current form
this.Close();
}
}

Related

How do I solve this error: 'Cannot access a disposed object. Object name: 'IncomeForm'.'?

What I'm trying to do is get user input from a form (IncomeForm) by using a textbox (TextBoxIncomePrice) and after pressing the button (ButtonConfirmIncome), the LabelIncome label in the form MainPage should change to the value input by the user.
Everything works as intented, except for when I try to reopen the IncomeForm by clicking the AddIncomeButton. I get the error shown in the title. It should be able to reopen and accept a new value no matter how many times you close the IncomeForm.
Main Form (MainPage):
IncomeForm incomeForm = new IncomeForm();
private void incomeForm_FormClosed(object sender, FormClosedEventArgs e)
{
LabelIncome.Text = incomeForm.TextBoxIncomePrice.Text;
}
private void AddIncomeButton_Click(object sender, EventArgs e)
{
incomeForm.FormClosed += new FormClosedEventHandler(incomeForm_FormClosed);
incomeForm.Show();
}
Add Income Form (IncomeForm):
private void ButtonConfirmIncome_Click(object sender, EventArgs e)
{
this.Close();
}

How to stop windows form from closing but hide upon clicking the X?

I'm trying to have a click event that will open another form. I don't want the user to be able to close this window because I get the following exception when the click event is executed again.
System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'Form2'.'
I'm not sure if I'm implementing this correctly or there's a better way of doing this.
Form1
public Form2 f = new Form2();
private void Btnsearch_Click(object sender, EventArgs e)
{
f.Show();
}
Form2
private bool allowClose = false;
private void Btnclose_Click(object sender, EventArgs e)
{
allowClose = true;
this.Hide();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!allowClose)
e.Cancel = true;
}
Subscribe to Form.OnClosing and set the Cancel property on the event args that are passed to the handler. This will tell the runtime to cancel the close event.
Since the event is getting canceled, you'll have to hide the form yourself (using Hide(), of course).
private void Form1_Closing(Object sender, CancelEventArgs e)
{
this.Hide();
e.Cancel = true;
}
The instance of form2 should be created within the event
private void Btnsearch_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
There are a couple of ways to approach this.
It's generally more efficient, in the FormClosing event, to hide the form and cancel the event, but this can require extra logic.
Unless you have some expensive code that needs to run when the form is created, this probably doesn't matter, and it'll be easier to simply allow the form to close normally.
Either way, all you particularly need to do, is throw some safeguards into the btnSearch handler, so that it can appropriately respond to the state of form f;
public Form2 f;
public void BtnSearch_Click(object sender, EventArgs e)
{
if (f == null || f.IsDisposed || f.Disposing) f = new Form2(...);
f.Show();
}

Creating a temporary name for a button

I've been looking for a solution for days now.
Currently have 2 Forms. Main Form has multiple buttons, lets say (1-10).
All buttons will open up my 2nd Form (say I press Button 4). On my 2nd Form I have a ComboBox with different names and a confirm button. When I choose a name from the ComboBox, then press the confirm button.
I want the name selected in the ComboBox to be displayed as the new button text from my Main form (So name3 from Form 2 ComboBox will replace Button text (Button 4) on Main Form).
Any suggestions on how I can achieve this?
I can get the text from ComboBox to Main Form into a Label or a Button of my choosing, but I can't do it from the pressed button on Main Form which opened Form 2.
I've tried changing the button pressed on Main Form to a buttonTemp name, then letting the text from ComboBox change buttonTemp text, but it's coming up as it doesn't exist on Form 2.
Form 1 code:
public void b1111_Click(object sender, EventArgs e)
{
b1111.BackColor = Color.Red;
buttonTemp.Name = "bTemp2";
b1111.Name = "buttonTemp";
Classroom f4 = new Classroom();
f4.Show();
}
this is on Form 2:
private void button1_Click(object sender, EventArgs e)
{
temp1 = comboBox1.Text;
// trying to figure out the label text
foreach (Term1 Form1 in Application.OpenForms.OfType<Term1>())
{
Form1.buttonTemp.Text = comboBox1.Text;
}
this.Close();
}
Do not operate on the controls of other forms. Instead operate with values.
In your case when you finished and closed Form2 you can return a value back to the Form1 and update button text with a returned value.
In Form2 create public property which will be populated before you close Form2.
public string SelectedName { get; set; }
private void selectNameButton_Click(object sender, EventArgs e)
{
SelectedName = comboBox1.Text;
this.Close();
}
In Form1 use .ShowDialog() method to display form in modal form
public void openForm2Button_Click(object sender, EventArgs e)
{
openForm2Button.BackColor = Color.Red;
using (var form = new Classroom())
{
form.ShowDialog();
// next line will be execute after form2 closed
openForm2Button.Text = form.SelectedName; // update button text
}
}
Suggested by #Enigmativity in the comments:
// Form 2
public string SelectedName => comboBox1.Text;
private void selectNameButton_Click(object sender, EventArgs e)
{
this.Close();
}
// Form 1 remains same
There is many ways to get your goal.
I hope you try to use event.
You can make your own event as below.
private void Form1_Load(object sender, EventArgs e)
{
//define listen event from custom event handler
_form2.OnUserSelectNewText += new Form2.TextChangeHappen(_form2_OnUserSelectNewText);
}
When you have member variable for remember which button clicked by user.
private Control activeControl = null;
and you can get text that user's choice from your custom event at Form2.
//to make simple code, centralize all buttons event to here.
private void button_Click(object sender, EventArgs e)
{
//to remeber which button is clicked.
activeControl = (Button)sender;
_form2.ShowDialog();
}
and then you just change text of "activeControl".
private void _form2_OnUserSelectNewText(string strText)
{
activeControl.Text = strText;
}
please refer this, how to make custom event with delegate.
public partial class Form2 : Form
{
//you can expand your own custom event, string strText can be Control, DataSet, etc
public delegate void TextChangeHappen(string strText); //my custom delegate
public event TextChangeHappen OnUserSelectNewText; //my custom event
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// to prevent null ref exception, if there is no event handler.
if (OnUserSelectNewText != null)
{
OnUserSelectNewText(this.comboBox1.Text);
}
this.Close();
}
}

C# WPF How to start a function in WindowA by action on WindowB?

I have two Windows: MainWindow and AddAlarm.
AddAlarm is getting opened by a button which is in MainWindow. (MainWindow is still active)
When I typed in my data in AddAlarm, I press the "OK" button and AddAlarm get's closed. After pressing "OK" I want to activate a function which is in MainWindow.cs
But how do I do that?
Opens new window (AddAlarm)
private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
{
AddAlarm frm = new AddAlarm();
frm.Show();
frm.Activate();
}
Pressing "OK"-button in AddAlarm window
private void Button_OK_Click(object sender, RoutedEventArgs e)
{
// some code which activates function in MainWindow
}
Function in MainWindow
public void Refresh()
{
string[] refresh = new string[0];
refresh = File.ReadAllLines("Alarms.txt");
}
There might be a clever and easy solution, but I just don't know how to do that.
I appreciate your help,
thanks
This totally depends on you but here is a simple solution.
private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
{
AddAlarm frm = new AddAlarm(this); // pass a reference to main window
frm.Show();
frm.Activate();
}
you'll need to create a private MainWindow mainWindow; in AddAlarm window and assign it in the constructor.
Then
private void Button_OK_Click(object sender, RoutedEventArgs e)
{
this.mainWindow.Refresh();
}
More complicated, but more "idiomatic", would be to rely on callback events (like an AlarmAdded event with an Alarm parameter which would be registered right after the AddAlarm is created and raised by the AddAlarm window when it's done).
The approach I would probably take would be to just open AddAlarm modally--that way you can read the information you need from the AddAlarm window in the same block.
private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
{
AddAlarm frm = new AddAlarm();
// ShowDialog waits until AddAlarm is closed before returning
frm.ShowDialog();
// Recommended to add a check on frm.DialogResult to verify whether the user OK'd or Cancelled.
if (frm.DialogResult = DialogResult.Ok) {
AlarmSettings settings = frm.AlarmSettings;
Alarm createdAlarm = new Alarm (AlarmSettings);
}
}

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 !

Categories