WPF - Open ContextMenu with the left mouse button

In Google Chrome, I really like the functionality of the left mouse while holding down the back button to get the full browsing history.

In my WPF application: for a button with a context menu, how can I open the menu while holding the left mouse button (and, of course, still with the usual right-click)?

+3
source share
2 answers

I would suggest handling the event MouseDownby starting a timer there. If the event is MouseUpfired, the timer must be stopped. You can use DispatcherTimer. Then you can set the time after which the event should be Timer_Ticktriggered, where you can perform the action that you want to perform. To avoid problems with bubbling events MouseDownand MouseUpI would suggest adding two handlers to the window constructor instead of adding them to XAML (at least the events didn’t light up in my code example, so I changed this) using

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

In addition, you need to set up a timer there:

Add field to window class:

DispatcherTimer timer = new DispatcherTimer();

and set the timer with the time when you want to wait for the event Timer_Tick(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 need to process the events and everything will be 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
}

, .

+3

, - MouseDown/Move/Up , , MouseDown, MouseMove MouseUp , ContextMenu. , , Click .

0

Source: https://habr.com/ru/post/1794695/


All Articles