user9283382
user9283382

Reputation: 15

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?

Upvotes: 0

Views: 861

Answers (4)

Tibi.
Tibi.

Reputation: 1

I think this should work:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Random rnd = new Random();
    button00.Margin = new Thickness(rnd.Next((int)this.Width-(int)button00.Width),rnd.Next((int)this.Height-(int)button00.Height),0,0);
}

Upvotes: 0

Lucax
Lucax

Reputation: 407

You could just create an object list containing references to the buttons.

List<Button> buttonList = new List<Button> {button00, button01, button02};

Then do something like this:

Random rnd = new Random();
int selection = rnd.Next(0, 3);
buttonList[selection].RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

Upvotes: 0

vCillusion
vCillusion

Reputation: 1809

Try using below code:

Random rnd = new Random();
            int x = 0;
            int y = rnd.Next(2);
            var buttonName = "button" + (x.ToString() + y.ToString());
            var buttonControl = this.FindName(buttonName) as Button;
            if (buttonControl != null)
            {
                buttonControl.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, buttonControl));
            }

Upvotes: 0

mm8
mm8

Reputation: 169400

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"> ...

Upvotes: 3

Related Questions