Hun*_*oul 15 wpf timer mouseclick-event
我必须处理单击和双击WPF应用程序中的按钮并进行不同的反应.不幸的是,在双击时,WPF会触发两次点击事件和双击事件,因此很难处理这种情况.
它试图用计时器解决它,但没有成功...我希望你能帮助我.
让我们看看代码:
private void delayedBtnClick(object statInfo)
{
if (doubleClickTimer != null)
doubleClickTimer.Dispose();
doubleClickTimer = null;
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new VoidDelegate(delegate()
{
// ... DO THE SINGLE CLICK ACTION
}));
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (doubleClickTimer == null)
doubleClickTimer = new Timer(delayedBtnClick, null, System.Windows.Forms.SystemInformation.DoubleClickTime, Timeout.Infinite);
}
}
}
private void btnNext_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (doubleClickTimer != null)
doubleClickTimer.Change(Timeout.Infinite, Timeout.Infinite); // disable it - I've tried it with and without this line
doubleClickTimer.Dispose();
doubleClickTimer = null;
//.... DO THE DOUBLE CLICK ACTION
}
Run Code Online (Sandbox Code Playgroud)
问题是双击时"双击"动作后的"单击动作".奇怪的是,我doubleClickTimer在双击时将delayedBtnClick其设置为null,但是它是真的:O
我已经尝试过更长的时间,一个布尔旗和锁......
你有什么想法?
最好!
rmo*_*ore 16
如果你在处理事件之后将RoutedEvent's 设置e.Handled为true,MouseDoubleClick那么它将不会Click在第二次之后调用事件MouseDoubleClick.
有一个最近的文章这倒是有不同的行为对SingleClick和DoubleClick这可能是有用的.
但是,如果您确定需要单独的行为并希望/需要阻止第一行Click和第二行Click,您可以使用DispatcherTimer您喜欢的行为.
private static DispatcherTimer myClickWaitTimer =
new DispatcherTimer(
new TimeSpan(0, 0, 0, 1),
DispatcherPriority.Background,
mouseWaitTimer_Tick,
Dispatcher.CurrentDispatcher);
private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// Stop the timer from ticking.
myClickWaitTimer.Stop();
Trace.WriteLine("Double Click");
e.Handled = true;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
myClickWaitTimer.Start();
}
private static void mouseWaitTimer_Tick(object sender, EventArgs e)
{
myClickWaitTimer.Stop();
// Handle Single Click Actions
Trace.WriteLine("Single Click");
}
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
Button.MouseLeftButtonDown += Button_MouseLeftButtonDown;
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
if (e.ClickCount > 1)
{
// Do double-click code
}
else
{
// Do single-click code
}
}
Run Code Online (Sandbox Code Playgroud)
如果需要,您可能需要单击鼠标并等待鼠标向上执行操作.