双击后禁用扩展

are*_*rek 16 .net c# winforms

有什么办法可以在doubleclick后禁用扩展TreeNode吗?

谢谢

小智 22

private bool isDoubleClick = false;

private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
    if (isDoubleClick && e.Action == TreeViewAction.Collapse)
        e.Cancel = true;
}

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    if (isDoubleClick && e.Action == TreeViewAction.Expand)
        e.Cancel = true;
}

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    isDoubleClick = e.Clicks > 1;
}
Run Code Online (Sandbox Code Playgroud)

您可以声明私有字段isDoubleClick并如上所述设置各种TreeView事件.这将阻止双击展开/折叠TreeView节点.但是,展开/折叠将通过+和 - 图标起作用.

  • 这应该是公认的答案,因为它不依赖于了解双击时间 (2认同)

Fre*_*örk 14

据我所知,没有简单的方法可以实现这一目标.一种想法是在DoubleClick事件上bool设置变量true,并使用事件的e.Cancel属性BeforeExpand来阻止节点扩展.但是,这两个事件是以相反的顺序触发的,因此这不是解决方案.我没有另外一个解决方案; 如果我拿出一个会更新.

更新

我已经玩了一下这个,我找到了一种工作得相当好的方法.正如我所提到的问题是BeforeExpand发生之前 DoubleClick,所以我们不能设置任何状态下DoubleClick才能使用BeforeExpand.

但是,我们可以通过另一种方式检测(潜在)双击:通过测量MouseDown事件之间的时间.如果我们MouseDown在定义双击的时间段内得到两个事件(如中所述SystemInformation.DoubleClickTime),则应该是双击,对吧?此MouseDown事件之前已经提出BeforeExpand.因此,以下代码运行良好:

private bool _preventExpand = false;
private DateTime _lastMouseDown = DateTime.Now;

private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    e.Cancel = _preventExpand;
    _preventExpand  = false;
}

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    int delta = (int)DateTime.Now.Subtract(_lastMouseDown).TotalMilliseconds;            
    _preventExpand = (delta < SystemInformation.DoubleClickTime);
    _lastMouseDown = DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)

我说"相当不错",因为我觉得它阻止节点在某些情况下不应该扩展(例如,如果你在双击时间内首先单击节点文本然后单击加号).这可能有可能以某种方式解决,或者也许你可以忍受.

  • 在MouseDown事件中,检查单击的位置是否在最后一个MouseDown位置的XY方向上的几个像素(可能是3-5)内.如果是这样,并且MouseDowns在阈值范围内,则双击. (2认同)
  • @KeithS:好的补充.如发生,存在距离的定义也:[SystemInformation.DoubleClickSize](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.doubleclicksize.aspx). (2认同)
  • 当使用传递给``MouseDown``事件处理程序的``MouseEventArgs``的``Clicks``属性时,检查鼠标按下事件之间的时间和像素增量将变得过时.此属性似乎是根据系统的双击配置设置的. (2认同)

Max*_*nce 5

MouseDown 事件将在 BeforeExpand/BeforeCollapse 事件之前发生。您可以检查 MouseEventArg 的 Clicks 属性来区分双击和单击:

bool dblClick;

private void treeView_MouseDown(object sender, MouseEventArgs e)
{
  dblClick = e.Button == MouseButtons.Left && e.Clicks == 2;
}

private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
  if (e.Action == TreeViewAction.Expand) e.Cancel = dblClick;
}
Run Code Online (Sandbox Code Playgroud)