C#, 在MainForm上点击按钮1切换到form1,点击按钮2切换到form2,点击按钮3切换到form3,点击按钮4切换到form4,点击按钮5切换到form5,每个按钮可重复点击,运行程序时默认显示MainForm的完整代码
时间: 2024-09-07 21:02:34 浏览: 37
C#实现简单的壁纸点击切换
5星 · 资源好评率100%
在C#中,为了实现在MainForm上通过按钮切换到不同的forms,你可以使用事件处理和Form的Show()方法。首先,在你的项目中创建五个Form类(Form1到Form5),然后在MainForm中添加相应的按钮并设置事件处理器。以下是MainForm的部分完整代码示例:
```csharp
using System;
using System.Windows.Forms;
public partial class MainForm : Form
{
private Form1 form1;
private Form2 form2;
private Form3 form3;
private Form4 form4;
private Form5 form5;
public MainForm()
{
InitializeComponent();
form1 = new Form1();
form2 = new Form2();
form3 = new Form3();
form4 = new Form4();
form5 = new Form5();
// 初始化Form1,使其透明以便于MainForm可见
form1.FormBorderStyle = FormBorderStyle.None;
form1.ShowInTaskbar = false;
button1.Click += Button1_Click;
button2.Click += Button2_Click;
button3.Click += Button3_Click;
button4.Click += Button4_Click;
button5.Click += Button5_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
if (CurrentForm != form1)
{
Close(); // 关闭当前窗口
form1.Show();
}
}
private void Button2_Click(object sender, EventArgs e)
{
if (CurrentForm != form2)
{
Close(); // 关闭当前窗口
form2.Show();
}
}
private void Button3_Click(object sender, EventArgs e)
{
if (CurrentForm != form3)
{
Close(); // 关闭当前窗口
form3.Show();
}
}
private void Button4_Click(object sender, EventArgs e)
{
if (CurrentForm != form4)
{
Close(); // 关闭当前窗口
form4.Show();
}
}
private void Button5_Click(object sender, EventArgs e)
{
if (CurrentForm != form5)
{
Close(); // 关闭当前窗口
form5.Show();
}
}
private Form CurrentForm => ((Form)this.ActiveForm);
}
// 同样,你需要为form1到form5分别创建对应的Click事件处理器
```
运行这个程序时,默认会显示MainForm。每个按钮点击后都会关闭当前显示的form,并显示对应按钮关联的form。
阅读全文