3

In Google Chrome I really like the functionality of the left mouse hold down on the Back button to get the full browse history.

In my WPF app: for a button with a context menu, how can I open the menu on hold down of the left mouse (and of course still with the regular right click)?

Reddog
  • 15,219
  • 3
  • 51
  • 63
  • Have a look at this: http://stackoverflow.com/questions/4428494/wpf-detect-mouse-down-for-a-set-period-of-time Its accepted answer is a lot better than that of this thread. – SepehrM Dec 06 '13 at 11:50

2 Answers2

3

I would suggest to handle the MouseDown event by starting a timer there. If the MouseUp event is fired, the timer needs to be stopped. You can use a DispatcherTimer for that. Then you can set up a time after that the Timer_Tick event should be fired, where you can perform the action you would like to perform. In order to avoid problems with the bubbling MouseDown and MouseUp events, I would suggest to add the two handlers in the window constructor instead of adding them in XAML (at least the events did not fire in my example code, so i changed that) by using

button1.AddHandler(FrameworkElement.MouseDownEvent, new MouseButtonEventHandler(button1_MouseDown), true);
button1.AddHandler(FrameworkElement.MouseUpEvent, new MouseButtonEventHandler(button1_MouseUp), true);

Additionally, you need to set up the timer there:

Add a field to the window class:

DispatcherTimer timer = new DispatcherTimer();

and set up the timer with the time you want to wait until the Timer_Tick event is fired (also in the window constructor):

timer.Tick += new EventHandler(timer_Tick);
// time until Tick event is fired
timer.Interval = new TimeSpan(0, 0, 1);

Then you only need to handle the events and you are done:

private void button1_MouseDown(object sender, MouseButtonEventArgs e) {
    timer.Start();
}

private void button1_MouseUp(object sender, MouseButtonEventArgs e) {
    timer.Stop();
}

void timer_Tick(object sender, EventArgs e) {
    timer.Stop();
    // perform certain action
}

Hope that helps.

Sören
  • 2,661
  • 2
  • 19
  • 22
0

I think your only way is to manually process MouseDown/Move/Up events over the button, wait for a certain amount of time to pass after MouseDown occured and if in this amount of time you don't have a MouseMove or MouseUp event, then manually show the ContextMenu. If you show the context menu, you'll have to take care for the button not to generate a Click event after that and to do it's default click action.

Andrei Pana
  • 4,484
  • 1
  • 26
  • 27