I'm trying to extend Button to add a RightClick event.
My customer wants a button to do different things depending on if you left-click or right-click. I expected there to be an easy event for right-clicking, but it turns out there's not.
I'd prefer Button's visual behavior to be identical to the preexisting Click event, but it's proving tough. Button has many graphical behaviors that occur when you click and drag on and off the button.
- When you click-down, the button lowers. If you drag off the lowered button, it raises (e.g. un-lowers). Any other buttons you drag over will ignore it.
- When you drag back on the original button, it will lower again.
- If you drag off and then release, the original button's state should reset (i.e. you can't reclick and drag on again).
These little graphical quirks will look rough if the left-click visuals don't match the right-click visuals.
Currently I'm stuck on this: If right-click and hold the button, then drag off the button, how do I detect if the user un-clicks? I need to know this so I can know not to re-lower the button on re-entry.
A broader question: Am I even on the right track? I couldn't find anyone who's done this before. My code is below.
public class RightClickButton : Button
{
public event RoutedEventHandler RightClick;
public RightClickButton()
{
this.MouseRightButtonDown += new System.Windows.Input.MouseButtonEventHandler(RightClickButton_MouseRightButtonDown);
this.MouseRightButtonUp += new System.Windows.Input.MouseButtonEventHandler(RightClickButton_MouseRightButtonUp);
this.MouseEnter += new System.Windows.Input.MouseEventHandler(RightClickButton_MouseEnter);
this.MouseLeave += new System.Windows.Input.MouseEventHandler(RightClickButton_MouseLeave);
}
void RightClickButton_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
this.IsPressed = true;
}
void RightClickButton_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
this.IsPressed = false;
if (RightClick != null)
RightClick.Invoke(this, e);
}
void RightClickButton_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
if (this.IsPressed)
this.IsPressed = false;
}
void RightClickButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
if (this.IsFocused && Mouse.RightButton == MouseButtonState.Pressed)
this.IsPressed = true;
}
}