WinForm+C#小案例--->爱心跑马灯演示

爱心跑马灯演示:

实现这个案例我们可以分为3个步骤

效果演示:

步骤 1:创建 Winform 项目并设计界面

  1. Label 控件 :命名为 lblMarquee
  2. Timer 控件 :命名为 timerMarquee

步骤 2:设置控件属性

  • lblMarquee 属性 :
    • Text:可以先清空,我们会在代码中设置
    • Font:选择一个合适的字体和大小,让爱心显示得更清楚
    • AutoSize:设置为 True
    • TextAlign:设置为 MiddleCenter,让文本在 Label 内居中
    • BackColor:可以设置一个背景色,方便观察
  • timerMarquee 属性 :
    • Interval:设为 200(单位为毫秒,数值越小,切换越快)
    • Enabled:设为 True

步骤 3:编写代码实现切换逻辑

cs 复制代码
using System;
using System.Windows.Forms;

namespace 跑马灯
{
    public partial class Form1 : Form
    {
        // 用于记录当前实心爱心(♥)在字符数组中的位置索引
        private int currentPosition = 0;
        // 定义一个空的心形,用于填充其他位置
        private const char EmptyHeart = '♡';
        // 定义一个实心的心形
        private const char SolidHeart = '♥';
        public Form1()
        {
            InitializeComponent();
        }

        // 窗体加载事件
        private void Form1_Load(object sender, EventArgs e)
        {
            UpdateMarqueeText();
        }

        /// <summary>
        /// 根据当前位置更新Label的文本
        /// </summary>
        // 私有方法:UpdateMarqueeText()
        // 作用:这是核心逻辑方法,专门用于根据 currentPosition 的值来构建并更新 Label 控件的显示文本
        private void UpdateMarqueeText()
        {
            // 创建一个字符数组
            char[] displayText = new char[21];

            for (int i = 0; i < displayText.Length; i++)
            {
                // 三元运算符:条件 ? 表达式1 : 表达式2
                //判断当前循环的索引i是否等于当前实心爱心的位置 currentPosition
                displayText[i] = (i == currentPosition) ? SolidHeart : EmptyHeart;
            }
            // 将构建好的字符数组 displayText 转换为一个字符串
            lblMarquee.Text = new string(displayText);
        }

        /// <summary>
        /// 定时器 Tick 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {

            // 移动到下一个位置
            currentPosition++;

            // 当爱心走到最后一个位置时,重置到第一个位置
            if (currentPosition >= 21)
            {
                currentPosition = 0;
            }

            // 根据新位置更新显示的文本
            UpdateMarqueeText();
        }
    }
}

希望对大家有所帮助。感谢大家的关注和点赞。

相关推荐
噢,我明白了2 小时前
JAVA中的一些基础应用知识点
java·开发语言
寂寞的船2 小时前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
时间的拾荒人3 小时前
Redis 入门详解:核心特性、重要文件与全局命令实战
开发语言·redis·面试
敲上瘾3 小时前
Qt Widgets入门:项目模板解析与Hello World
开发语言·数据库·c++·qt·ui·qt6.3
码途行者5 小时前
网站的SQL 注入:从攻击原理到防御措施
开发语言·sql·php
旖旎夜光5 小时前
【C++ 基础入门】C++ 多态(中):虚函数表、多态原理与动静绑定
开发语言·c++·笔记·学习
你看我名字5 小时前
产品参数昨天还对,今天已过期:数眼智能与大模型应用如何做资料版本校验
开发语言·架构
1-1=06 小时前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
老秦包你会6 小时前
计算机网络第二课 ----Socket(套接字)编程预备
开发语言·计算机网络·php
旖旎夜光6 小时前
【C++ 基础入门】C++多态(下):单/多继承虚表、多态补充与 21 道高频题
开发语言·c++·笔记·学习