前言
我属于刚接触C#的萌新,自学了三四天就开始写项目的那种。在第一个项目中,涉及到界面的伸缩,当时,只想到最笨的方法,就是下面介绍的第一种,今天我有时间探索了一下,有了第二种方法。
两种实现方式
第一种方式
因为是初学者,我还搞不懂WinForm里面的各个控件的用法,所以怎么让他显示又隐藏,而且界面大小随之变化,我只想到了:设置要操控部分的可视度(visible),改变其大小,然后为了让界面其他各个控件随之变化,则将其各个控件位置关系重新刷新了一遍。
以下是测试代码,我弄了四个面板进行测试,为了方便我将面板的高度都调整为100,button1控制Panel2的伸缩,button2控制Panel4的伸缩,这个写的比较简陋,图标什么的都没改,大家凑合着看。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
updateForm();
}
private void updateForm()
{
panel2.Top = panel1.Bottom;
panel3.Top = panel2.Bottom;
panel4.Top = panel3.Bottom;
}
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
switch(Convert.ToInt16(btn.Tag))
{
case 1:
changePanel(panel2);
break;
case 2:
changePanel(panel4);
break;
}
updateForm();
}
void changePanel(Panel panel)
{
if (panel.Visible)
{
panel.Visible = false;
this.Height -= 100;
panel.Height = 0;
}
else
{
panel.Visible = true;
this.Height += 100;
panel.Height = 100;
}
}
}
}
以下是效果图
第二种方式
第二种方式则是,使用了控件SpliteContainer,由于它是由伸缩功能的(它包含两个面板,任意一个都可伸缩, SplitContainer.Panel1Collapsed、SplitContainer.PanelCollapsed),但仅仅设置这个是不够的,在这种情况下,设置某一个面板收起来,另一个面板会占据整个区域,所以我又调整了SpliteContainer的高度。这个方法明显看着更简洁,更好控制一些,特别是在界面复杂的情况。
代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testForm
{
public partial class Form2 : MyBaseForm
{
public Form2()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
Button btn = (Button)sender;
switch (Convert.ToInt16(btn.Tag))
{
case 1:
ContainerCollapsed(splitContainer1, btn);
break;
case 2:
ContainerCollapsed(splitContainer2, btn);
break;
}
}
private void ContainerCollapsed(SplitContainer split,Button btn)
{
if (split.Panel2Collapsed)
{
split.Panel2Collapsed = false;
split.Height += split.SplitterDistance;
this.Height += split.SplitterDistance;
btn.Image = Image.FromFile(".\\res\\up.png");
}
else
{
split.Panel2Collapsed = true;
split.Height -= split.SplitterDistance;
this.Height -= split.SplitterDistance;
btn.Image = Image.FromFile(".\\res\\down.png");
}
}
private void label1_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//为当前应用程序释放鼠标捕获
ReleaseCapture();
//发送消息 让系统误以为在标题栏上按下鼠标
SendMessage((IntPtr)this.Handle, VM_NCLBUTTONDOWN, HTCAPTION, 0);
}
}
}
}
效果图如下
结束语
不说什么啦,下班啦。