i learned earlier how to move between two forms back and forth. but what if there's more forms? this is my code for form1:
Form2 form2 = new Form2();
private void aboutoldtrafford_MouseClick(object sender, MouseEventArgs e)
{
this.Hide();
form2.ShowDialog();
this.Show();
}
i can go to form2 and there's two button there: back and next
private void backbutton_MouseClick(object sender, MouseEventArgs e)
{
this.DialogResult = DialogResult.OK;
}
Form3 form3 = new Form3();
private void nextbutton_MouseClick(object sender, MouseEventArgs e)
{
this.Hide();
form3.ShowDialog();
this.Show();
}
back button will return to form1 and the next button will go to form3. below is my code for form3. in form3, there are two buttons: back 开发者_C百科and finish
private void back_MouseClick(object sender, MouseEventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void finish_MouseClick(object sender, MouseEventArgs e)
{
this.Hide();
// i want to go back to form1
}
back button will return to form2 and the finish button will go back to form1. obviously, i cant do "this.DialogResult = DialogResult.OK;" in the finish button. how can i go back to form1 without going to form2? please help...
First option - you can use UserControls instead of Forms and just call BringToFront() on control that you want to make active.
Another option - move application state management to some object. Create states map
public class StateManager
{
private Dictionary<ApplicationState, Form> _stateMap = new Dictionary<ApplicationState, Form>();
private ApplicationState _currentState;
public void RegisterState(ApplicationState state, Form form)
{
if (_stateMap.ContainsKey(state))
// throw an exception, or rewrite mapping
_stateMap.Add(state, form);
}
public ApplicationState CurrentState
{
get { return _currentState; }
set
{
if (!_stateMap.ContainsKey(value))
// do nothing or throw exception
if (_currentState == value)
return;
CurrentForm.Hide();
_currentState = value;
CurrentForm.Show();
}
}
public Form CurrentForm
{
get { return _stateMap[_currentState]; }
}
}
I used here forms instances, but you can create instances via factory.
Next step - register states of application (of course, you should give more meaningful names for application states):
StateManager stateManager = StateManager.Instance;
stateManager.RegisterState(ApplicationState.Form1, new Form1());
stateManager.RegisterState(ApplicationState.Form2, new Form2());
stateManager.RegisterState(ApplicationState.Form3, new Form3());
Set current state and run application:
stateManager.CurrentState = ApplicationState.Form1;
Application.Run(stateManager.CurrentForm);
And last step - change applications states. You can pass stateManager instance to forms constructors, or use static Singleton:
private void previousButton_Click(object sender, EventArgs e)
{
StateManager.Instance.CurrentState = ApplicationState.Form1;
}
Further you can create forms dynamically, use configuration file for states definition etc.
Good luck!
精彩评论