今年公司年会,领导要我做一个小的抽奖软件,给了一组号码,要求每次抽奖抽的众多号码中的一个随机数,并且抽奖之后该号码不会参与下次抽奖。
前端代码:
<Window x:Class="WpfApp1.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfApp1"mc:Ignorable="d"Title="抽奖系统" Height="450" Width="800"PreviewTextInput="Window_PreviewTextInput"PreviewKeyDown="Window_PreviewKeyDown"><Grid><Image Source="img/2.png" Stretch="Fill"></Image><StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Center"><Button Content="抽奖" HorizontalContentAlignment="Center" Width="200" Height="80" FontSize="50" FontWeight="Bold" x:Name="prize" Background="Red" Foreground="Gold" Click="prize_Click" Margin="100"></Button> </StackPanel><Label x:Name="PrizeCode" FontSize="300" Foreground="Gold" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"></Label></Grid>
</Window>
后台代码:
public MainWindow(){InitializeComponent();#region 启动时窗口最大化Rect rc = SystemParameters.WorkArea;this.Left = 0;this.Top = 0;this.Width = rc.Width;this.Height = rc.Height;#endregionSystem.Timers.Timer timer = new System.Timers.Timer();timer.Interval = 50;timer.Start();timer.Elapsed += Timer_Elapsed;}string input = string.Empty;Random random = new Random();List<int> arr = new List<int>{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85};int code = 0; int j = 85;bool isPrize = false;private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e){if (isPrize){code = arr[random.Next(0, j)];this.PrizeCode.Dispatcher.BeginInvoke(new Action(() => {PrizeCode.Content = code;}));if (input == "Return")//键盘输入回车键{arr.Remove(code);isPrize = false;input = " ";if (j > 0){j--;}}} }private void prize_Click(object sender, RoutedEventArgs e){isPrize = true; }private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e){//input = e.Text;//MessageBox.Show(input);}private void Window_PreviewKeyDown(object sender, KeyEventArgs e){input = e.Key.ToString();//获取电脑键盘输入// MessageBox.Show(e.Key.ToString());}