Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable expanding after doubleclick

Tags:

Is there any way I can disable expanding TreeNode after doubleclick??

Thanks

like image 288
arek Avatar asked Aug 08 '09 16:08

arek


2 Answers

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;
}

You can declare a private field isDoubleClick and set various TreeView events as above. This will prevent expand/collapse TreeView node on double click. However expand/collapse will work via + and - icons.

like image 92
Suniket Patel Avatar answered Sep 25 '22 10:09

Suniket Patel


There is no simple way to achieve this, as far as I know. One thought would be to have a bool variable set to true on the DoubleClick event, and use the e.Cancel property of the BeforeExpand event to prevent the node from expanding. However, those two events are fired in the opposite order, so that is not a solution. I don't have another solution from the top of my head; will update if I come up with one.

Update

I have played around with this a bit, and I have found one way that works reasonably well. As I have mentioned the problem is that BeforeExpand happens before DoubleClick, so we can't set any state in DoubleClick to use in BeforeExpand.

We can, however, detect (potential) double clicks in another way: by measuring the time between MouseDown events. If we get two MouseDown events within the time period that defines a double click (as stated in SystemInformation.DoubleClickTime), it should be a double click, right? And the MouseDown event is raised before BeforeExpand. So, the following code works rather well:

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;
}

I say "rather well" because I feel that it prevents the node from expanding in some cases when it should not (for instance if you within the double click time click first on the node text and then on the plus sign). That might be possible to solve in some way, or perhaps you can live with that.

like image 42
Fredrik Mörk Avatar answered Sep 23 '22 10:09

Fredrik Mörk