随机改变控件背景颜色

平时做C#中的WPF时需要对控件背景颜色进行随机调整,如下是解决这一问题的相关代码:

DispatcherTimer timer = new DispatcherTimer();
        public MainWindow()
        {
            InitializeComponent();
            //(2)
            timer.Interval = TimeSpan.FromMilliseconds(500);
            timer.Tick += Timer_Tick;
            //(3)
            timer.Start();
        }

        Random ran = new Random();
        private void Timer_Tick(object sender, EventArgs e)
        {
            int a= ran.Next(0, 256);
            int r = ran.Next(0, 256);
            int g = ran.Next(0, 256);
            int b = ran.Next(0, 256);
            Color c = Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b);
            this.Background = new SolidColorBrush(c);
        }

  通过时钟变化生成随机数,从而改变,r,g,b的值而改变背景颜色。

猜你喜欢

转载自www.cnblogs.com/lcy-4/p/12707508.html