时间:2022-12-04 12:56:18 | 栏目:.NET代码 | 点击:次
本文实例为大家分享了C#实现简化QQ聊天窗口的具体代码,供大家参考,具体内容如下
如图样式,详细步骤如下
整个窗体设置
private void Form1_Load(object sender, EventArgs e) { this.BackColor = Color.Chocolate;//设置窗体背景颜色 this.Text = "与张某正在聊天...";//设置窗体文本内容 this.Size = new Size(450,400);//设置窗体大小 //设置窗体在工作区居中显示 this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width/2-this.Width/2,Screen.PrimaryScreen.WorkingArea.Height/2-this.Height/2) ; }
添加两个textbox分别为聊天内容与输入框;
添加两个button分别为抖一抖与发送;
抖动事件
private void button1_Click(object sender, EventArgs e) { //抖动事件 int x = this.Left; int y = this.Top; for (int n = 0; n < 3; n++) { //添加using System.Threading; this.Location = new Point(x - 3, y); Thread.Sleep(20);//挂起20毫秒 this.Location = new Point(x - 3, y - 3); Thread.Sleep(20); this.Location = new Point(x, y - 3); Thread.Sleep(20); this.Location = new Point(x + 3, y - 3); Thread.Sleep(20); this.Location = new Point(x + 3, y + 3); Thread.Sleep(20); this.Location = new Point(x, y + 3); Thread.Sleep(20); this.Location = new Point(x - 3, y + 3); Thread.Sleep(20); this.Location = new Point(x - 3, y); Thread.Sleep(20); this.Location = new Point(x, y); } }
发送事件
private void button2_Click(object sender, EventArgs e) { //发送时间 if (textBox2.Text!="")//当输入栏不为空内容时 { //textbox1内容等于textbox1原本内容(聊天记录)+现在的时间+发话人+textbox2的输入内容 textBox1.Text = textBox1.Text + DateTime.Now + "\r\n" + "李某:"+textBox2.Text+"\r\n"; textBox2.Text= "";//清空输出框 } }
添加滚动条
private void textBox1_TextChanged(object sender, EventArgs e) { //在textbox1属性设置scrollbars滚动条显示 //滚轮显示最后一行 this.textBox1.SelectionStart = this.textBox1.Text.Length; this.textBox1.ScrollToCaret(); //设置lcon类型图标 }
添加键盘事件
(Enter实现发送功能)
private void textBox2_KeyDown(object sender, KeyEventArgs e) { //在输入框内添加键盘事件,Enter实现发送功能 if (e.KeyCode == Keys.Enter) { button2_Click(sender, e); } }