herohuyongtao
herohuyongtao

Reputation: 50667

How to determine which mouse button (e.g. LeftButton) is just released?

I can easily check which button is currently in the Pressed state or Released state. For example, to check if the LeftButton is currently released, I can use:

void mouse_event_handler(object sender, MouseButtonEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Released)
    {
        // left button is released
    }
}

My question is that: How can I determine which mouse button (e.g. LeftButton) has just recently changed its state from Pressed to Released? The above method will fail to determine this as it will also be true irrespective of which button, MiddleButton or RightButton, was previously released (i.e. it only check the current state). I am not sure C#/WPF natively support this. I want something like:

if (e.LeftButton == MouseButtonState.Just_Released)

P.S.: I know a way to work around by using an extra flag when the mouse button is down, and check this flag afterwards.

Upvotes: 2

Views: 1623

Answers (1)

Frederik Prijck
Frederik Prijck

Reputation: 1509

You can use the ChangedButton property of the MouseButtonEventArgs class

if (e.ChangedButton == MouseButton.Left)
{
    // Only occurs when the Left button is released
}

if (e.LeftButton == MouseButtonState.Released)
{
    // Occurs everytime a button is released (doesnt matter which one) AND the left mouse button is in released mode
}

More information: http://msdn.microsoft.com/en-us/library/system.windows.input.mousebuttoneventargs.changedbutton(v=vs.110).aspx

Upvotes: 5

Related Questions