When you drag and drop in a treeview control, you need to support some auto scroll functions. For example, when you drag an item from the visible node tree, and the node destination tree is outside the current tree view, the control should automatically scroll up or down depending on the direction of the mouse.
The Windows Forms Treeview control does not include built-in functions to accomplish this. However, it is quite easy to implement this on your own.
Step 1: Get Your Tree Tree Drag Code
Make sure your tree structure drag and drop code works correctly without autoscrolling. See Sections in this folder for more information on how to implement drag and drop in a tree structure.
Step 2: Add a SendMessage Function Definition
To scroll up or down the tree, you need to call the Windows API SendMessage () function. To do this, add the following code at the beginning of your class:
// Make sure you have the correct using clause to see DllImport: // using System.Runtime.InteropServices; [DllImport("user32.dll")] private static extern int SendMessage (IntPtr hWnd, int wMsg, int wParam, int lParam);
Step 3: Capturing the DragScroll Event
In the DragScroll event, determine where the mouse pointer is relative to the top and bottom of the treeview control. Then call SendMessage to scroll as appropriate.
// Implement an "autoscroll" routine for drag // and drop. If the drag cursor moves to the bottom // or top of the treeview, call the Windows API // SendMessage function to scroll up or down automatically. private void DragScroll ( object sender, DragEventArgs e) { // Set a constant to define the autoscroll region const Single scrollRegion = 20; // See where the cursor is Point pt = TreeView1.PointToClient(Cursor.Position); // See if we need to scroll up or down if ((pt.Y + scrollRegion) > TreeView1.Height) { // Call the API to scroll down SendMessage(TreeView1.Handle, (int)277, (int)1, 0); } else if (pt.Y < (TreeView1.Top + scrollRegion)) { // Call thje API to scroll up SendMessage(TreeView1.Handle, (int)277, (int)0, 0); }
Taken from here .