wpfbuttonevents

WPF application fails to handle several too quick button clicks


In a WPF C# application I have 2 buttons. If the user clicks the 1st button and then very quickly clicks the 2nd button, then only the click event handler of the 2nd button is invoked. Any WPF C# applocation with 2 buttons which have a click event handler each will do to show the problem.

Can anyone explain the phenomenon and suggest how can the 1st button event handler be invoked prior to the invocation of the 2nd?

I tried to serve 2 click events of 2 different buttons according to the actual clicking sequence. Yet, if only a very short period of time elapses between the clicks then only the second click button handler is invoked.


Solution

  • The problem is definitely not in two quick clicks on different buttons.

    All UI elements (not only in WPF, but also in Forms) work only synchronously in one thread - that's why the main thread of the application is often also called the UI thread. Processing the next click is not possible until the previous one is processed.

    Run this example in an empty project and everything will work fine:

        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <UniformGrid Columns="2">
                <Button Content="One" Click="OnOneClick" Margin="5" Padding="5"/>
                <Button Content="Two" Click="OnTwoClick" Margin="5" Padding="5"/>
            </UniformGrid>
            <TextBlock x:Name="tblock" Grid.Row="1" Margin="5"/>
            <x:Code>
                <![CDATA[
            private void OnOneClick(object sender, RoutedEventArgs e)
            {
                tblock.Text += "OnOneClick" + Environment.NewLine;
            }
    
            private void OnTwoClick(object sender, RoutedEventArgs e)
            {
                tblock.Text += "OnTwoClick" + Environment.NewLine;
            }
                ]]>
            </x:Code>
        </Grid>
    </Window>
    

    If I click the 2nd button very shortly after clicking the 1st button, the program doesn't arrive at the breakpoint.

    In my example, there is an output in TextBlock of the name of the called method. Have you managed to make such fast clicks that the output from the previous one is not recorded in TextBlock?

    I see the following possible reasons:

    1. You are using "not manual" button clicks. And it is this tool that automates the clicks that is causing the failure;
    2. You are using asynchrony somewhere, which you may not even know about;
    3. It is possible that this is a Debuger bug - it does not have time to trigger at the required breakpoint.