2011-02-25 75 views
3

在谷歌浏览器中,我真的很喜欢按住“后退”按钮的左键功能,以获得完整的浏览历史记录。WPF - 用鼠标左键打开ContextMenu

在我的WPF应用程序中:对于具有上下文菜单的按钮,如何在按住鼠标左键的同时打开菜单(当然还有常规的右键单击)?

+0

看看这个:http://stackoverflow.com/questions/4428494/wpf-detect-mouse-down-for-a-set-period-of-time 它接受的答案比那更好这个线程。 – SepehrM 2013-12-06 11:50:03

回答

3

我建议通过在那里启动一个计时器来处理MouseDown事件。如果触发MouseUp事件,则需要停止计时器。你可以使用DispatcherTimer。然后,您可以设置一段时间,然后触发Timer_Tick事件,您可以在其中执行您希望执行的操作。为了避免冒泡MouseDownMouseUp事件的问题,我建议在窗口构造函数中添加两个处理程序,而不是在XAML中添加它们(至少事件并未在我的示例代码中触发,所以我改变了这一点)使用

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

此外,还需要设置定时器有:

一个字段添加到窗口类:

DispatcherTimer timer = new DispatcherTimer(); 

,并设置了要等待的时间计时器直到Timer_Tick事件被触发(也窗口构造函数):

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

然后你只需要处理的事件,和你做:

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 
} 

希望有所帮助。

0

我认为你唯一的方法就是在按钮上手动处理MouseDown/Move/Up事件,在MouseDown发生后等待一段时间,如果在这段时间内没有MouseMove或MouseUp事件,然后手动显示ContextMenu。如果您显示上下文菜单,那么您必须注意该按钮之后不要生成Click事件并执行默认的点击操作。