4月30日 窗体应用程序
键盘事件练习
using System;
using System.Drawing;
using System.Windows.Forms;
namespace KeyEventGame
{
public partial class Form1 : Form
{
// 用来记录当前按住的键
private char currentKey;
public Form1()
{
InitializeComponent();
// 让窗体优先接收键盘事件(必须加,否则事件可能不触发)
this.KeyPreview = true;
}
// ===================== 1. KeyDown 按下瞬间触发 =====================
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// 显示事件信息
lblInfo.Text = $"触发:KeyDown | 按键代码:{e.KeyCode}";
// 只处理字母、数字、空格(过滤功能键如Shift、Ctrl)
if (char.IsLetterOrDigit((char)e.KeyCode) || e.KeyCode == Keys.Space)
{
// 空格特殊处理
if (e.KeyCode == Keys.Space)
currentKey = '□';
else
currentKey = (char)e.KeyCode;
// 显示字符 + 随机颜色
lblChar.Text = currentKey.ToString();
lblChar.ForeColor = GetRandomColor();
}
}
// ===================== 2. KeyPress 按下后触发(晚于KeyDown) =====================
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
// 仅显示事件,不做逻辑,方便观察触发顺序
lblInfo.Text += "\n触发:KeyPress | 输入字符:" + e.KeyChar;
}
// ===================== 3. KeyUp 松开按键触发 =====================
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
// 松开按键 → 清空大字符
lblChar.Text = "";
lblInfo.Text = $"触发:KeyUp | 松开按键:{e.KeyCode}\n等待下次按键...";
}
// 辅助方法:生成随机颜色(让界面更好看)
private Color GetRandomColor()
{
Random rand = new Random();
return Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
}
}
}
案例1:猜大小
public partial class Form1 : Form
{
// 全局变量:随机数、猜测次数
private int targetNumber;
private int guessCount;
// 将控件声明为字段
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
public Form1()
{
InitializeComponent();
// 按钮
button1 = new System.Windows.Forms.Button();
button1.Size = new System.Drawing.Size(100, 50);
button1.Text = "猜大小";
// 计算居中位置
int x = (this.Width - button1.Width) / 2;
int y = (this.Height - button1.Height) / 2;
button1.Location = new System.Drawing.Point(x, y);
button1.Click += button1_Click;
this.Controls.Add(button1);
// 文本框
textBox1 = new System.Windows.Forms.TextBox();
textBox1.Size = new System.Drawing.Size(100, 30);
int x2 = (this.Width - textBox1.Width) / 2;
int y2 = (this.Height - textBox1.Height) / 2;
textBox1.Location = new System.Drawing.Point(x2, y2 - 50); // 文本框在按钮上方
this.Controls.Add(textBox1);
// 标签
label1 = new System.Windows.Forms.Label();
label1.Text = "Hello World";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
StartNewGame();
}
public void StartNewGame()
{
// 初始化
Random random = new Random();
targetNumber = random.Next(1, 101); // 生成 1~100 随机数
guessCount = 0;
label1.AutoSize = true;
label1.Text = "我已经想好了 1~100 之间的数字,来猜猜看吧!";
label1.Location = new Point((this.Width - label1.Width) / 2, 50); // 标签居中
textBox1.Clear();
textBox1.Focus();
}
public void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show("Hello");
// 判断输入是否为有效数字
if (!int.TryParse(textBox1.Text, out int userGuess))
{
MessageBox.Show("请输入有效的整数!", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox1.Clear();
textBox1.Focus();
return;
}
guessCount++; // 次数+1
// 判断大小
if (userGuess < targetNumber)
{
label1.Text = $"第 {guessCount} 次:太小了,再大一点!";
}
else if (userGuess > targetNumber)
{
label1.Text = $"第 {guessCount} 次:太大了,再小一点!";
}
else
{
// 猜对了
label1.Text = $"🎉 恭喜你猜对了!答案是 {targetNumber},一共猜了 {guessCount} 次!";
MessageBox.Show(label1.Text, "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
StartNewGame(); // 自动重新开始
}
textBox1.Clear();
textBox1.Focus();
}
}
弹窗恶作剧
using System;
using System.Windows.Forms;
namespace FunnyPrank
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "趣味小游戏";
this.Size = new System.Drawing.Size(300, 150);
Button btn = new Button();
btn.Text = "开始游戏";
btn.Size = new System.Drawing.Size(120, 40);
btn.Location = new System.Drawing.Point(80, 40);
btn.Click += btn_Click;
this.Controls.Add(btn);
}
private void btn_Click(object sender, EventArgs e)
{
// 1
MessageBox.Show("你确定要点吗?");
// 2
MessageBox.Show("真的要点吗?");
// 3
MessageBox.Show("那我可开始了哦!");
// 4
MessageBox.Show("准备好被弹窗轰炸了吗?");
// 5
MessageBox.Show("三!");
// 6
MessageBox.Show("二!");
// 7
MessageBox.Show("一!");
// 8
MessageBox.Show("开始啦!");
// 9
MessageBox.Show("哈哈哈哈哈哈");
// 10
MessageBox.Show("点不掉吧!");
// 11
MessageBox.Show("是不是有点烦了?");
// 12
MessageBox.Show("烦就对了!");
// 13
MessageBox.Show("继续点!");
// 14
MessageBox.Show("别想关掉我!");
// 15
MessageBox.Show("你越急我越开心");
// 16
MessageBox.Show("哈哈哈哈");
// 17
MessageBox.Show("还没点完呢!");
// 18
MessageBox.Show("才十几个而已");
// 19
MessageBox.Show("坚持住!");
// 20
MessageBox.Show("马上就二十个了!");
// 21
MessageBox.Show("二十个啦!");
// 22
MessageBox.Show("手酸不酸?");
// 23
MessageBox.Show("酸也没用!");
// 24
MessageBox.Show("继续点!");
// 25
MessageBox.Show("我还能弹一百个!");
// 26
MessageBox.Show("你敢信?");
// 27
MessageBox.Show("反正你关不掉");
// 28
MessageBox.Show("认命吧!");
// 29
MessageBox.Show("哈哈哈哈");
// 30
MessageBox.Show("三十个咯!");
// 31
MessageBox.Show("三十个啦!");
// 32
MessageBox.Show("是不是想砸电脑?");
// 33
MessageBox.Show("别别别!");
// 34
MessageBox.Show("马上就一半了!");
// 35
MessageBox.Show("加油加油!");
// 36
MessageBox.Show("你是最棒的!");
// 37
MessageBox.Show("点弹窗小能手!");
// 38
MessageBox.Show("继续继续!");
// 39
MessageBox.Show("不要停!");
// 40
MessageBox.Show("四十个啦!");
// 41
MessageBox.Show("四十个啦!");
// 42
MessageBox.Show("一半了一半了!");
// 43
MessageBox.Show("激动不激动?");
// 44
MessageBox.Show("兴奋不兴奋?");
// 45
MessageBox.Show("可惜还没完!");
// 46
MessageBox.Show("哈哈哈哈");
// 47
MessageBox.Show("继续点!");
// 48
MessageBox.Show("手还好吗?");
// 49
MessageBox.Show("不行也得行!");
// 50
MessageBox.Show("五十个啦!");
// 51
MessageBox.Show("五十个啦!");
// 52
MessageBox.Show("过半了哦!");
// 53
MessageBox.Show("是不是看到希望了?");
// 54
MessageBox.Show("并没有!");
// 55
MessageBox.Show("还有五十个!");
// 56
MessageBox.Show("惊不惊喜?");
// 57
MessageBox.Show("意不意外?");
// 58
MessageBox.Show("继续点!");
// 59
MessageBox.Show("不要放弃!");
// 60
MessageBox.Show("六十个啦!");
// 61
MessageBox.Show("六十个啦!");
// 62
MessageBox.Show("离胜利不远了!");
// 63
MessageBox.Show("大概还有四十个吧!");
// 64
MessageBox.Show("哈哈哈哈");
// 65
MessageBox.Show("是不是想骂我?");
// 66
MessageBox.Show("骂也没用!");
// 67
MessageBox.Show("继续点!");
// 68
MessageBox.Show("坚持就是胜利!");
// 69
MessageBox.Show("奥利给!");
// 70
MessageBox.Show("七十个啦!");
// 71
MessageBox.Show("七十个啦!");
// 72
MessageBox.Show("快了快了!");
// 73
MessageBox.Show("还有三十个!");
// 74
MessageBox.Show("加油加油!");
// 75
MessageBox.Show("你可以的!");
// 76
MessageBox.Show("不要放弃治疗!");
// 77
MessageBox.Show("继续点!");
// 78
MessageBox.Show("马上就八十了!");
// 79
MessageBox.Show("冲鸭!");
// 80
MessageBox.Show("八十个啦!");
// 81
MessageBox.Show("八十个啦!");
// 82
MessageBox.Show("只剩二十个了!");
// 83
MessageBox.Show("激动的心!");
// 84
MessageBox.Show("颤抖的手!");
// 85
MessageBox.Show("继续点!");
// 86
MessageBox.Show("不要停!");
// 87
MessageBox.Show("胜利就在眼前!");
// 88
MessageBox.Show("哈哈哈哈");
// 89
MessageBox.Show("还有十几个!");
// 90
MessageBox.Show("九十个啦!");
// 91
MessageBox.Show("九十个啦!");
// 92
MessageBox.Show("只剩十个了!");
// 93
MessageBox.Show("九!");
// 94
MessageBox.Show("八!");
// 95
MessageBox.Show("七!");
// 96
MessageBox.Show("六!");
// 97
MessageBox.Show("五!");
// 98
MessageBox.Show("四!");
// 99
MessageBox.Show("三!");
// 100
MessageBox.Show("恭喜你!终于点完100个弹窗了!可以去休息了!");
}
}
}
弹窗恶作剧
using System;
using System.Windows.Forms;
namespace PrankStory
{
public partial class Form1 : Form
{
// 要循环的故事内容
private string[] story = new string[]
{
"我给你讲故事吧",
"从前有座山",
"山里有个庙",
"庙里有个老和尚",
"在给小和尚讲故事",
"讲的什么呢?"
};
public Form1()
{
InitializeComponent();
// 设置窗口
this.Text = "整蛊小游戏";
this.Size = new System.Drawing.Size(300, 150);
// 创建按钮
Button btnStart = new Button();
btnStart.Text = "开始游戏";
btnStart.Size = new System.Drawing.Size(120, 40);
btnStart.Location = new System.Drawing.Point(80, 40);
btnStart.Click += BtnStart_Click;
this.Controls.Add(btnStart);
}
private void BtnStart_Click(object sender, EventArgs e)
{
// 连续弹 100 次
for (int i = 0; i < 100; i++)
{
// 循环取故事内容
string msg = story[i % story.Length];
MessageBox.Show(msg, "故事时间~", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
MessageBox.Show("终于讲完啦!!", "结束", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
窗体随机背景色
using System;
using System.Drawing;
using System.Windows.Forms;
namespace BackgroundColorChanger
{
public partial class ColorForm : Form
{
// 随机数生成器
private Random random = new Random();
public ColorForm()
{
InitializeComponent();
// 设置按钮文字
button1.Text = "红色";
button2.Text = "蓝色";
button3.Text = "绿色";
button4.Text = "随机";
button5.Text = "默认";
// 设置窗体标题和大小
this.Text = "背景颜色切换器";
this.Size = new Size(500, 300);
// 初始背景色
this.BackColor = SystemColors.Control;
}
// ========== 红色按钮 ==========
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = Color.Red;
// 可选:显示当前颜色信息
this.Text = "背景颜色:红色";
}
// ========== 蓝色按钮 ==========
private void button2_Click(object sender, EventArgs e)
{
this.BackColor = Color.Blue;
this.Text = "背景颜色:蓝色";
}
// ========== 绿色按钮 ==========
private void button3_Click(object sender, EventArgs e)
{
this.BackColor = Color.Green;
this.Text = "背景颜色:绿色";
}
// ========== 随机颜色按钮 ==========
private void button4_Click(object sender, EventArgs e)
{
// 生成随机RGB颜色
int r = random.Next(0, 256); // 红色分量 0-255
int g = random.Next(0, 256); // 绿色分量 0-255
int b = random.Next(0, 256); // 蓝色分量 0-255
Color randomColor = Color.FromArgb(r, g, b);
this.BackColor = randomColor;
// 显示RGB值
this.Text = $"随机颜色:R={r}, G={g}, B={b}";
}
// ========== 恢复默认按钮 ==========
private void button5_Click(object sender, EventArgs e)
{
this.BackColor = SystemColors.Control; // 系统默认颜色
this.Text = "背景颜色切换器";
}
}
}
生成5个div
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Panel panel = new Panel();
panel.Size = new Size(50, 50);
panel.BackColor = Color.Red;
panel.Location = new Point(50 + i * 60, 60);
this.Controls.Add(panel);
}
}
窗体属性
// 设置窗体属性
this.Text = "🎨 色彩工厂 v1.0";
this.Size = new Size(400, 300);
this.BackColor = Color.FromArgb(245, 245, 90);
this.Location = new Point(100, 100);
this.StartPosition = FormStartPosition.CenterScreen;
this.WindowState = FormWindowState.Maximized;
_myButton = new Button();
_myButton.Size = new Size(100, 30);
_myButton.Text = "点我";
_myButton.Location = new Point(50, 100);
this.Controls.Add(_myButton);
聊天
public partial class Form1 : Form
{
// 3.声明字段str
public string str;
public Form1()
{
InitializeComponent();
}
// 1.点击button1时,执行花括号里的代码
private void button1_Click(object sender, EventArgs e)
{
// 2.读取textBox1的内容,并赋值给变量str
str = textBox1.Text;
// 4. 把获取到的str赋值给textBox2.Text
textBox2.Text += comboBox1.Text + ":" + str + "\r\n";
// 5.清空textBox1的text属性值
textBox1.Text = "";
// 6.为textBox2添加背景色
textBox2.BackColor = Color.FromArgb(155,255,0);
//textBox2.BackColor = Color.Yellow;
}
}
变形盒子
- panel1.Width // 大、中、小
- panel1.Height
- panel1.BackColor
- panel1.FixedSingle
字号大小
- textBox
private void button1_Click(object sender, EventArgs e)
{
// 获取文本框当前的字体大小
float currentSize = textBox1.Font.Size;
// 创建新字体:字体家族不变,字号+1
textBox1.Font = new Font(textBox1.Font.FontFamily, currentSize + 1);
}
微博字数统计
要求:
- 实时统计字符数
- 0~200:黑色
- >200:红色,并显示超出多少字
界面控件
textBox1:输入文字的框(允许多行)label1:用来显示字数统计
实现思路
- 在
textBox1_TextChanged事件里写逻辑 - 获取长度 → 判断颜色 → 显示文字
- 超过200时,额外显示
(超出XX字)
完整代码
private void textBox1_TextChanged(object sender, EventArgs e)
{
// 获取当前字符数量
int count = textBox1.Text.Length;
if (count > 0 && count <= 200)
{
// 正常范围:黑色
label1.ForeColor = Color.Black;
label1.Text = $"已输入:{count} 字";
}
else if (count > 200)
{
// 超出范围:红色,并显示超出数量
int over = count - 200;
label1.ForeColor = Color.Red;
label1.Text = $"已输入:{count} 字(超出 {over} 字)";
}
else
{
// 没有文字时
label1.ForeColor = Color.Black;
label1.Text = "已输入:0 字";
}
}
效果说明
- 输入 1~200 字:
已输入:XX 字→ 黑色 - 输入 201 字及以上:
已输入:XX 字(超出 X 字)→ 红色 - 清空时:
已输入:0 字→ 黑色
如果你想限制最多只能输200字 可以在事件最前面加一句:
if (textBox1.Text.Length > 200)
{
textBox1.Text = textBox1.Text.Substring(0, 200);
textBox1.SelectionStart = 200;
}
展开文字
using System;
using System.Windows.Forms;
namespace TextToggleApp
{
public class MainForm : Form
{
private TextBox textBox;
private Button toggleButton;
private string fullText;
private bool flag = true; // 对应原 JS 中的 on 变量
public MainForm()
{
// 初始化窗体
this.Text = "文本展开/收缩示例";
this.Size = new System.Drawing.Size(600, 400);
this.StartPosition = FormStartPosition.CenterScreen;
// 完整文本内容(与原 HTML 中的 <p> 内容一致)
fullText = "通过对元宇宙构思和概念的“考古”,可以从时空性、真实性、独立性、连接性四个方面去交叉定义元宇宙。" +
"从时空性来看,元宇宙是一个空间维度上虚拟而时间维度上真实的数字世界;从真实性来看,元宇宙中既有现实世界的数字化复制物," +
"也有虚拟世界的创造物;从独立性来看,元宇宙是一个与外部真实世界既紧密相连,又高度独立的平行空间;从连接性来看," +
"元宇宙是一个把网络、硬件终端和用户囊括进来的一个永续的、广覆盖的虚拟现实系统。";
// 文本框:用于显示文本(只读、多行、带滚动条)
textBox = new TextBox
{
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Vertical,
Dock = DockStyle.Fill,
Font = new System.Drawing.Font("宋体", 10F)
};
// 按钮:用于切换显示状态
toggleButton = new Button
{
Text = "收缩",
Dock = DockStyle.Bottom,
Height = 40,
Font = new System.Drawing.Font("宋体", 10F)
};
toggleButton.Click += ToggleButton_Click;
// 将控件添加到窗体
this.Controls.Add(textBox);
this.Controls.Add(toggleButton);
// 初始显示完整文本
textBox.Text = fullText;
}
private void ToggleButton_Click(object sender, EventArgs e)
{
// 模拟原 JS 的 onclick 逻辑:完全依照原 JS 的 if(on) 分支行为
if (flag)
{
// 截取前 20 个字符(注意长度不足时的处理)
string truncated = fullText.Length > 20 ? fullText.Substring(0, 20) : fullText;
textBox.Text = truncated;
toggleButton.Text = "收缩";
}
else
{
textBox.Text = fullText;
toggleButton.Text = "展开";
}
// 翻转标志位
flag = !flag;
}
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
移动文字
private async void button2_Click(object sender, EventArgs e)
{
// 先清空右边文本框
textBox2.Clear();
// 循环:每次取第一个字符
while (textBox1.Text.Length > 0)
{
// 取第一个字
char firstChar = textBox1.Text[0];
// 加到右边
textBox2.AppendText(firstChar.ToString());
// 左边删除第一个字(真正移动)
textBox1.Text = textBox1.Text.Substring(1);
// 等待1秒(不会卡死界面)
await Task.Delay(1000);
}
}