Since this article is only a small (but hopefully a useful) delta to other Treeview articles, there is no project to download - it consists of only a few lines of code, and therefore should be very easy to integrate this feature into your own solution.
There are situations where you need to expand the
Treeview control's functionality. For example, you want to add Drag & Drop behaviour to your solution. To implement scrolling while dragging, many examples use the
TreeNode.EnsureVisible method. Whenever this method is called, the control scrolls to the right end of the node by default. Depending on the length of the node’s text, this has - in my eyes - the negative effect that most of the tree content is no longer visible! This article is about stopping the control from scrolling right.
The ‘key idea’ is to create a left scrolling method which is invoked right after the regular
EnsureVisible method. Left scrolling is implemented by a
SendMessage call. We need a couple of declarations for that:
private const int WM_HSCROLL = 276;
private const int SB_LEFT = 6;
private static extern int SendMessage(IntPtr hWnd, int wMsg,
int wParam, int lParam);
To keep it simple, we encapsulate the new feature in a new method (in all probability we could override the
TreeNode’s method as well).
private void EnsureVisibleWithoutRightScrolling(TreeNode node)
SendMessage(treeView1.Handle, WM_HSCROLL,SB_LEFT , 0);
In your own solution, you only have to replace the
EnsureVisible calls by the new call and you are done - no more right scrolling.
private void button1_Click(object sender, System.EventArgs e)
TreeNode node = new TreeNode("A very very very very large item");