You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C#实现类似youareanidiot病毒的窗体弹跳效果

C# 窗体弹跳效果实现指南(WinForm 版本,适合初学者)

基础准备

新建 Windows Forms 项目即可,无需引入额外依赖库。

一、单窗体碰边界回弹实现

  1. 在你的窗体类中声明两个全局变量,用来控制横向、纵向的移动速度:
    // 可自行调整数值大小控制移动速度
    int moveSpeedX = 5;
    int moveSpeedY = 5;
    Random random = new Random(); // 如果需要加闪烁效果可以提前声明
    
  2. 从工具箱拖动一个 Timer 控件到窗体设计界面,设置属性:
    • Interval 设为 15~20(单位毫秒,控制移动流畅度,数值越小移动越快)
    • Enabled 设为 true(程序启动就自动开始移动)
  3. 双击 Timer 控件,在自动生成的 Tick 事件中写入以下代码:
    private void timer1_Tick(object sender, EventArgs e)
    {
        // 按当前速度移动窗体
        this.Left += moveSpeedX;
        this.Top += moveSpeedY;
    
        // 碰到屏幕左右边缘,横向速度反向
        if (this.Left <= 0 || this.Right >= Screen.PrimaryScreen.WorkingArea.Width)
        {
            moveSpeedX = -moveSpeedX;
            // 可选:碰边时切换背景色实现闪烁效果
            // this.BackColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
        }
        // 碰到屏幕上下边缘,纵向速度反向
        if (this.Top <= 0 || this.Bottom >= Screen.PrimaryScreen.WorkingArea.Height)
        {
            moveSpeedY = -moveSpeedY;
            // 可选:碰边时切换背景色实现闪烁效果
            // this.BackColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
        }
    }
    

小提示:如果需要窗体可以覆盖任务栏弹跳,把代码中的 Screen.PrimaryScreen.WorkingArea 替换为 Screen.PrimaryScreen.Bounds 即可。

二、多窗体同时弹跳实现方案

你已经写好的带弹跳逻辑的窗体可以直接复用,只要批量创建实例即可:

  1. 打开项目下的 Program.cs 文件,修改入口代码如下:
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Random positionRnd = new Random();
        // 此处数值可以调整,控制生成的窗体数量
        int formCount = 8;
    
        for (int i = 0; i < formCount; i++)
        {
            // 你的弹跳窗体类名,默认是Form1
            Form bounceForm = new Form1();
            bounceForm.StartPosition = FormStartPosition.Manual;
            // 给每个窗体随机生成初始位置,避免重叠
            bounceForm.Left = positionRnd.Next(Screen.PrimaryScreen.WorkingArea.Width - bounceForm.Width);
            bounceForm.Top = positionRnd.Next(Screen.PrimaryScreen.WorkingArea.Height - bounceForm.Height);
            bounceForm.Show();
        }
        // 启动消息循环,所有窗体关闭后程序自动退出
        Application.Run();
    }
    

内容的提问来源于stack exchange,提问作者MaiSakurajima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:45:06