在 Google Chrome 中,我非常喜欢鼠标左键按住“后退”按钮以获取完整浏览历史记录的功能。
在我的 WPF 应用程序中:对于带有上下文菜单的按钮,如何在按住鼠标左键的同时打开菜单(当然仍然是常规的右键单击)?
最佳答案
我建议通过启动计时器来处理 MouseDown
事件。如果触发了 MouseUp
事件,则需要停止计时器。您可以使用 DispatcherTimer
为了那个原因。然后您可以设置一个时间,之后应该触发 Timer_Tick
事件,您可以在其中执行您想要执行的操作。为了避免冒泡的 MouseDown
和 MouseUp
事件出现问题,我建议在窗口构造函数中添加这两个处理程序,而不是在 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
}
希望对您有所帮助。
关于.net - WPF - 按住鼠标左键打开上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5116806/