C#WinForm应用程序——简易摇号系统
去年班级元旦晚会制作的要好系统,一直都忘记把代码贡献出来,把制作方法和大家说一下。
元旦party的logo是sxy同学制作的
界面背景是zlq同学制作的
最后效果图
功能介绍:
点击开始,可以在“冲冲冲”里滚动姓名
点击结束,滚动停止
在文本框里输入姓名,添加幸运儿,后台文件会多出一个名字,可用于增加概率
下面讲一下制作的方法
一、环境
安装有C#WinForm窗体程序的Visual Studio
二、项目细节设置
- 设置程序icon
点击这里,选中整个项目,按F4,进入属性界面
三、界面布局
- TabControl
拖一个TabContorl出来
在属性种设置Dock为Fill充满整个窗体 - TabPage
设置TabPage背景图片,设置page名为摇号系统 - 其他控件
button1:添加幸运儿
button2:开始/结束
label1:冲冲冲
label2:当前人数
textBox1
timer1
其他内容都是背景图片里面的
控件位置随意放,自己感觉
四、代码
- 添加按钮单机事件的时候,需要在窗体里面双击按钮,进入button1_Click事件代码里,或者在时间里面双击click事件
- 时钟timer1,用于控制姓名滚动,添加时间,需要双击timer1,或者在事件里面双击Tick事件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Rolling
{
public partial class Lucky : Form
{
//定义random的上下限初始值,防止空指针异常随便些一个数,maxValue后面会重新赋值
int minValue = 0;
int maxValue = 42;
Random r = new Random();
//定义文件路径
static string path = "Lucky.txt";
//读取文件的行数
private int line_num()
{
string[] lines = File.ReadAllLines(path);
int i = lines.Length;
return i;
}
//随机时钟
private void timer1_Tick(object sender, EventArgs e)
{
//设置随机数的上下限,标准规定的取值是,左闭右开
string[] content = File.ReadAllLines(path);
maxValue = line_num();
int i = r.Next(minValue, maxValue);
label1.Text = content[i];
timer1.Start();
}
//添加幸运儿按钮
private void button1_Click(object sender, EventArgs e)
{
//在文件末尾追加一行
FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine(textBox1.Text);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
label2.Text = "当前人数:" + line_num().ToString();
}
//抽奖开始结束按钮
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "开始")
{ button2.Text = "结束"; timer1.Start(); }
else
{ button2.Text = "开始"; timer1.Stop(); }
}
private void Form1_Load(object sender, EventArgs e)
{
label2.Text = "当前人数:"+line_num().ToString();
}
public Lucky()
{
InitializeComponent();
}
}
}
五、名称txt文件
我们在程序里面定义了一个static string path = “Lucky.txt”;
具体Lucky.txt需要需要存放在:自己的工程目录\bin\Debug
Lucky里面放姓名,每个姓名一行
到此已经完成,可以调试运行了,运行结果就和文章最开始的那样