目录
winform控件
一、概述
二、常用属性
eg1:Do you love me?
eg2:动态的显示当前时间:
eg3:跑马灯
eg4:简单记事本NoteBook
eg5:单选和多选
eg6:MDI窗体
eg7、PictureBox上下选择图片
eg8、Directory创建、删除目录
eg9、ComboBox 选择年月日
eg10、ListBox 图片、音频播放器
eg11:综合应用__记事本程序(OpenFileDialogue SaveFileDialogue)
Form1.Designer.cs:这个文件大家不要去手动修改它,它是由系统自动生成的。
Form1.resx:资源文件 可以制作双语文件
当双击窗体上的控件时,就会为该控件添加一个默认的事件,默认的即最常用的
事件:可以说是用户的操作,比如说按下键盘,点击鼠标,双击鼠标,鼠标移入,让该控件可以做一些事情
构造函数是用来初始化控件的
Text:显示在控件上的文本
Name:该控件的姓名,在后台代码中,通过Name属性来访问该控件
。。。。。。
注:如何关闭主窗口:
方法一:创建static静态类。
方法二:Application.Exit();
方法三:System.Environment.Exit(0);//彻底关闭
MouseEnter:当鼠标指针穿过元素时,会执行事件.
当鼠标移入button的时候,我立马改变Button的位置,移出鼠标范围
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("I love you");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("好吧,我投降了!");
}
private void button2_MouseEnter(object sender, EventArgs e)
{
//找到鼠标可以移动的最大范围
int fx = this.ClientSize.Width;
int fy = this.ClientSize.Height;
int w = button2.Width;
int h = button2.Height;
int x = fx - w;
int y = fy - h;
Random r = new Random();
Point p = new Point();//坐标
p.X = r.Next(0, x);
p.Y = r.Next(0, y);
button2.Location = p;
}
}
所有知识基本上都是围绕着类,定时器也不例外,Timer类 属性 方法
Enable:控件是否可用
Interval:时间间隔 希望定时器多久执行一次 计时单位是ms 1s=1000ms
Tick事件:事件到了,让定时器做什么,在该事件中实现
获取当前时间:DateTime类
Start():启动定时器
Stop():停止定时器
让窗体居中:StarPosition 改成:CenterScreen
Timer:在指定的时间间隔内做一些事情
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
关键:timer事件中,将字符串的第一个字符放到最后。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
string str = textBox1.Text;
string tou = str.Substring(0, 1);
string sub = str.Substring(1, str.Length - 1)+tou;
textBox1.Text = sub.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
窗体1(登录):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textUser.Text == "admin" && textPwd.Text == "123")
{
this.Hide();
MessageBox.Show("欢迎光临!");
Form2 f2 = new Form2();
f2.Show();
}
else
{
MessageBox.Show("输入错误!");
}
}
}
窗体2(写字板):
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
textBox1.WordWrap = false;
}
private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.WordWrap = true;
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
using(StreamWriter sw=new StreamWriter(@"E:\notebook.txt", false, Encoding.Default))
{
sw.Write(textBox1.Text);
MessageBox.Show("保存成功!");
}
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
注:1.让文本框变成密码框:设置textBox1的PasswordChar属性 为 *。
2.将文本框的WordWrap属性设为True----自动换行
Checked:指示控件是否处于选中状态
默认情况下,单选控件只能被选中一个,用GroupBox进行分组
private void button1_Click(object sender, EventArgs e)
{
string text1 = "";
if (radioButton1.Checked)
{
text1= "你的性别是:"+radioButton1.Text+"\n";
}
else
{
text1 = "你的性别是:" + radioButton2.Text + "\n";
}
text1 = text1 + "你喜欢吃:";
if (checkBox1.Checked)
text1 = text1 + " " + checkBox1.Text;
if (checkBox2.Checked)
text1 += " " + checkBox2.Text;
if (checkBox3.Checked)
text1 += " " + checkBox3.Text;
MessageBox.Show(text1);
}
1)创建一个父窗体 Form1
设置IsMdiContainer为true
2)创建子窗体,并设置他们的父窗体
Form2 frm = new Form2();
frm.MdiParent = this;
平铺:LayoutMdi(MdiLayout.TileHorizontal); 纵向排列
垂直排列:LayoutMdi(MdiLayout.TileVertical);横向排列
private void 添加子窗体ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.MdiParent = this;
Form3 f3 = new Form3();
f3.MdiParent = this;
Form4 f4 = new Form4();
f4.MdiParent = this;
f2.Show();
f3.Show();
f4.Show();
}
private void 纵向排列ToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileHorizontal);
}
private void 横向排列ToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileVertical);
}
1)图片上一张、下一张
2)PicutreBox与Timer组合,随机显示图片
public partial class Form1 : Form
{
string[] imgs; //存储文件夹中图片路径的数组
public Dog TaiDi { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Image img = Image.FromFile(@"C:\Users\Administrator\Desktop\Image\下载 (1).jpg"); //从文件中获取图片
//获取文件夹所在的路径
imgs=Directory.GetFiles(@"C:\Users\Administrator\Desktop\Image");
Image img = Image.FromFile(imgs[0]);
pictureBox1.Image = img;
}
int i = 0; //数组的索引
///
/// 下一张
///
///
///
private void btnDown_Click(object sender, EventArgs e)
{
i++;
//如果到了数组下标的最大值,将i赋值为0
if (i == imgs.Length)
{
i = 0;
}
pictureBox1.Image = Image.FromFile(imgs[i]); //10
}
///
/// 上一张
///
///
///
private void btnUp_Click(object sender, EventArgs e)
{
i--;
if (i < 0)
{
i = imgs.Length-1;
}
pictureBox1.Image = Image.FromFile(imgs[i]);
}
}
(using System.IO)
1)Create:创建文件夹
2)Delete(strpath,true):删除文件夹:第二个变量指示是否删除子文件
3)Move(path1,path2):将文件夹从path1剪切到path2
4)GetFiles(strpath, ”*.jpg”):获取指定文件夹下所有jpg文件的全路径
5)GetDirec tories():获取指定目录下的所有文件夹
6)Directories.Exists(strPath):判断指定目录是否存在
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Dictionary:目录
//创建一个目录
string path = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
Directory.CreateDirectory(path);
}
private void button2_Click(object sender, EventArgs e)
{
string path = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
Directory.Delete(path);
}
private void button3_Click(object sender, EventArgs e)
{
string path1 = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
string path2 = textBox2.Text.Trim();
Directory.Move(path1,path2);
}
///
/// 获取目录中指定文件
///
///
///
private void button4_Click(object sender, EventArgs e)
{
string path1 = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
string[]arr=Directory.GetFiles(path1, "*.txt");
for (int i = 0; i < arr.Length; i++)
{
MessageBox.Show(arr[i]);
}
}
//获取目录下的所有文件夹
private void button5_Click(object sender, EventArgs e)
{
string path1 = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
string[]arr=Directory.GetDirectories(path1);
for (int i = 0; i < arr.Length; i++)
{
MessageBox.Show(arr[i]);
}
}
//目录是否存在
private void button6_Click(object sender, EventArgs e)
{
string path1 = textBox1.Text.Trim(); //Trim:去掉文本框前后的空格
bool b=Directory.Exists(path1);
if (b)
{
MessageBox.Show("存在");
}
else
{
MessageBox.Show("不存在");
}
}
}
DropDownStyle:下拉框的样式
例:三个ComboBox分别显示年、月、日
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//添加年
for (int i = 1995; i < 2020; i++)
{
//往ComboBox中添加元素
comboYear.Items.Add(i);
}
//添加月
for (int i = 1; i < 13; i++)
{
combYue.Items.Add(i);
}
}
public void AddDay(int year, int month)
{
//清空控件中的现有项
combDay.Items.Clear();
int day = 0;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
//判断啊是否是闰年
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
{
day = 29;
}
else
{
day = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
}
for (int i = 1 ; i <= day; i++)
{
combDay.Items.Add(i);
}
}
private void combYue_SelectedIndexChanged(object sender, EventArgs e)
{
//获取控件中选中的年
int year = int.Parse( comboYear.SelectedItem.ToString());
int month = int.Parse(combYue.SelectedItem.ToString());
AddDay(year, month);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show( comboYear.SelectedItem.ToString());
}
}
1)绑定数据源:
//显示的数据
ComBox1.DisplayMemeber="name";//name为类A的字段名
//隐藏的数据(对于多个数据,可以用逗号隔开。例:id,name)
ComBox1.ValueMember="id";//id为类A的字段名(对于隐藏对个数据,把数据放到一个字段用逗号隔开)
//绑定数据源
ComBox1.DataSource=dt;
2)显示数据
ComBox1.SelectedValue 获取或设置由ValueMember 属性指定的成员属性的值
ComBox1.SelectedText 获取或设置ComboBox 的可编辑部分中选定的文本。
1)双击显示图片
SizeMode设为Zoom,显示完整图片。
public partial class Form1 : Form
{
string[] arrImgPaths;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string path = @"E:\图片";
bool b=Directory.Exists(path);
if (b)
{
arrImgPaths = Directory.GetFiles(path, "*.jpg");
for (int i = 0; i < arrImgPaths.Length; i++)
{
string FileName = Path.GetFileName(arrImgPaths[i]);
listBox1.Items.Add(FileName);
}
}
else
{
MessageBox.Show("不存在");
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = listBox1.SelectedIndex;
string s = arrImgPaths[index];
pictureBox1.Image = Image.FromFile(s);
}
}
2)双击播放音乐
添加音视频播放控件
工具箱上点鼠标右键--》选择项--》COM组件--》Windows Media Player 前面打上对勾--》确定
public partial class 音频播放器 : Form
{
List arrs = new List();
public 音频播放器()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string path = @"E:\那些经典";
bool b = Directory.Exists(path);
if (b)
{
arrs.AddRange(Directory.GetFiles(path, "*.mp3"));
foreach (string item in arrs)
{
string FileName = Path.GetFileName(item);
listBox1.Items.Add(FileName);
}
}
else
{
MessageBox.Show("不存在");
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = listBox1.SelectedIndex;
string s = arrs[index];
axWindowsMediaPlayer1.URL = s;
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "打开文件位置";
openFileDialog1.Filter = "音频(.mp3)|*.mp3|视频(.mp4)|*.mp4";
openFileDialog1.InitialDirectory=@"E:\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path2 = openFileDialog1.FileName;
arrs.Add(path2);
string FileName = Path.GetFileName(path2);
if (listBox1.Items.Contains(FileName))
{
MessageBox.Show("已存在");
}
else
{
listBox1.Items.Add(FileName);
}
}
}
}
1、OpenFileDialogue 打开文件对话框
2、SaveFileDialogue 保存文件对话框
3、综合应用——记事本程序
1)打开文件,显示到文本框中,可以更改字体和颜色,更改完以后保存文件。
2)已经打开过的文件在左侧ListBox中显示, 可以显示 隐藏。
public partial class Form2 : Form
{
List listPaths = new List();
bool richboxTextHasChanged = false;
public Form2()
{
InitializeComponent();
richTextBox1.WordWrap = false;
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.FileName != "" && richboxTextHasChanged == true && MessageBox.Show("文本内容已更改\n是否保存修改?", "信息提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{//若文本改动,首先保存
richTextBox1.SaveFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
Application.Exit();
}
private void 保存ToolStripMenuItem1_Click(object sender, EventArgs e)
{
if(openFileDialog1.FileName != "")
{
string pathYy = openFileDialog1.FileName;
using (StreamWriter sw = new StreamWriter(pathYy, false, Encoding.Default))
{
sw.Write(richTextBox1.Text);
MessageBox.Show("保存成功!");
}
}
else
{
saveFileDialog1.FileName = Path.GetFileName(openFileDialog1.FileName);
saveFileDialog1.InitialDirectory = openFileDialog1.FileName;
saveFileDialog1.Filter = "文本文件(.txt)|*.txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
}
}
private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.ForeColor = colorDialog1.Color;
}
}
private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.Font = fontDialog1.Font;
}
}
private void 打开ToolStripMenuItem1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "文本文件(.txt)|*.txt";
openFileDialog1.InitialDirectory = @"D:\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//将文本文件里面的内容加载到界面内
string path = openFileDialog1.FileName;
listPaths.Add(path);
string FileName = Path.GetFileName(path);
listBox1.Items.Add(FileName);
richTextBox1.LoadFile(path, RichTextBoxStreamType.PlainText);
this.Text = openFileDialog1.FileName + "-记事本";
#region 法二:
//richTextBox1.Clear();
//string path = openFileDialog1.FileName;
//string FileName = Path.GetFileName(path);
//using (StreamReader sr = new StreamReader(path, Encoding.Default))
//{
// string str = null;//先声明一个字符串
// while ((str = sr.ReadLine()) != null)//判断读取到的字符串是为null,如果为null,说明已经读取到文件末尾
// {
// richTextBox1.AppendText(str);//将读取到的字符串打印到控制台
// }
//}
#endregion
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richboxTextHasChanged = true;
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.FileName != "" && richboxTextHasChanged == true && MessageBox.Show("文本内容已更改\n是否保存修改?", "信息提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
{//若文本改动,首先保存
richTextBox1.SaveFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
//不然初始化界面
openFileDialog1.FileName = "";
this.Text = "记事本";
richTextBox1.Clear();
richboxTextHasChanged = false;
MessageBox.Show("已初始化界面");
}
private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = Path.GetFileName(openFileDialog1.FileName);
saveFileDialog1.InitialDirectory = openFileDialog1.FileName;
saveFileDialog1.Filter = "文本文件(.txt)|*.txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
int index = listBox1.SelectedIndex;
string path = listPaths[index];
richTextBox1.LoadFile(path, RichTextBoxStreamType.PlainText);
}
private void 最近打开ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
if (最近打开ToolStripMenuItem.CheckState == CheckState.Checked)
{
listBox1.Visible = true;
MessageBox.Show("显示");
}
else
{
listBox1.Visible = false;
MessageBox.Show("隐藏");
//listBox1.Hide();
}
}
private void 自动换行ToolStripMenuItem1_CheckedChanged(object sender, EventArgs e)
{
if (自动换行ToolStripMenuItem1.CheckState==CheckState.Checked)
{
richTextBox1.WordWrap = true;
}
else
{
richTextBox1.WordWrap = false;
}
}
}