WPF响应长按事件
程序员文章站
2022-06-08 22:23:26
...
思路:MouseDown 时启动一个线程并标记IsMouseDown=True,若MouseUp则修改标记IsMouseDown=False,线程内Sleep 1500ms之后判断IsMouseDown=True则开始响应事件
bool IsLeftMouseDown = false;
private void DataGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsLeftMouseDown = true;
Thread th = new Thread(new ThreadStart(() =>
{
Thread.Sleep(1500);
if (IsLeftMouseDown)
{
MessageBox.Show("长按了1.5秒");
IsLeftMouseDown = false;
}
else
{
MessageBox.Show("1.5秒内释放了点击");
}
}));
th.Start();
}
private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
IsLeftMouseDown = false;
}
以上的实现可以解决问题,但是有bug,以下提供更优的解决方案:
bool IsLeftMouseDown = false;
bool EntryTouch = false;
Thread th = null;
private void DataGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsLeftMouseDown = true;
if (th != null)
{
if (th.ThreadState == ThreadState.Running || th.ThreadState == ThreadState.WaitSleepJoin)
th.Abort();
}
th = new Thread(new ThreadStart(() =>
{
Thread.Sleep(1500);
if (IsLeftMouseDown)
{
EntryTouch = true;
MessageBox.Show("长按了1.5秒");
IsLeftMouseDown = false;
}
else
{
MessageBox.Show("1.5秒内释放了点击");
}
EntryTouch = false;
}));
th.Start();
}
private void DataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if(EntryTouch)
{
MessageBox.Show("已进入长按事件");
}
IsLeftMouseDown = false;
}