Search code examples
c#wpfbuttonrandomclick

C# WPF click random button


I have multiple buttons on WPF that perform Click method

 <Grid Margin="0,0,490,170">
    <Grid.RowDefinitions>
        <RowDefinition Height="0*"/>
        <RowDefinition Height="18*"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button x:Name="button00" HorizontalAlignment="Left" Height="82" Margin="0,1,-114,-7" Grid.RowSpan="3" VerticalAlignment="Top" Width="114" Click="Button_Click"/>
    <Button x:Name="button02" Content="" HorizontalAlignment="Left" Height="82" Margin="228,0,-342,-7" Grid.RowSpan="3" VerticalAlignment="Bottom" Width="114" Click="Button_Click"/>
    <Button x:Name="button01" Content="" HorizontalAlignment="Left" Height="82" Margin="114,1,-228,-7" Grid.RowSpan="3" VerticalAlignment="Top" Width="114" Click="Button_Click" />
...
</Grid>

My on click is this

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    methodDoingStuff(button);
}

and i have tried to automate that computer could randomly click on of buttons. Like this

Random rnd = new Random();
int x = rnd.Next(2);
int y = rnd.Next(2);
Button btn = new Button();
btn.Name = "button" +(x.ToString() + y.ToString());
Button_Click(btn);

But i cant seem to able to do that. Any tips how i can do that kind of thing?


Solution

  • Try this:

    Button[] allButtons = grid.Children.OfType<Button>().ToArray();
    Random rnd = new Random();
    int x = rnd.Next(0, allButtons.Length);
    Button btn = allButtons[x];
    btn.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
    

    ...where "grid" is the x:Name of the Grid in your XAML:

    <Grid x:Name="grid" Margin="0,0,490,170"> ...