仅供学习交流,还有一些Bug
1.基本的用户控件
public partial class BaseView : UserControl
{
public BaseView()
{
InitializeComponent();
}
protected MainForm parentForm;
/// <summary>
/// 父窗体
/// </summary>
public MainForm ParentForm
{
get { return parentForm; }
set { parentForm = value; }
}
protected string msg;
/// <summary>
/// 标题
/// </summary>
public string Msg
{
get { return msg; }
set { msg = value; }
}
/// <summary>
/// 单快捷键按下后激活事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void OnHotKey(object sender, KeyEventArgs e)
{
}
}
2.主窗体
public partial class MainForm : Form
{
private BaseView currentView = null;
public BaseView CurrentView
{
get { return currentView; }
set { currentView = value; }
}
public MainForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
this.LoadView(typeof(LoginForm));
}
public BaseView LoadView(Type targetType)
{
if (currentView != null)
{
currentView.Visible = false;
}
BaseView newView = null;
foreach (Control control in this.MainPanel.Controls)
{
if (control.GetType() == targetType)
{
newView = (BaseView)control;
break;
}
}
if (newView == null)
{
newView = (BaseView)Activator.CreateInstance(targetType);
MainPanel.Controls.Add(newView);
newView.ParentForm = this;
}
currentView = newView;
newView.Visible = true;
this.label1.Text = newView.Msg;
//如果baseview里面要加啥别的方法这里也要处理执行
return newView;
}
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = DateTime.Now.ToString("yyyyMMdd HH:mm");
}
private void MainForm_Closed(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
catch (Exception ex)
{
}
}
}
3登录
public partial class LoginForm : BaseView
{
public LoginForm()
{
InitializeComponent();
this.Msg = "登录";
}
private void button1_Click(object sender, EventArgs e)
{
this.parentForm.LoadView(typeof(MainView));
}
}
4.主界面
public partial class MainView : BaseView
{
public MainView()
{
InitializeComponent();
this.Msg = "主界面";
}
private void button1_Click(object sender, EventArgs e)
{
this.ParentForm.LoadView(typeof(LoginForm));
}
}
5.program
Application.Run(new MainForm());