常见键盘事件
KeyPress:在控件具有焦点并且用户按下释放某个键发生
KeyDown:首次按下某个键发生
KeyUp:释放键时发生。
举例:keypress :设置键盘输入符号
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar>'9' || e.KeyChar<'0')
{
e.Handled = true; //处理
}
}
//只能输入0-9
Listbox控件:
private void button1_Click(object sender, EventArgs e)
{
listImageName.Items.Add(textBox1.Text); //将文本框内容放到list里面
textBox1.Text="" ; //清空文本框
textBox1.Focus(); //光标定位到文本框
}
//从文本框输入内容,点击添加则放到list里面,并清空文本框重写。
举例:点击图片名字:
主要属性:
string path=@”绝对地址”; 调取图片
substring:切割图片路径
Items.Add(); 把图片名字加载到集合
image.fromfile();默认显示第一个图片
selectedindex=0;默认选择第一个内容
//让左面的文档中显示出图片的目录,然后点击对应的目录显示图片:
string[] images;
private void Form1_Load(object sender, EventArgs e)
{
string path = @"E:\我的应用数据\计算机项目\软件工程项目之CS学习\02 C#\传智播客基础实训4\20121110C#基础\资料\img";
images = Directory.GetFiles(path, "*.jpg");//把这个文件夹下面所有.jpg文件拿出来存到数组中去
for (int i = 0; i < images.Length; i++)
{
string imageName=images[i].Substring(images[i].LastIndexOf('\\')+1);//切割图片的路径,只要图片名字
listBoxImageName.Items.Add(imageName);//把图片名字加到集合中
picImage.Image = Image.FromFile(images[0]);//默认显示第一张图片
//判断这个listbox控件中是否有元素
if (listBoxImageName.Items.Count !=0)
{
//如果这个集合中有元素就把默认的选中第一个内容
listBoxImageName.SelectedIndex = 0;
}
}
}
private void listBoxImageName_SelectedIndexChanged(object sender, EventArgs e)
{
//获取当前选中图片名字的索引,把选中的索引放到存路径的数组中作为索引使用;
picImage.Image = Image.FromFile(images[listBoxImageName.SelectedIndex]);
}
Timer组件
//添加:timer, 并将enabled属性变为true
private void timer1_Tick(object sender, EventArgs e)
{
MessageBox.Show("厉害了");
}
//1s弹出一个框
Timer练习一:跑马灯
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = label1.Text.Substring(1) + label1.Text[0]; //substring是切掉第一个,目的是让他们一个一个移动起来
label2.Text = label2.Text.Substring(label2.Text.Length - 1) + label2.Text.Substring(0, label2.Text.Length - 1);
}
//让其闪烁
label2.Text = label2.Text[label2.Text.Length - 1] + label2.Text.Substring(0, label2.Text.Length - 1);//这个是让五角星从左到右循环走。
Timer练习二:小闹钟
//应用:using System.Media;
private void timer1_Tick(object sender, EventArgs e)
{
labTime.Text = DateTime.Now.ToString ();//显示当前时间
if (DateTime.Now.Second==10) //时间经过10s后播放音乐
{
//播放音乐
SoundPlayer sp=new SoundPlayer();
sp.SoundLocation = @"E:\FFOutput\罗志祥-岁堤春晓.wav";
sp.Play();
}
}
private void Form1_Load(object sender, EventArgs e)
{
labTime.Text = DateTime.Now.ToString(); //显示当前时间
}