目录:程序员
3. 创建事件模板,而后调用this
5. 用代码执行事件firefox
1. 实现代码的等待操做 |
System.Threading.Thread.Sleep(Int32):将当前线程挂起指定的毫秒数。线程
for (int i = 0; i < 100; i++) { System.Threading.Thread.Sleep(50); label1.Text = i.ToString(); label1.Refresh(); }
2. 实现文件夹/文件打开操做 |
System.Diagnostics.Process.Start(String, String):用指定的程序打开指定路径的文件。orm
// 1. 用Explorer.exe打开文件夹: System.Diagnostics.Process.Start("Explorer.exe",@"D:\DOCUMENTS\"); System.Diagnostics.Process.Start("Explorer.exe",@"D:\DOCUMENTS"); // 2. 用notepad.exe打开记事本: System.Diagnostics.Process.Start("notepad.exe",@"F:\Desktop\1.txt"); // 3. 用Word的快捷方式打开Word文件: System.Diagnostics.Process.Start(@"F:\Desktop\Word 2010", @"F:\Desktop\1.docx"); // 4. 用Firefox打开网址:www.baidu.com: System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe", "www.baidu.com");
3. 创建事件模板,而后调用 |
因为事件的监视及管理是由Application对象进行的,程序员不须要知道用户什么时候响应事件或者是响应了什么事件,只须要为事件添加响应方法便可。添加方法”+=“,取消方法”-=“。参数sender为事件发出者;e为事件的附加数据,事件不一样,e也不一样。对象
示例一:四个事件调用一个方法blog
public Form1() { InitializeComponent(); textBox2.MouseMove += new MouseEventHandler(textBox_MouseMove); //调用事先创建的模板 textBox3.MouseMove += new MouseEventHandler(textBox_MouseMove); //四个TextBox能够实现相同的功能 textBox4.MouseMove += new MouseEventHandler(textBox_MouseMove); //经过单击Tab键,能够自动实现后半部分 textBox5.MouseMove += new MouseEventHandler(textBox_MouseMove); //经过再单击Tab键,能够实现函数的自动生成 } private void textBox_MouseMove(object sender, MouseEventArgs e) //创建事件模板 { TextBox tb = sender as TextBox; tb.BackColor = Color.Red; }
示例二:TextBox_KeyPress 只容许数字输入
public Form1() { InitializeComponent(); textBox1.KeyPress += new KeyPressEventHandler(textBox_KeyPress); //单击tab键出现一行 textBox2.KeyPress += new KeyPressEventHandler(textBox_KeyPress); //双击tab键出现N行 textBox3.KeyPress += new KeyPressEventHandler(textBox_KeyPress); textBox4.KeyPress += new KeyPressEventHandler(textBox_KeyPress); } private void textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != 8 && e.KeyChar != 13) { e.Handled = true; } }
4. 用代码在Form中写控件,同时能够编写控件数组 |
首先用Label创建数组,接下来遍历数组,给数组的每一个要素声明Label,接下来用Controls的Add方法将用代码写的控件添加到控件集中,同时设置控件的位置和长宽。
private void Form1_Load(object sender, EventArgs e) { Label[] lbs = new Label[5]; //创建标签控件数组 for (int i = 0; i < lbs.Length; i++) { lbs[i] = new Label(); //在声明下Label类 this.Controls.Add(lbs[i]); //将Label加到控件集中 lbs[i].Left = 714; lbs[i].Top = 30 * i + 14; //设置控件的位置 lbs[i].Width = 400; //设置控件的宽度 lbs[i].Text = "hhhhh"; //设置文本内容 //批量写入事件 lbs[i].MouseMove += new MouseEventHandler(Label_MouseMove); } } void Label_MouseMove(object sender, MouseEventArgs e) { Label l = sender as Label; l.BackColor = Color.GreenYellow; }
5. 用代码执行事件 |
首先是双击控件,生成一个button1_Click(object sender,EventArgs e)的函数,经过代码直接调用这个函数,既能够调用这个事件,说到底就是调用函数。
private void button1_Click(object sender, EventArgs e) { axWindowsMediaPlayer1.URL = musicPath + @"music\1.mp3"; } private void timer1_Tick(object sender, EventArgs e) { button1_Click(button1, e); //经过代码调用按钮单击事件,其余事件调用是相似的! }