C#创建随机更换背景图片的窗体的方法:创建特殊窗体

目录

一、涉及到的知识点

1.图片资源管理器设计Resources.Designer.cs

2.把图片集按Random.Next方法随机化

3.BackgroundImage属性

二、实例设计

1. Resources.Designer.cs

2.Form1.Designer.cs

3.Form1.cs

4.生成效果


        很多时候,我们需要每次打开窗体时能够更换一副新的背景图片。

一、涉及到的知识点

1.图片资源管理器设计Resources.Designer.cs

         把项目需要的图片资源设计到Resources.Designer.cs里,详见本文作者最近写的其它文章:C#手动改变自制窗体的大小-CSDN博客 https://wenchm.blog.csdn.net/article/details/137027140

2.把图片集按Random.Next方法随机化

        Random类表示伪随机数生成器,它是一种能够产生满足某些随机性统计要求的数字序列的设备,其Next方法用来返回一个小于所指定最大值的非负随机数,语法格式如下:

public virtual int Next(int maxValue)
参数说明
maxValue:要生成的随机数的上界(随机数不能取该上界值)。maxValue必须大于或等于零。
返回值:大于或等于零且小于maxValue的32位带符号整数,即返回的值范围包括零但不包括maxValue。
 string[] strImages = ["01", "02", "03", "04", "05"];//定义一个字符串数组,用来存储背景图片列表
 Random rdn = new();                                 //定义一个伪随机数生成器对象
 int intIndex = rdn.Next(0, strImages.Length - 1);   //产生一个随机数

3.BackgroundImage属性

        BackgroundImage属性用来获取或设置在窗体中显示的背景图像。语法格式如下:

public virtual Image BackgroundImage {get;set;}
参数说明
属性值:一个Image图像,它表示在窗体的背景中显示的图像。

        本例中,让窗体的BackgroundImage属性值由资源图片随机赋值;

BackgroundImage = Properties.Resources.GetObject(strImages[intIndex].ToString());
BackgroundImageLayout = ImageLayout.Stretch;

二、实例设计

1. Resources.Designer.cs

        注意:本实例除了自动设计之外,还需要手工设计GetObject方法。

//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.42000
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------

namespace _183.Properties {
    using System;
    
    
    /// <summary>
    ///   一个强类型的资源类,用于查找本地化的字符串等。
    /// </summary>
    // 此类是由 StronglyTypedResourceBuilder
    // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
    // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
    // (以 /str 作为命令选项),或重新生成 VS 项目。
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {
        
        private static global::System.Resources.ResourceManager resourceMan;
        
        private static global::System.Globalization.CultureInfo resourceCulture;
        
        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }
        
        /// <summary>
        ///   返回此类使用的缓存的 ResourceManager 实例。
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("_183.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }
        
        /// <summary>
        ///   重写当前线程的 CurrentUICulture 属性,对
        ///   使用此强类型资源类的所有资源查找执行重写。
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }
        
        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap _01 {
            get {
                object obj = ResourceManager.GetObject("_01", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
        
        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap _02 {
            get {
                object obj = ResourceManager.GetObject("_02", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
        
        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap _03 {
            get {
                object obj = ResourceManager.GetObject("_03", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
        
        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap _04 {
            get {
                object obj = ResourceManager.GetObject("_04", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
        
        /// <summary>
        ///   查找 System.Drawing.Bitmap 类型的本地化资源。
        /// </summary>
        internal static System.Drawing.Bitmap _05 {
            get {
                object obj = ResourceManager.GetObject("_05", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        internal static Bitmap GetObject(string v)
        {
            return v switch
            {
                "05" => _05,
                "04" => _04,
                "03" => _03,
                "02" => _02,
                "01" => _01,
                _ => null
            };
        }
    }
}

2.Form1.Designer.cs

namespace _183
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            SuspendLayout();
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(331, 244);
            Name = "Form1";
            Text = "Form1";
            Load += Form1_Load;
            ResumeLayout(false);
        }

        #endregion
    }
}

3.Form1.cs

// 随机更换背景图片
namespace _183
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] strImages = ["01", "02", "03", "04", "05"];//定义一个字符串数组,用来存储背景图片列表
            Random rdn = new();                                 //定义一个伪随机数生成器对象
            int intIndex = rdn.Next(0, strImages.Length - 1);   //产生一个随机数
            BackgroundImage = Properties.Resources.GetObject(strImages[intIndex].ToString());
            BackgroundImageLayout = ImageLayout.Stretch;
        }
    }
}

4.生成效果

         每次打开应用都随机更换窗体的背景。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wenchm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值