3

在 Google Chrome 中,我非常喜欢鼠标左键按住后退按钮以获取完整浏览历史记录的功能。

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

4

2 回答 2

3

我建议MouseDown通过在那里启动一个计时器来处理该事件。如果MouseUp事件被触发,则需要停止计时器。你可以使用 a 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
}

希望有帮助。

于 2011-02-25T12:16:10.467 回答
0

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

于 2011-02-25T11:54:09.173 回答